訪問UCI機器學習數據集為實驗進行數據支撐。該數據集包含隨訪期間收集的29 9名心力衰竭患者的病歷,其中每個患者檔案有 13 個臨床特征。目標為死亡事件:患者是否在隨訪期間死亡。
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score,roc_curve, auc
# 將數據集劃分為訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 特征標準化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 創建邏輯回歸模型
model = LogisticRegression()
# 訓練模型
model.fit(X_train, y_train)
# 在測試集上進行預測
y_pred = model.predict(X_test)
# 計算準確度
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')
# 預測并計算性能指標(如AUC)
y_pred_proba = model.predict_proba(X_test)[:, 1]
fpr, tpr, _ = roc_curve(y_test, y_pred_proba)
roc_auc_nb = auc(fpr,tpr)
使用 scikit-learn 實現邏輯回歸模型,包括數據集劃分、特征標準化、模型訓練、準確度計算以及通過 ROC 曲線計算 AUC 等步驟,用于解決二分類問題。
from sklearn.metrics import classification_report, confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
# 輸出混淆矩陣
confusion_matrix = confusion_matrix(y_test, y_pred)
plt.figure(figsize = (6, 6), dpi = 300)
sns.heatmap(confusion_matrix, annot = True, annot_kws = {'size':15}, fmt = 'd', cmap = 'YlGnBu_r')
# 繪制熱力圖 annot = True熱力圖上顯示數值,annot_kws設置單元格數值標簽的其他屬性,fmt指定單元格數據顯示格式cmap用于熱力圖填色
plt.title('混淆矩陣熱力圖')
plt.xlabel('預測值')
plt.ylabel('真實值')
plt.show()
使用scikit-learn庫評估分類模型的性能。它根據預測值(y_pred
)和真實標簽(y_test
)生成混淆矩陣。通過seaborn和matplotlib,將混淆矩陣可視化為熱力圖,直觀展示模型在預測不同類別方面的表現。
# 繪制ROC曲線
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc_nb)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC曲線')
plt.legend(loc="lower right")
plt.show()
繪制二分類模型的ROC曲線(Receiver Operating Characteristic)。ROC曲線是一種用于評估分類模型性能的圖形工具,它以真正例率(True Positive Rate,又稱為靈敏度或召回率)為縱軸,假正例率(False Positive Rate)為橫軸,展示了在模型的性能,ROC曲線越靠近左上角,模型性能越好。
# 輸出模型報告, 查看評價指標
print(classification_report(y_test, y_pred))
邏輯回歸分類模型的性能報告,報告中包含了針對每個類別(在這里是0和1)的精確度(precision)、召回率(recall)、F1分數(f1-score)以及支持數量(support)。下面是對這些指標的簡要解釋:
總體而言,這個模型對類別0的性能較好(高精確度和高召回率),但對類別1的性能稍顯下降。
本文章轉載微信公眾號@Python機器學習AI