python葡萄酒数据集_利用python分析红葡萄酒数据
在本次分析中,我使用了隨機(jī)森林回歸,并涉及數(shù)據(jù)標(biāo)準(zhǔn)化和超參數(shù)調(diào)優(yōu)。在這里,我使用隨機(jī)森林分類器,對(duì)好酒和不太好的酒進(jìn)行二元分類。
首先導(dǎo)入數(shù)據(jù)包:
importnumpy as npimportpandas as pdimportmatplotlib.pyplot as pltimport seaborn as sns
導(dǎo)入數(shù)據(jù):
data = pd.read_csv(‘winequality-red.csv‘)
data.head()
data.describe()
注釋:
fixed acidity:非揮發(fā)性酸
volatile acidity :?揮發(fā)性酸
citric acid:檸檬酸
residual sugar :剩余糖分
chlorides:氯化物
free sulfur dioxide :游離二氧化硫
total sulfur dioxide:總二氧化硫
density:密度
pH:pH
sulphates:硫酸鹽
alcohol:酒精
quality:質(zhì)量
所有數(shù)據(jù)的數(shù)值為1599,所以沒有缺失值。讓我們看看是否有重復(fù)值:
extra =data[data.duplicated()]
extra.shape
有240個(gè)重復(fù)值,但先不刪除它,因?yàn)槠咸丫频馁|(zhì)量等級(jí)是由不同的品酒師給出的。
數(shù)據(jù)可視化
sns.set()
data.hist(figsize=(10,10), color=‘red‘)
plt.show()
只有質(zhì)量是離散型變量,主要集中在5和6中,下面分析下變量的相關(guān)性:
colormap =plt.cm.viridis
plt.figure(figsize=(12,12))
plt.title(‘Correlation of Features‘, y=1.05, size=15)
sns.heatmap(data.astype(float).corr(),linewidths=0.1,vmax=1.0, square=True,
linecolor=‘white‘, annot=True)
觀察:
酒精與葡萄酒質(zhì)量的相關(guān)性最高,其次是各種酸度、硫酸鹽、密度和氯化物。
使用分類器:
將葡萄酒分成兩組;“優(yōu)質(zhì)”>5為“好酒”
y = data.quality #set ‘quality‘ as target
X = data.drop(‘quality‘, axis=1) #rest are features
print(y.shape, X.shape) #check correctness
#Create a new y1
y1 = (y > 5).astype(int)
y1.head()
# plot histogram
ax= y1.plot.hist(color=‘green‘)
ax.set_title(‘Wine quality distribution‘, fontsize=14)
ax.set_xlabel(‘a(chǎn)ggregated target value‘)
利用隨機(jī)森林分類器訓(xùn)練預(yù)測(cè)模型
from sklearn.model_selection importtrain_test_split, cross_val_scorefrom sklearn.ensemble importRandomForestClassifierfrom sklearn.metrics importaccuracy_score, log_lossfrom sklearn.metrics import confusion_matrix
將數(shù)據(jù)分割為訓(xùn)練和測(cè)試數(shù)據(jù)集
seed = 8 #set seed for reproducibility
X_train, X_test, y_train, y_test = train_test_split(X, y1, test_size=0.2,
random_state=seed)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
對(duì)隨機(jī)森林分類器進(jìn)行交叉驗(yàn)證訓(xùn)練和評(píng)價(jià)
#Instantiate the Random Forest Classifier
RF_clf = RandomForestClassifier(random_state=seed)
RF_clf
#在訓(xùn)練數(shù)據(jù)集上計(jì)算k-fold交叉驗(yàn)證,并查看平均精度得分
cv_scores = cross_val_score(RF_clf,X_train, y_train, cv=10, scoring=‘a(chǎn)ccuracy‘)print(‘The accuracy scores for the iterations are {}‘.format(cv_scores))print(‘The mean accuracy score is {}‘.format(cv_scores.mean()))
執(zhí)行預(yù)測(cè)
RF_clf.fit(X_train, y_train)
pred_RF= RF_clf.predict(X_test)
#Print 5 results to see
for i in range(0,5):print(‘Actual wine quality is‘, y_test.iloc[i], ‘a(chǎn)nd predicted is‘, pred_RF[i])
在前五名中,有一個(gè)錯(cuò)誤。讓我們看看指標(biāo)。
print(accuracy_score(y_test, pred_LR))print(log_loss(y_test, pred_LR))
print(confusion_matrix(y_test, pred_LR))
總共有81個(gè)分類錯(cuò)誤。
與Logistic回歸分類器相比,隨機(jī)森林分類器更優(yōu)。
讓我們調(diào)優(yōu)隨機(jī)森林分類器的超參數(shù)
from sklearn.model_selection importGridSearchCV
grid_values= {‘n_estimators‘:[50,100,200],‘max_depth‘:[None,30,15,5],‘max_features‘:[‘a(chǎn)uto‘,‘sqrt‘,‘log2‘],‘min_samples_leaf‘:[1,20,50,100]}
grid_RF= GridSearchCV(RF_clf,param_grid=grid_values,scoring=‘a(chǎn)ccuracy‘)
grid_RF.fit(X_train, y_train)
grid_RF.best_params_
除了估計(jì)數(shù)之外,其他推薦值是默認(rèn)值。
RF_clf = RandomForestClassifier(n_estimators=100,random_state=seed)
RF_clf.fit(X_train,y_train)
pred_RF=RF_clf.predict(X_test)print(accuracy_score(y_test,pred_RF))print(log_loss(y_test,pred_RF))
print(confusion_matrix(y_test,pred_RF))
通過超參數(shù)調(diào)諧,射頻分類器的準(zhǔn)確度已提高到82.5%,日志損失值也相應(yīng)降低。分類錯(cuò)誤的數(shù)量也減少到56個(gè)。
將隨機(jī)森林分類器作為基本推薦器,將紅酒分為“推薦”(6級(jí)以上)或“不推薦”(5級(jí)以下),預(yù)測(cè)準(zhǔn)確率為82.5%似乎是合理的。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python葡萄酒数据集_利用python分析红葡萄酒数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 参数化 c_MySQL(16
- 下一篇: python 线程 的类库_python