1.掌握常见机器学习分类模型思想、算法,包括Fisher线性判别、KNN、朴素贝叶斯、Logistic回归、决策树等;
2.掌握Python编程实现分类问题,模型评价指标、计时功能、保存模型。
实验步骤
1、读入数据
2、数据预处理
3、数据分析方法介绍
4、编程实现数据分析方法,含代码注释
5、重要结果的图表绘制
6、必要的结果解释
利用Fisher线性判别分类器计算下面的问题,要求报告模型评价指标、计时功能、保存模型。
为了防止出现假冒伪劣、逃避关税情况,某海关单位已有以往化验检测2个原产地的葡萄酒样品124个,现有6个未知类别样本葡萄酒需要确定来源地,如何制定检验策略对6个未知样本原产地进行甄别?利用所学分类算法探讨此问题,要求进行模型评价、增加计时功能、保存模型。数据见 data_wine_new.csv.
0 1 分别对应1 2原产地
# -*- coding: utf-8 -*-
'''step1 调用包'''
import time
starttime = time.time()
import pandas as pd
import numpy as np
from sklearn import discriminant_analysis
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score #调用准确率计算函数
from sklearn import metrics
from sklearn.metrics import confusion_matrix,classification_report
'''step2 导入数据'''
data = pd.read_csv('data_wine_new.csv')
'''step3 数据预处理'''
# 把带类标号数据(用于训练和检验)
# 和待判(最后3行)数据分开
data_used = data.iloc[:124,:]
#Python从0开始计数,故上一行代码从第0行取到第114行
#共提取了115行。
data_unused = data.iloc[124:,:]
'''step4 划分数据集'''
#(将带类标号数据
#划分为训练集(75%)
#和检验集(25%)
#将类别列和特征列拆分,
#便于下面调用划分函数
y_data=data_used.iloc[:,0]
x_data=data_used.iloc[:,1:]
#调用sklearn中的函数划分上述数据
x_train, x_test, y_train, y_test = train_test_split(
x_data,y_data,test_size=0.25,random_state=0)
'''step5 模型计算(训练、检验、评价)'''
#step5.1 训练模型
lda_fisher = discriminant_analysis.LinearDiscriminantAnalysis()
lda_fisher.fit(x_train, y_train)
print('\n 判别函数系数:xi系数:\n',np.round(lda_fisher.coef_,2))
print('\n判别函数系数:截距:\n' ,np.round(lda_fisher.intercept_,2))
#step5.2 检验模型
pred_test = lda_fisher.predict(x_test)
#step5.3 模型评价(准确率)
#这里y_test为真实检验集类标号
#pred_test为模型预测的检验集类标号
#比较二者即可得到准确率
# acc_test = accuracy_score(y_test,pred_test)
# print('检验准确率为:',acc_test)
'''模型评价 升级版'''
accuracy_score = accuracy_score(y_test,pred_test)
confusion_matrix = confusion_matrix(y_test,pred_test,labels=[0,1])
classification_report = classification_report(y_test,pred_test,labels=[0,1], target_names=["1号原产地","2号原产地"])
classification_report_split=classification_report.split () #提取矩阵中的值
# auc = auc(best_estimator, X_train, X_test)
##计算AUC
# from sklearn import metrics
from itertools import cycle
colors = cycle('gmcr')
if hasattr(lda_fisher, 'predict_proba'):
y_score = lda_fisher.predict_proba(x_test)
y_score=y_score[:,1]
else:
y_score = lda_fisher.decision_function(x_test)
fpr, tpr, thresholds = metrics.roc_curve(y_test, y_score)
auc = metrics.auc(fpr, tpr)
# print('\n AUC is:',auc)
endtime = time.time()
testtime = endtime-starttime
print('\n confusion_matrix = \n',confusion_matrix)
print('\n classification_report =\n', classification_report)
print('\n accuracy_score= ',accuracy_score)
print('\n precison= ',metrics.precision_score(y_test, pred_test))
print('\n recall= ',metrics.recall_score(y_test, pred_test))
print('\n f1_Score= ',metrics.f1_score(y_test, pred_test))
# print('\n auc of train/test =', auc )
print('\n AUC is:',auc)
print("\n Time consuming is",testtime)
'''step6 模型存储'''
import joblib
joblib.dump(lda_fisher,'model_Fisher.m') #保存模型
'''step7 预测结果'''
#模型训练完,检验效果满意
#未知类别进行预测(分类)
x_unused = data_unused.iloc[:,1:]
pred_unused = lda_fisher.predict(x_unused)
print('待判样本预测类别为:',pred_unused)
判别函数系数:xi系数:
[[-4.22 -0.94 -7.94 0.92 -0.02 2.89 -2.19 -0.09 1.99 0.06 -0.91 -5.49
-0.02]]
判别函数系数:截距:
[85.44]
confusion_matrix =
[[16 0]
[ 0 15]]
classification_report = | precision | recall | f1-score | support |
---|---|---|---|---|
1号原产地 | 1.00 | 1.00 | 1.00 | 16 |
2号原产地 | 1.00 | 1.00 | 1.00 | 15 |
accuracy | 1.00 | 31 | ||
macro avg | 1.00 | 1.00 | 1.00 | 31 |
weighted avg | 1.00 | 1.00 | 1.00 | 31 |
accuracy_score= 1.0
precison= 1.0
recall= 1.0
f1_Score= 1.0
AUC is: 1.0
Time consuming is 0.025928735733032227
待判样本预测类别为: [1. 1. 1. 0. 0. 0.]