数据链接:FE_pima-indians-diabetes.csv · biabianm/pima-indians-diabetes -
import pandas as pdfrom sklearn.model_selection import train_test_split # 数据分离from sklearn.linear_model import LogisticRegression # 逻辑回归模型from sklearn import metrics # 准确率评估path = f"../FE_pima-indians-diabetes.csv"def confusion_matrix_test():"""pima 印第安人糖尿病混淆矩阵分析:return:"""pima = pd.read_csv(path)print(pima.columns.values)# x,y赋值feature_names = ['pregnants', 'serum_insulin', 'BMI', 'Age']x = pima[feature_names]y = pima['Target']# 维度确认print(x.shape)print(y.shape)# 数据分离x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=0)# 模型训练logreg = LogisticRegression()logreg.fit(x_train, y_train)# 基于测试数据集结果预测y_pred = logreg.predict(x_test)# 使用准确率进行评估print(metrics.accuracy_score(y_test, y_pred))# 确认自负样本数据量print(y_test.value_counts())# 1的比例print(y_test.mean())# 0的比例print(1 - y_test.mean())# 空准确率print(max(y_test.mean(), 1 - y_test.mean()))# 单独准确率评估局限性大# 混淆矩阵实现# 计算展示混淆矩阵print(metrics.confusion_matrix(y_test, y_pred))# 展示部分实际结果与预测结果(25组)print("true", y_test.values[0:25])print("pred", y_pred[0:25])# 四个因子赋值confusion = metrics.confusion_matrix(y_test, y_pred)TN = confusion[0, 0]FP = confusion[0, 1]FN = confusion[1, 0]TP = confusion[1, 1]print(TN, FP, FN, TP)# 混淆矩阵指标# 准确率accuracy = (TP + TN) / (TP + TN + FP + FN)print(accuracy)print(metrics.accuracy_score(y_test, y_pred))# 错误率mis_rate = (FP + FN) / (TP + TN + FP + FN)print(mis_rate)print(1 - accuracy)# 灵敏度(召回率:正样本中,预测正确的比例)recall = TP / (TP + FN)print(recall)# 特异度:负样本中,预测正确的比例specificity = TN / (TN + FP)print(specificity)# 精确率:预测结果为正的样本中,预测正确的比例precision = TP / (TP + FP)print(precision)# F1分数:综合Precision和Recall的一个判断指标f1_recall = 2 * precision * recall / (precision * recall)print(f1_recall)if __name__ == '__main__':confusion_matrix_test()
如果觉得《sklearn 混淆矩阵分析pima 印第安人糖尿病数据》对你有帮助,请点赞、收藏,并留下你的观点哦!