python输入水果求个数问题_水果爱好者:用Python解决一个简单的分类问题
作者?| Ocktavia Nurima Putri
來源?| Medium
編輯?|?代碼醫(yī)生團隊
在這篇文章中,將使用Scikit-learn在Python中實現(xiàn)幾種機器學(xué)習(xí)算法。將使用一個簡單的數(shù)據(jù)集來訓(xùn)練分類器,以區(qū)分不同類型的水果。在數(shù)據(jù)科學(xué)中存在的每種方法中,希望比較不同的算法并選擇最適合的算法。
數(shù)據(jù)
水果數(shù)據(jù)集由愛丁堡大學(xué)的Iain Murray博士創(chuàng)建,然后密歇根大學(xué)的教授稍微格式化了水果數(shù)據(jù),可以從這里下載。
https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/fruit_data_with_colors.txt
%matplotlib?inline
import?pandas?as?pd
import?matplotlib.pyplot?as?plt
fruits?=?pd.read_table('fruit_data_with_colors.txt')
fruits.head()
圖1
在數(shù)據(jù)的前幾行中,數(shù)據(jù)集的每一行代表一個水果,由表格列中的幾個要素表示,如標(biāo)簽,名稱,子類型,質(zhì)量,寬度,高度和顏色。
通過下面的腳本,知道數(shù)據(jù)集中有59個水果和7個特征。
print(fruits.shape)
(59, 7)
然后,有四種水果。
print(fruits['fruit_name'].unique())
[‘a(chǎn)pple’ ‘mandarin’ ‘orange’ ‘lemon’]
通過下面的輸出,可以假設(shè)數(shù)據(jù)非常平衡,除了mandarin。
print(fruits.groupby('fruit_name').size())
圖2
import?seaborn?as?sns
sns.countplot(fruits['fruit_name'],label="Count")
plt.show()
圖3
可視化
每個數(shù)字變量的箱形圖將更清楚地了解輸入變量的分布:
fruits.drop('fruit_label',?axis=1).plot(kind='box',?subplots=True,?layout=(2,2),?sharex=False,?sharey=False,?figsize=(9,9),
title='Box?Plot?for?each?input?variable')
plt.savefig('fruits_box')
plt.show()
圖4
看起來顏色分?jǐn)?shù)可能接近高斯分布。
import?pylab?as?pl
fruits.drop('fruit_label'?,axis=1).hist(bins=30,?figsize=(9,9))
pl.suptitle("Histogram?for?each?numeric?input?variable")
plt.savefig('fruits_hist')
plt.show()
圖5
一些屬性對是相關(guān)的(質(zhì)量和寬度)。這表明高度相關(guān)性和可預(yù)測的關(guān)系。
from?pandas.tools.plotting?import?scatter_matrix
from?matplotlib?import?cm
feature_names?=?['mass',?'width',?'height',?'color_score']
X?=?fruits[feature_names]
y?=?fruits['fruit_label']
cmap?=?cm.get_cmap('gnuplot')
scatter?=?pd.scatter_matrix(X,?c?=?y,?marker?=?'o',?s=40,?hist_kwds={'bins':15},?figsize=(9,9),?cmap?=?cmap)
plt.suptitle('Scatter-matrix?for?each?input?variable')
plt.savefig('fruits_scatter_matrix')
圖6
統(tǒng)計摘要
圖7
可以看到數(shù)值不具有相同的比例。需要將縮放應(yīng)用于為訓(xùn)練集計算的測試集。
創(chuàng)建訓(xùn)練和測試集并應(yīng)用縮放
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.preprocessing?import?MinMaxScaler
scaler?=?MinMaxScaler()
X_train?=?scaler.fit_transform(X_train)
X_test?=?scaler.transform(X_test)
構(gòu)建模型
Logistic回歸
from?sklearn.linear_model?import?LogisticRegression
logreg?=?LogisticRegression()
logreg.fit(X_train,?y_train)
print('Accuracy?of?Logistic?regression?classifier?on?training?set:?{:.2f}'
.format(logreg.score(X_train,?y_train)))
print('Accuracy?of?Logistic?regression?classifier?on?test?set:?{:.2f}'
.format(logreg.score(X_test,?y_test)))
Logistic回歸分類器在訓(xùn)練集上的準(zhǔn)確度:0.70
Logistic回歸分類器在測試集上的準(zhǔn)確度:0.40
決策樹
from?sklearn.tree?import?DecisionTreeClassifier
clf?=?DecisionTreeClassifier().fit(X_train,?y_train)
print('Accuracy?of?Decision?Tree?classifier?on?training?set:?{:.2f}'
.format(clf.score(X_train,?y_train)))
print('Accuracy?of?Decision?Tree?classifier?on?test?set:?{:.2f}'
.format(clf.score(X_test,?y_test)))
訓(xùn)練集
上決策樹分類器的準(zhǔn)確度:1.00
測試集上決策樹分類器的準(zhǔn)確度:0.73
K-Nearest Neighbors
from?sklearn.neighbors?import?KNeighborsClassifier
knn?=?KNeighborsClassifier()
knn.fit(X_train,?y_train)
print('Accuracy?of?K-NN?classifier?on?training?set:?{:.2f}'
.format(knn.score(X_train,?y_train)))
print('Accuracy?of?K-NN?classifier?on?test?set:?{:.2f}'
.format(knn.score(X_test,?y_test)))
訓(xùn)練集上K-NN分類器的準(zhǔn)確度:0.95
測試集上K-NN分類器的準(zhǔn)確度:1.00
線性判別分析
from?sklearn.discriminant_analysis?import?LinearDiscriminantAnalysis
lda?=?LinearDiscriminantAnalysis()
lda.fit(X_train,?y_train)
print('Accuracy?of?LDA?classifier?on?training?set:?{:.2f}'
.format(lda.score(X_train,?y_train)))
print('Accuracy?of?LDA?classifier?on?test?set:?{:.2f}'
.format(lda.score(X_test,?y_test)))
LDA分類器在訓(xùn)練集上的準(zhǔn)確度:0.86
LDA分類器在測試集上的準(zhǔn)確度:0.67
高斯樸素貝葉斯
from?sklearn.naive_bayes?import?GaussianNB
gnb?=?GaussianNB()
gnb.fit(X_train,?y_train)
print('Accuracy?of?GNB?classifier?on?training?set:?{:.2f}'
.format(gnb.score(X_train,?y_train)))
print('Accuracy?of?GNB?classifier?on?test?set:?{:.2f}'
.format(gnb.score(X_test,?y_test)))
GNB分類器對訓(xùn)練集的準(zhǔn)確度:0.86
GNB分類器在測試集上的準(zhǔn)確度:0.67
支持向量機
from?sklearn.svm?import?SVC
svm?=?SVC()
svm.fit(X_train,?y_train)
print('Accuracy?of?SVM?classifier?on?training?set:?{:.2f}'
.format(svm.score(X_train,?y_train)))
print('Accuracy?of?SVM?classifier?on?test?set:?{:.2f}'
.format(svm.score(X_test,?y_test)))
SVM分類器在訓(xùn)練集上的準(zhǔn)確度:0.61
測試集上SVM分類器的準(zhǔn)確度:0.33
KNN算法是嘗試過的最準(zhǔn)確的模型。混淆矩陣提供了對測試集沒有錯誤的指示。但是,測試集非常小。
from?sklearn.metrics?import?classification_report
from?sklearn.metrics?import?confusion_matrix
pred?=?knn.predict(X_test)
print(confusion_matrix(y_test,?pred))
print(classification_report(y_test,?pred))
圖7
繪制k-NN分類器的決策邊界
import?matplotlib.cm?as?cm
from?matplotlib.colors?import?ListedColormap,?BoundaryNorm
import?matplotlib.patches?as?mpatches
import?matplotlib.patches?as?mpatches
X?=?fruits[['mass',?'width',?'height',?'color_score']]
y?=?fruits['fruit_label']
X_train,?X_test,?y_train,?y_test?=?train_test_split(X,?y,?random_state=0)
def?plot_fruit_knn(X,?y,?n_neighbors,?weights):
X_mat?=?X[['height',?'width']].as_matrix()
y_mat?=?y.as_matrix()
#?Create?color?maps
cmap_light?=?ListedColormap(['#FFAAAA',?'#AAFFAA',?'#AAAAFF','#AFAFAF'])
cmap_bold??=?ListedColormap(['#FF0000',?'#00FF00',?'#0000FF','#AFAFAF'])
clf?=?neighbors.KNeighborsClassifier(n_neighbors,?weights=weights)
clf.fit(X_mat,?y_mat)
#?Plot?the?decision?boundary?by?assigning?a?color?in?the?color?map
#?to?each?mesh?point.
mesh_step_size?=?.01??#?step?size?in?the?mesh
plot_symbol_size?=?50
x_min,?x_max?=?X_mat[:,?0].min()?-?1,?X_mat[:,?0].max()?+?1
y_min,?y_max?=?X_mat[:,?1].min()?-?1,?X_mat[:,?1].max()?+?1
xx,?yy?=?np.meshgrid(np.arange(x_min,?x_max,?mesh_step_size),
np.arange(y_min,?y_max,?mesh_step_size))
Z?=?clf.predict(np.c_[xx.ravel(),?yy.ravel()])
#?Put?the?result?into?a?color?plot
Z?=?Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx,?yy,?Z,?cmap=cmap_light)
#?Plot?training?points
plt.scatter(X_mat[:,?0],?X_mat[:,?1],?s=plot_symbol_size,?c=y,?cmap=cmap_bold,?edgecolor?=?'black')
plt.xlim(xx.min(),?xx.max())
plt.ylim(yy.min(),?yy.max())
patch0?=?mpatches.Patch(color='#FF0000',?label='apple')
patch1?=?mpatches.Patch(color='#00FF00',?label='mandarin')
patch2?=?mpatches.Patch(color='#0000FF',?label='orange')
patch3?=?mpatches.Patch(color='#AFAFAF',?label='lemon')
plt.legend(handles=[patch0,?patch1,?patch2,?patch3])
plt.xlabel('height?(cm)')
plt.ylabel('width?(cm)')
plt.title("4-Class?classification?(k?=?%i,?weights?=?'%s')"
%?(n_neighbors,?weights))
plt.show()
plot_fruit_knn(X_train,?y_train,?5,?'uniform')
圖8
k_range?=?range(1,?20)
scores?=?[]
for?k?in?k_range:
knn?=?KNeighborsClassifier(n_neighbors?=?k)
knn.fit(X_train,?y_train)
scores.append(knn.score(X_test,?y_test))
plt.figure()
plt.xlabel('k')
plt.ylabel('accuracy')
plt.scatter(k_range,?scores)
plt.xticks([0,5,10,15,20])
圖9
對于這個特定的日期集,當(dāng)k = 5時,獲得最高的準(zhǔn)確度。
結(jié)論
在這篇文章中,關(guān)注預(yù)測的準(zhǔn)確性。目標(biāo)是確定最適合手頭問題的機器學(xué)習(xí)算法。因此比較了不同的算法并選擇了性能最佳的算法。
源代碼:
https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Solving%20A%20Simple%20Classification%20Problem%20with%20Python.ipynb
關(guān)于圖書
《深度學(xué)習(xí)之TensorFlow:入門、原理與進階實戰(zhàn)》和《Python帶我起飛——入門、進階、商業(yè)實戰(zhàn)》兩本圖書是代碼醫(yī)生團隊精心編著的 AI入門與提高的精品圖書。配套資源豐富:配套視頻、QQ讀者群、實例源碼、 配套論壇:http://bbs.aianaconda.com。更多請見:aianaconda.com
點擊“閱讀原文”配套圖書資源
總結(jié)
以上是生活随笔為你收集整理的python输入水果求个数问题_水果爱好者:用Python解决一个简单的分类问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开卡工本费要扣几次
- 下一篇: python格式化代码工具_python