가장 대표적으로 많이 사용하는 상관계수!
(왼쪽 그래프)
🫡 선형적인 관계가 예상 될 때 사용(비선형적일 때는 사용 불가🔥)
<예시 코드>
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import pearsonr
# 예시 데이터 생성
np.random.seed(0)
study_hours = np.random.rand(100) * 10
exam_scores = 3 * study_hours + np.random.randn(100) * 5
# 데이터프레임 생성
df = pd.DataFrame({'Study Hours': study_hours, 'Exam Scores': exam_scores})
# 피어슨 상관계수 계산
pearson_corr, _ = pearsonr(df['Study Hours'], df['Exam Scores'])
print(f"피어슨 상관계수: {pearson_corr}")
# 상관관계 히트맵 시각화
sns.heatmap(df.corr(), annot=True, cmap='coolwarm', vmin=-1, vmax=1)
plt.title('pearson coefficient heatmap')
plt.show()
데이터가 정규분포를 따르지 않을 때 사용하는 상관계수!
(가운데, 오른쪽 그래프)
🌝 1. 데이터의 분포에 대한 가정을 하지 못할 때
🌝 2. 순서형 데이터에서도 사용하고 싶을 때
<예시 코드>
from scipy.stats import spearmanr, kendalltau
# 예시 데이터 생성
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})
# 스피어만 상관계수 계산
spearman_corr, _ = spearmanr(df['Customer Satisfaction'], df['Repurchase Intent'])
print(f"스피어만 상관계수: {spearman_corr}")
# 켄달의 타우 상관계수 계산
kendall_corr, _ = kendalltau(df['Customer Satisfaction'], df['Repurchase Intent'])
print(f"켄달의 타우 상관계수: {kendall_corr}")
# 상관관계 히트맵 시각화
sns.heatmap(df.corr(method='spearman'), annot=True, cmap='coolwarm', vmin=-1, vmax=1)
plt.title('spearman coefficient heatmap')
plt.show()
상호정보를 이용한 변수끼리의 상관계수 계산!
🌞 1. 두 변수가 범주형 변수일 때
🌞 2. 비선형적이고 복잡한 관계를 탐지하고자 할 때
import numpy as np
from sklearn.metrics import mutual_info_score
# 범주형 예제 데이터
X = np.array(['cat', 'dog', 'cat', 'cat', 'dog', 'dog', 'cat', 'dog', 'dog', 'cat'])
Y = np.array(['high', 'low', 'high', 'high', 'low', 'low', 'high', 'low', 'low', 'high'])
# 상호 정보량 계산
mi = mutual_info_score(X, Y)
print(f"Mutual Information (categorical): {mi}")
우연히 결과가 나오는 것이 아닌, 항상 일관된 결과가 나오는지 확인해야 함!
☑️ 실험 조건을 동일하게 조성하기 어려움
☑️ 가설검정 사용방법에 있어서 잘못됨
인위적으로 p-값을 낮추지 않을 수 있도록 조심해야 함!
🫵🏻 여러 가설 검정을 시도 할 때
말 그대로 선택적으로 보고하는 것!
☑️ 유의미한 결과만 공개 할 때
☑️ 결과를 보면서 가설을 다시 새로 설정했는데 마치 처음부터 설정한 가설이라고 얘기할 때
원하는 결과가 나올 때 까지 자료를 수집하는 것을 조심!
🔥 결과를 이미 정해놓고 그에 맞추기 위해 자료수집을 하고자 할 때
<예시 코드>
# 데이터 수집 예시
np.random.seed(42)
data = np.random.normal(0, 1, 1000)
sample_sizes = [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
p_values = []
for size in sample_sizes:
sample = np.random.choice(data, size)
_, p_value = stats.ttest_1samp(sample, 0)
p_values.append(p_value)
# p-값 시각화
plt.plot(sample_sizes, p_values, marker='o')
plt.axhline(y=0.05, color='red', linestyle='dashed', linewidth=1)
plt.title('자료수집 중단 시점에 따른 p-값 변화')
plt.xlabel('샘플 크기')
plt.ylabel('p-값')
plt.show()
🫡 검증하기 위한 데이터는 반드시 따로 분리 해놓아야 함!
👊🏻 검증하기 위한 데이터가 따로 필요할 때
<예시 코드>
from sklearn.model_selection import train_test_split
# 데이터 생성
np.random.seed(42)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
# 데이터 분할 (탐색용 80%, 검증용 20%)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 모델 학습
model = LinearRegression()
model.fit(X_train, y_train)
# 탐색용 데이터로 예측
y_train_pred = model.predict(X_train)
# 검증용 데이터로 예측
y_test_pred = model.predict(X_test)
# 탐색용 데이터 평가
train_mse = mean_squared_error(y_train, y_train_pred)
train_r2 = r2_score(y_train, y_train_pred)
print(f"탐색용 데이터 - MSE: {train_mse}, R2: {train_r2}")
# 검증용 데이터 평가
test_mse = mean_squared_error(y_test, y_test_pred)
test_r2 = r2_score(y_test, y_test_pred)
print(f"검증용 데이터 - MSE: {test_mse}, R2: {test_r2}")