# 导包
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Perceptron
from sklearn.linear_model import SGDClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix# 生成用来记录评价指标的dataframe kpi
cols_list=['ACC','TPR','TNR']
kpi=pd.DataFrame(columns=cols_list)# 多个机器学习模型
logreg = LogisticRegression()
svc = SVC()
linear_svc = LinearSVC()
knn = KNeighborsClassifier(n_neighbors = 3)
gaussian = GaussianNB()
decision_tree = DecisionTreeClassifier()
random_forest = RandomForestClassifier(n_estimators=100) # 构造树的个数ways=[logreg,svc,linear_svc,knn,gaussian,decision_tree,random_forest]# 预测
for way in ways:way.fit(X_train, Y_train)Y_pred = way.predict(X_test)# 通过混淆矩阵计算评价指标TP=confusion_matrix(Y_test,Y_pred)[0][0]FN=confusion_matrix(Y_test,Y_pred)[0][1]FP=confusion_matrix(Y_test,Y_pred)[1][0]TN=confusion_matrix(Y_test,Y_pred)[1][1]new=pd.DataFrame(columns=cols_list,index=[str(way)])new['ACC']=round(way.score(X_test, Y_test) * 100, 2)new['TPR']=TP/(TP+FN) # 灵敏度new['TNR']=TN/(FP+TN) # 特异度kpi=kpi.append(new,ignore_index=False)