sklearn各種分類器簡單使用
阿新 • • 發佈:2018-02-09
iris targe tro fit 簡單 red port style res
sklearn中有很多經典分類器,使用非常簡單:1.導入數據 2.導入模型 3.fit--->predict
下面的示例為在iris數據集上用各種分類器進行分類:
1 #用各種方式在iris數據集上數據分類 2 3 #載入iris數據集,其中每個特征向量有四個維度,有三種類別 4 from sklearn import datasets 5 iris = datasets.load_iris() 6 print ("The iris‘ target names: ",iris.target_names) 7 x = iris.data 8 y = iris.target9 10 #待分類的兩個樣本 11 test_vector = [[1,-1,2.6,-2],[0,0,7,0.8]] 12 13 #線性回歸 14 from sklearn import linear_model 15 linear = linear_model.LinearRegression() 16 linear.fit(x,y) 17 print ("linear‘s score: ",linear.score(x,y)) 18 print ("w:",linear.coef_) 19 print ("b:",linear.intercept_) 20 print ("predict: ",linear.predict(test_vector)) 21 22 #邏輯回歸 23 LR = linear_model.LogisticRegression() 24 LR.fit(x,y) 25 print ("LogisticRegression:",LR.predict(test_vector)) 26 27 #決策樹 28 from sklearn import tree 29 TR = tree.DecisionTreeClassifier(criterion=‘entropy‘) 30 TR.fit(x,y) 31 print ("DecisionTree:",TR.predict(test_vector)) 32 33 #支持向量機 34 from sklearn import svm 35 SV = svm.SVC() 36 SV.fit(x,y) 37 print ("svm:",SV.predict(test_vector)) 38 39 #樸素貝葉斯 40 from sklearn import naive_bayes 41 NB = naive_bayes.GaussianNB() 42 NB.fit(x,y) 43 print ("naive_bayes:",NB.predict(test_vector)) 44 45 #K近鄰 46 from sklearn import neighbors 47 KNN = neighbors.KNeighborsClassifier(n_neighbors = 3) 48 KNN.fit(x,y) 49 print ("KNeighbors:",KNN.predict(test_vector)) 50 ‘‘‘ 51 he iris‘ target names: [‘setosa‘ ‘versicolor‘ ‘virginica‘] 52 linear‘s score: 0.930422367533 53 w: [-0.10974146 -0.04424045 0.22700138 0.60989412] 54 b: 0.192083994828 55 predict: [-0.50300167 2.26900897] 56 LogisticRegression: [1 2] 57 DecisionTree: [1 2] 58 svm: [2 2] 59 naive_bayes: [2 2] 60 KNeighbors: [0 1] 61 ‘‘‘
sklearn各種分類器簡單使用