1. 程式人生 > >sklearn訓練感知器用iris數據集

sklearn訓練感知器用iris數據集

proc load %d gre 通過 lin tro 感知 misc

簡化版代碼

 1 from sklearn import datasets
 2 import numpy as np
 3 
 4 #獲取data和類標
 5 iris = datasets.load_iris()
 6 X = iris.data[:,[2,3]]
 7 y = iris.target
 8 
 9 #測試樣本和訓練樣本三七分
10 from sklearn.model_selection import train_test_split
11 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=0)
12 13 #數據特征標準化 14 from sklearn.preprocessing import StandardScaler 15 sc = StandardScaler() 16 sc.fit(X_train) 17 X_test_std = sc.transform(X_test) 18 X_train_std = sc.transform(X_train) 19 20 #訓練感知器模型 21 from sklearn.linear_model import Perceptron 22 ppn = Perceptron(max_iter=40,eta0=0.1,random_state=0)
23 ppn.fit(X_train_std,y_train) 24 25 #訓練完成後,對測試數據進行預測 26 y_pred = ppn.predict(X_test_std) 27 print(Missclassified samples:%d%(y_pred!=y_test).sum()) 28 from sklearn.metrics import accuracy_score 29 print(Accuracy:%.2f%accuracy_score(y_test,y_pred))

解釋版+可視化

from sklearn import datasets#iris已包含在sklearn庫中
import numpy as np iris = datasets.load_iris() #提取150個花朵樣本中的花瓣長度和花瓣寬度兩個特征的值,並由此構建特征矩陣X,同時將對應花朵所屬類型的類標賦值給向量y #打印出來iris可以發現iris包括的key包括五個值:data(其中有四列)、target、target_name、DESCR、feature_names #X提取的是data裏面的3、4列,y提取的是target,即類型的類標 #print(iris) #print(iris.keys()) #print(iris.data.shape) #print(iris.data[:5])#顯示樣本前五行,因為iris是字典不是列表,所以不能調用head()的方法獲取前五行 X = iris.data[:, [2, 3]] y = iris.target#iris的每個樣本都包含了品種信息,即目標屬性(第5列,也叫target或label) ‘‘‘如果執行np.unique(y)返回存儲在iris.target中的各類花朵的類標,可以看到,scikit-learn已分別將Iris-Sentosa、Iris-Versicolor 和Iris-Virginia的類名另存為整數(0,1,2),對許多機器學習庫來說,這是針對性能優化一種推薦的做法 print(np.unique(y)) ‘‘‘ ‘‘‘ 為了評估訓練得到的模型在未知數據上的表現,我們進一步將數據集劃分為訓練數據集和測試數據集 使用scikit-learn中model_selection模塊中的train_test_split函數,隨機將數據矩陣X與類標向量y按照3:7的比例劃分為測試數據集( 45個樣本)和訓練數據集(105個樣本) ‘‘‘ from sklearn.model_selection import train_test_split X_train, X_test, y_train,y_test = train_test_split(X, y, test_size=0.3, random_state=0) ‘‘‘ 許多機器學習和優化算法都要求對數據做特征縮放。我們將使用scikit-learn的preprocessing模塊中的StandardScaler類 對特征進行標準化處理 在下面的代碼中,從preprocessing模塊中加載了StandardScaler類,並實例化了一個StandScaler對象,用變量sc作為對它的引用 使用StandardScaler中的fit方法,可以計算訓練數據中的每個特征的μ(樣本均值)和σ(標準差)。通過調用transform方法, 可以使用前面計算得到的μ和σ來對訓練數據做標準化處理。註意:需要使用相同的縮放參數分別處理訓練和測試數據。 ‘‘‘ from sklearn.preprocessing import StandardScaler sc = StandardScaler() sc.fit(X_train) X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) ‘‘‘ 在對訓練數據做了標準化處理後,下面訓練感知器模型 ‘‘‘ from sklearn.linear_model import Perceptron ppn = Perceptron(max_iter=40, eta0=0.1, random_state=0)#n_iter是叠代次數,eta是學習速率,random_state參數在每次叠代後初始化重新排練數據集 ppn.fit(X_train_std, y_train) ‘‘‘ 使用scikit-learn完成模型的訓練後,就可以在測試數據集上使用predict方法進行預測了 ‘‘‘ y_pred = ppn.predict(X_test_std)#predict class labels for samples in X print(Misclassified samples:%d%(y_test != y_pred).sum()) ‘‘‘ 計算感知器在測試數據集上的分類準確率 ‘‘‘ from sklearn.metrics import accuracy_score print(Accuracy:%.2f % accuracy_score(y_test,y_pred)) ‘‘‘ 使用plot_decision_regions函數來繪制剛剛訓練過得模型的決策區域,並觀察不同花朵樣本的分類項 ‘‘‘ from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt def plot_decision_regions(X,y,classifier,test_idx = None,resolution = 0.02): #setup marker generator and color map markers = (s, x, o, ^, v) colors = (red, blue, lightgreen, gray, cyan) cmap = ListedColormap(colors[:len(np.unique(y))]) #plot the decision surface x1_min, x1_max = X[:, 0].min()-1, X[:, 0].max()+1 x2_min, x2_max = X[:, 0].min()-1, X[:, 1].max()+1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) #plot all samples X_test,y_test = X[test_idx, :], y[test_idx] for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl) #highlight test samples if test_idx: X_test, Y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0],X_test[:, 1], c=‘‘, alpha=1.0, linewidth=1, marker=o, s=55, label=test set) X_combined_std = np.vstack((X_train_std, X_test_std)) Y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X=X_combined_std, y=Y_combined, classifier=ppn, test_idx=range(105, 150)) plt.xlabel(petal length [standardized]) plt.ylabel(petal width [standardized]) plt.legend(loc=upper left) print(plt.show())

自己手動註釋

技術分享圖片技術分享圖片技術分享圖片

sklearn訓練感知器用iris數據集