python使用自帶SVM,資料集iris
阿新 • • 發佈:2018-12-26
轉至:https://www.cnblogs.com/luyaoblog/p/6775342.html
和Python3不是很相容,改了一部分
import numpy as np from sklearn import svm import matplotlib as mpl import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split %matplotlib inline def iris_type(s): it = {b'Iris-setosa':0,b'Iris-versicolor':1, b'Iris-virginica':2} #Python2和3有點區別 return it[s] #print(iris_type('Iris-setosa')) path = u'C:/Users/Administrator/Desktop/iris/iris.data' data = np.loadtxt(path, dtype = float, delimiter = ',', converters = {4:iris_type}) #data x, y = np.split(data, (4,), axis = 1) x = x[:, :2] x_train, x_test, y_train, y_test = train_test_split(x, y, random_state = 1, test_size = 0.39) clf = svm.SVC(C = 0.8, kernel = 'rbf', gamma = 20) #呼叫svm.svc clf.fit(x_train, y_train.ravel()) print (clf.score(x_train, y_train)) # 精度 y_hat = clf.predict(x_train) #show_accuracy(y_hat, y_train, '訓練集') print (clf.score(x_test, y_test)) y_hat = clf.predict(x_test) #show_accuracy(y_hat, y_test, '測試集') #print ('decision_function:\n', clf.decision_function(x_train)) #每一列的值代表到各類別的距離 print ('\npredict:\n', clf.predict(x_train)) x1_min, x1_max = x[:, 0].min(), x[:, 0].max() # 第0列的範圍 x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 第1列的範圍 x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j] # 生成網格取樣點 grid_test = np.stack((x1.flat, x2.flat), axis=1) # 測試點 grid_hat = clf.predict(grid_test) # 預測分類值 grid_hat = grid_hat.reshape(x1.shape) # 使之與輸入的形狀相同 mpl.rcParams['font.sans-serif'] = [u'SimHei'] mpl.rcParams['axes.unicode_minus'] = False cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF']) cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b']) plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light) plt.scatter(x[:, 0], x[:, 1], c=np.squeeze(y), edgecolors='k', s=50, cmap=cm_dark) # 樣本 , c=y是錯的 plt.scatter(x_test[:, 0], x_test[:, 1], s=120, facecolors='none', zorder=10) # 圈中測試集樣本 plt.xlabel(u'花萼長度', fontsize=13) plt.ylabel(u'花萼寬度', fontsize=13) plt.xlim(x1_min, x1_max) plt.ylim(x2_min, x2_max) plt.title(u'鳶尾花SVM二特徵分類', fontsize=15) # plt.grid() plt.show()