ピアソン相関分析&プロット描画(相関係数ヒストグラム、非null値の数のヒストグラム描画)
1. ピアソン相関分析
- ピアソン相関分析は、2 つの変数間の線形関係の強さを検出するために使用される統計手法であり、結果は -1 から 1 までの間になります。相関係数 1 は完全な正の関係を示し、-1 は完全な負の関係を示し、0 は線形関係がないことを示します。ピアソン相関分析は、データが正規分布から得られ、外れ値の影響を受けやすいことを前提としています。
2. ピアソン相関分析の例
def calculate_pearsonr(pd):
head = pd.head().columns.values
GDM = pd["目标变量"].tolist()
coefficient_of_association = {
}
significance_level = {
}
feature_cnt = {
}
for feature in head:
if feature != "目标变量":
ftc = 0
feature_values = pd[feature].tolist()
GDM_temp, feature_temp, tag = [], [], 0
for v in feature_values:
if str(v) != "nan":
ftc += 1
GDM_temp.append(GDM[tag])
feature_temp.append(v)
tag += 1
feature_cnt[feature] = ftc
if len(feature_temp) > 1:
pc = pearsonr(np.array(feature_temp), np.array(GDM_temp))
if str(pc[0]) != "nan":
ca = pc[0]
if ca < -0.0001:
ca = ca*-1
coefficient_of_association[feature] = ca
significance_level[feature] = pc[1]
elif ca > 0.0001:
coefficient_of_association[feature] = ca
significance_level[feature] = pc[1]
dp_ca = sorted(
coefficient_of_association.items(),
key=lambda x: x[1],
reverse=True)
print("pearsonr-相关系数:",dp_ca)
dp_ca_Nempty=[(i[0], feature_cnt[i[0]]) for i in dp_ca]
print("非空值的数量:",dp_ca_Nempty)
return dp_ca
import matplotlib.pyplot as plt
def plot1(dp_ca):
dp_ca_dict = dict(dp_ca)
fig = plt.figure(figsize=(16, 10))
ax = fig.add_subplot(1, 1, 1)
ax.bar(dp_ca_dict.keys(), dp_ca_dict.values())
ax.set_title('Correlation between Feature and 目标变量')
ax.set_xlabel('Features')
ax.set_ylabel('Correlation Coefficient')
plt.xticks(rotation=45,ha='right')
ax.tick_params(axis='x', labelsize=10)
plt.tight_layout()
plt.savefig("./Pearson.jpeg")
plt.show()
if __name__ == '__main__':
file = pd.read_excel("./filename.xlsx")
dp_ca=calculate_pearsonr(file)
plot1(dp_ca)
3.プロット描画(相関係数ヒストグラム、非null値の数のヒストグラム描画)
import matplotlib.pyplot as plt
dp_ca = [('feature1', 0.8), ('feature2', 0.6), ('feature3', 0.4),('feature4', 0.77), ('feature5', 0.2), ('feature6', 0.4)]
dp_ca_Nempty = [('feature1', 100), ('feature3', 50), ('feature2', 20),('feature4', 70), ('feature5', 10), ('feature6', 26)]
dp_ca_dict = dict(dp_ca)
dp_ca_Nempty_dict = dict(dp_ca_Nempty)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].bar(dp_ca_dict.keys(), dp_ca_dict.values())
axs[0].set_title('Pearson correlation coefficients')
axs[0].set_xlabel('Features')
axs[0].set_ylabel('Correlation coefficient')
axs[1].bar(dp_ca_Nempty_dict.keys(), dp_ca_Nempty_dict.values())
axs[1].set_title('Number of non-empty values')
axs[1].set_xlabel('Features')
axs[1].set_ylabel('Count')
plt.xticks(rotation=45,ha='right')
axs[0].tick_params(axis='x', labelsize=10)
axs[1].tick_params(axis='x', labelsize=10)
plt.tight_layout()
plt.show()