
使用這些基本 REST API 最佳實踐構建出色的 API
通過整合皮爾遜相關系數及其顯著性水平(p值)、散點圖結合線性回歸擬合線及置信區間、以及對角線的單變量直方圖,用一個矩陣可視化全面展示數據特征間的相關性和分布趨勢
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
import seaborn as sns
warnings.filterwarnings("ignore")
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['axes.unicode_minus'] = False
df = pd.read_excel('2024-12-4-公眾號Python機器學習AI.xlsx')
# 計算皮爾遜相關系數矩陣
corr = df.corr()
plt.figure(figsize=(10, 8))
# 使用 Seaborn 繪制熱圖
sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm", square=True, cbar_kws={"shrink": .8})
plt.title("Correlation Matrix Heatmap")
plt.savefig("Correlation Matrix Heatmap.pdf", format='pdf', bbox_inches='tight', dpi=1200)
plt.show()
這是一個基礎的熱圖繪制,通過計算數據框的皮爾遜相關系數矩陣,利用Seaborn庫的heatmap函數可視化各特征間的相關性,熱圖通過顏色深淺直觀展示相關性強弱,是分析特征間關系的簡單且常用的方法
plt.figure(figsize=(8, 6))
plt.scatter(df["Variable_1"], df["Variable_2"], alpha=0.7, edgecolor='k')
plt.title("Scatter Plot of Variable_1 vs Variable_2", fontsize=14)
plt.xlabel("Variable_1", fontsize=12)
plt.ylabel("Variable_2", fontsize=12)
plt.grid(alpha=0.3)
plt.savefig("1.pdf", format='pdf', bbox_inches='tight', dpi=1200)
plt.show()
通過plt.scatter() 繪制了一個基礎散點圖,展示df[“Variable_1”]和df[“Variable_2”]之間的關系,直觀反映數據的分布情況。為了進一步分析,可以在此基礎上利用statsmodels庫擬合線性模型,添加擬合線和置信區間,以可視化兩變量之間的線性趨勢及其統計可靠性,從而實現更深入的數據洞察
import statsmodels.api as sm
# 擬合線性模型
X = sm.add_constant(df["Variable_1"]) # 添加常數項以適應截距
model = sm.OLS(df["Variable_2"], X).fit() # 使用最小二乘法擬合
predictions = model.get_prediction(X) # 獲取預測結果
confidence_intervals = predictions.conf_int(alpha=0.05) # 獲取95%置信區間
# 為擬合線生成 x 和 y 值
x_values = np.linspace(df["Variable_1"].min(), df["Variable_1"].max(), 100)
X_pred = sm.add_constant(x_values)
predicted_means = model.predict(X_pred)
conf_int_pred = model.get_prediction(X_pred).conf_int()
# 繪制散點圖和擬合線
plt.figure(figsize=(8, 6))
plt.scatter(df["Variable_1"], df["Variable_2"], alpha=0.7, edgecolor='k', label="Data Points") # 數據點
plt.plot(x_values, predicted_means, color='red', label=f"Fit Line: y = {coefficients[0]:.2f}x + {coefficients[1]:.2f}") # 擬合線
# 繪制置信區間
plt.fill_between(
x_values,
conf_int_pred[:, 0], # 置信區間下界
conf_int_pred[:, 1], # 置信區間上界
color='blue',
alpha=0.2,
label="95% Confidence Interval"
)
plt.title("Scatter Plot of Variable_1 and Variable_2 with Fit Line and Confidence Interval", fontsize=14)
plt.xlabel("Variable_1", fontsize=12)
plt.ylabel("Variable_2", fontsize=12)
plt.grid(alpha=0.3)
plt.legend(fontsize=10, loc='best')
plt.savefig("3.pdf", format='pdf', bbox_inches='tight', dpi=1200)
plt.show()
通過擬合線性模型繪制散點圖、擬合線以及95%的置信區間,展示Variable_1和Variable_2之間的線性關系及其統計可靠性
接下來,可以將這邏輯整合到相關系數熱圖中:上三角保留相關系數熱圖和顯著性標記,下三角繪制散點圖并疊加擬合線和置信區間,對角線保留特征的分布直方圖,實現全面分析特征間的關系
構建一個帶有多種形式可視化的相關系數可視化,用于全面分析數據特征之間的關系,對角線展示每個特征的直方圖和核密度估計 (KDE),直觀反映單變量的分布形態;下三角繪制散點圖并疊加線性擬合線及95%置信區間,呈現特征間的線性趨勢和統計置信度;上三角顯示皮爾遜相關系數熱圖,通過顏色深淺和數字注釋量化特征間的相關性強弱。
增強對特征間線性關系可靠性的統計檢驗解讀,使得相關性分析更具科學性和直觀性