1、使用 sklearn处理wine和wine_quality数据集
(1)训练要点:
(2)需求说明:
wine数据集和 wine_quality数据集是两份和酒有关的数据集。wine数据集包含3种
同起源的葡萄酒的记录,共178条。其中,每个特征对应葡萄酒的每种化学成分,并且都属于连续型数据。通过化学分析可以推断葡萄酒的起源。
wine_quality数据集共有4898个观察值,11个输入特征和一个标签。其中,不同类的
观察值数量不等,所有特征为连续型数据。通过酒的各类化学成分,预测该葡萄酒的评分。
需求说明:wine数据集的葡萄酒总共分为3种,通过将wine数据集的数据进行聚类,聚集为3个簇,能够实现葡萄酒的类别划分。
答:
##使用sklearn处理wine和wine_quality数据集
import pandas as pd
#1、读取数据集
wine = pd.read_csv('./第六章 实验数据/实训数据/wine.csv')
#winequality = pd.read_csv('./第六章 实验数据test/实训数据/winequality.csv')
winequality = pd.read_csv('./第六章 实验数据/实训数据/winequality.csv',sep = ';')
#2、数据和标签拆分开
wine_data=wine.iloc[:,1:]
wine_target=wine['Class']
winequality_data=winequality.iloc[:,:-1]
winequality_target=winequality['quality']
#winequality_target=winequality.iloc[:,-1]
#3、划分训练集和测试集
from sklearn.model_selection import train_test_split
wine_data_train, wine_data_test, \
wine_target_train, wine_target_test = \
train_test_split(wine_data, wine_target, \
test_size=0.1, random_state=6)
winequality_data_train, winequality_data_test, \
winequality_target_train, winequality_target_test = \
train_test_split(winequality_data, winequality_target, \
test_size=0.1, random_state=6)
#4、标准化数据集
from sklearn.preprocessing import StandardScaler #标准差标准化
stdScale = StandardScaler().fit(wine_data_train) #生成规则(建模)
wine_trainScaler = stdScale.transform(wine_data_train)#对训练集进行标准化
wine_testScaler = stdScale.transform(wine_data_test)#用训练集训练的模型对测试集标准化
stdScale = StandardScaler().fit(winequality_data_train)
winequality_trainScaler = stdScale.transform(winequality_data_train)
winequality_testScaler = stdScale.transform(winequality_data_test)
#5、PCA降维
from sklearn.decomposition import PCA
pca = PCA(n_components=5).fit(wine_trainScaler)
wine_trainPca = pca.transform(wine_trainScaler)
wine_testPca = pca.transform(wine_testScaler)
pca = PCA(n_components=5).fit(winequality_trainScaler)
winequality_trainPca = pca.transform(winequality_trainScaler)
winequality_testPca = pca.transform(winequality_testScaler)
2、答
#实训2:构建基于wine数据集的K-Means聚类模型
#从实训2开始需要基于前面的数据处理部分
#1、根据实训1的wine数据集处理的结果,构建聚类数目为3的 K-Means模型
from sklearn.cluster import KMeans
#用标准化后的训练集建模
kmeans = KMeans(n_clusters = 3,random_state=1).fit(wine_trainScaler)
#用标准化后PCA降维后的训练集建模(采用降维后的数据聚类效果不好,故此处不采用)
#kmeans = KMeans(n_clusters = 3,random_state=1).fit(wine_trainPca)
print('构建的KMeans模型为:\n',kmeans)
#2、对比真实标签和聚类标签求取FMI
from sklearn.metrics import fowlkes_mallows_score #FMI评价法
score=fowlkes_mallows_score(wine_target_train,kmeans.labels_)
print("wine数据集的FMI:%f"%(score))
#3、在聚类数目为2~10类时,确定最优聚类数目
for i in range(2,11):
##构建并训练模型
kmeans = KMeans(n_clusters = i,random_state=123).fit(wine_trainScaler)
score = fowlkes_mallows_score(wine_target_train,kmeans.labels_)
print('iris数据聚%d类FMI评价分值为:%f' %(i,score))
#4、求取模型的轮廓系数,绘制轮廓系数折线图,确定最优聚类数目
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
silhouettteScore = []
for i in range(2,11):
##构建并训练模型
kmeans = KMeans(n_clusters = i,random_state=1).fit(wine)
score = silhouette_score(wine,kmeans.labels_)
silhouettteScore.append(score)
plt.figure(figsize=(10,6))
plt.plot(range(2,11),silhouettteScore,linewidth=1.5, linestyle="-")
plt.show()
#5、求取 Calinski-Harabasz指数,确定最优聚类数
from sklearn.metrics import calinski_harabaz_score
for i in range(2,11):
##构建并训练模型
kmeans = KMeans(n_clusters = i,random_state=1).fit(wine)
score = calinski_harabaz_score(wine,kmeans.labels_)
print('seeds数据聚%d类calinski_harabaz指数为:%f'%(i,score))
3、答:
#实训3:构建基于wine数据集的SVM分类模型
#(1)读取wine数据集,区分标签和数据
import pandas as pd
wine = pd.read_csv("D:/ly/desk/数据/1124实验数据/实验数据/wine.csv")
wine_data=wine.iloc[:,1:]
wine_target=wine['Class']
#(2)将wine数据集划分为训练集和测试集
from sklearn.model_selection import train_test_split
wine_data_train, wine_data_test, \
wine_target_train, wine_target_test = \
train_test_split(wine_data, wine_target, \
test_size=0.1, random_state=6)
#(3)使用离差标准化方法标准化wine数据集。
from sklearn.preprocessing import MinMaxScaler #标准差标准化
stdScale = MinMaxScaler().fit(wine_data_train) #生成规则(建模)
wine_trainScaler = stdScale.transform(wine_data_train)#对训练集进行标准化
wine_testScaler = stdScale.transform(wine_data_test)#用训练集训练的模型对测试集标准化
#(4)构建SVM模型,并预测测试集结果。
from sklearn.svm import SVC
svm = SVC().fit(wine_trainScaler,wine_target_train)
print('建立的SVM模型为:\n',svm)
wine_target_pred = svm.predict(wine_testScaler)
print('预测前10个结果为:\n',wine_target_pred[:10])
#(5)打印出分类报告,评价分类模型性能
from sklearn.metrics import classification_report
print('使用SVM预测iris数据的分类报告为:','\n',
classification_report(wine_target_test,
wine_target_pred))
4、答:
#实训4:构建基于 wine quality数据集的回归模型
#(1)根据wine_quality数据集处理的结果,构建线性回归模型。
from sklearn.linear_model import LinearRegression
clf = LinearRegression().fit(winequality_trainPca,winequality_target_train)
y_pred = clf.predict(winequality_testPca)
print('线性回归模型预测前10个结果为:','\n',y_pred[:10])
#(2)根据wine_quality数据集处理的结果,构建梯度提升回归模型。
from sklearn.ensemble import GradientBoostingRegressor
GBR_wine = GradientBoostingRegressor().\
fit(winequality_trainPca,winequality_target_train)
wine_target_pred = GBR_wine.predict(winequality_testPca)
print('梯度提升回归模型预测前10个结果为:','\n',wine_target_pred[:10])
print('真实标签前十个预测结果为:','\n',list(winequality_target_test[:10]))
#(3)结合真实评分和预测评分,计算均方误差、中值绝对误差、可解释方差值。
#(4)根据得分,判定模型的性能优劣
print('线性回归模型评价结果:')
print('winequality数据线性回归模型的平均绝对误差为:',
mean_absolute_error(winequality_target_test,y_pred))
print('winequality数据线性回归模型的均方误差为:',
mean_squared_error(winequality_target_test,y_pred))
print('winequality数据线性回归模型的中值绝对误差为:',
median_absolute_error(winequality_target_test,y_pred))
print('winequality数据线性回归模型的可解释方差值为:',
explained_variance_score(winequality_target_test,y_pred))
print('winequality数据线性回归模型的R方值为:',
r2_score(winequality_target_test,y_pred))
print('梯度提升回归模型评价结果:')
from sklearn.metrics import explained_variance_score,\
mean_absolute_error,mean_squared_error,median_absolute_error,r2_score
print('winequality数据梯度提升回归树模型的平均绝对误差为:',
mean_absolute_error(winequality_target_test,wine_target_pred))
print('winequality数据梯度提升回归树模型的均方误差为:',
mean_squared_error(winequality_target_test,wine_target_pred))
print('winequality数据梯度提升回归树模型的中值绝对误差为:',
median_absolute_error(winequality_target_test,wine_target_pred))
print('winequality数据梯度提升回归树模型的可解释方差值为:',
explained_variance_score(winequality_target_test,wine_target_pred))
print('winequality数据梯度提升回归树模型的R方值为:',
r2_score(winequality_target_test,wine_target_pred))