[업무 지식]/Statistics
[비모수상관계수] 상관관계
에디터 윤슬
2024. 11. 12. 16:18
비모수 상관계수
- 데이터가 정규분포를 따르지 않거나 변수들이 순서형 데이터일 때 사용하는 상관계수
- 데이터의 분포에 대한 가정 없이 두 변수 간의 상관관계를 측정할 때 사용
- 대표적으로 스피어만 상관계수와 켄달의 타우 상관계수가 있음
스피어만 상관계수
- 두 변수의 순위 간의 일관성을 측정
- 켄달의 타우 상관계수보다 데이터 내 편차와 에러에 민간
from scipy.stats import spearmanr
# 예시 데이터 생성
np.random.seed(0)
customer_satisfaction = np.random.rand(100)
repurchase_intent = 3 * customer_satisfaction + np.random.randn(100) * 0.5
# 데이터프레임 생성
df = pd.DataFrame({'Customer Satisfaction': customer_satisfaction, 'Repurchase Intent': repurchase_intent})
df
# 스피어만 상관계수 계산
spearman_corr, _ = spearmanr(df['Customer Satisfaction'], df['Repurchase Intent'])
print(f"스피어만 상관계수: {spearman_corr}")
스피어만 상관계수: 0.8663546354635462
spearmanr: 두 연속형 변수 간의 스피어만 순위 상관계수(Spearman Correlation Coefficient)를 계산하는 함수입니다.
출력된 스피어만 상관계수는 약 0.87로, 이는 고객 만족도와 재구매 의도 간에 강한 양의 순위 기반 상관 관계가 있음을 의미합니다.
# 상관관계 히트맵 시각화
sns.heatmap(df.corr(method='spearman'), annot=True, cmap='coolwarm', vmin=-1, vmax=1)
plt.title('spearman coefficient heatmap')
plt.show()
켄달의 타우 상관계수
- 순위 간의 일치 쌍 및 불일치 쌍의 비율을 바탕으로 계산
- 예를들어 사람의 키와 몸무게에 대해 상관계수를 알고자 할 때 키가 크고 몸무게도 더 나가면 일치 쌍에 해당, 키가 크지만 몸무게가 더 적으면 불일치 쌍에 해당 이들의 개수 비율로 상관계수를 결정
from scipy.stats import kendalltau
# 켄달의 타우 상관계수 계산
kendall_corr, _ = kendalltau(df['Customer Satisfaction'], df['Repurchase Intent'])
print(f"켄달의 타우 상관계수: {kendall_corr}")
켄달의 타우 상관계수: 0.6690909090909092
kendalltau: 두 연속형 변수 간의 켄달의 타우(Kendall's Tau)를 계산하는 함수입니다.
출력된 켄달의 타우 값은 약 0.67로, 이는 고객 만족도와 재구매 의도 간에 강한 순위 기반 관계가 있음을 나타냅니다.
# 켄달의 타우 상관관계 히트맵 시각화
sns.heatmap(df.corr(method='kendall'), annot=True, cmap='coolwarm', vmin=-1, vmax=1)
plt.title('Kendall Tau Correlation Coefficient Heatmap')
plt.show()