第一步:先进行数据预处理
#数据预处理
import pandas as pd
path = 'C:/Users/詹鹏程/Desktop/python/机器学习/diabetes.csv'
pima = pd.read_csv(path)
pima.head()
#查看是否正确读入
#print(pima)
#用x,y进行赋值
feature_names = ['Pregnancies','Insulin','BMI','Age']
x = pima[feature_names]
y = pima.Outcome
#确认维度
print(x.shape)
print(y.shape)
运行结果:
第二步:进行数据分离和基本的一些操作
#数据分离
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y,random_state=0)
#模型训练
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(x_train,y_train)
#基于测试数据集结果预测
y_pred = logreg.predict(x_test)
#使用准确率进行评估
from sklearn import metrics
print(metrics.accuracy_score(y_test,y_pred))
#确认正负样本的数据量
print(y_test.value_counts())
#1的比例
y_test.mean()
#0的比例
1-y_test.mean()
#空准确率
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)/(TN+FP+FN+TP)
print(Accuracy)
print(metrics.accuracy_score(y_test,y_pred))
#错误率
mis_rate = (FP+FN)/(TN+FP+FN+TP)
print(mis_rate)
print(1-metrics.accuracy_score(y_test,y_pred))
#灵敏度(召回率)
recall = TP/(TP+FN)
print(recall)
#特异度
specificity = TN/(TN+FP)
print(specificity)
#精确度
precision = TP/(TP+FP)
print(precision)
#F1_Score分数
F1_Score = (2*precision*recall)/(recall+precision)
print(F1_Score)
输出结果:
混淆矩阵的基本定义:
TP = True Postive :预测准确,实际为正样本的数量
FP = False Positive :预测错误,实际为负样本的数量
FN = False Negative :预测错误,实际为正样本的数量
TN = True Negative :预测准确,实际为负样本的数量
混淆指标: