1. 程式人生 > >機器學習-python通過使用sklearn編寫支援向量機SVM

機器學習-python通過使用sklearn編寫支援向量機SVM

程式碼及資料集下載:SVM
線性支援向量機

import numpy as np
from sklearn import svm
from matplotlib import pyplot as plt

def loadDataSet(fileName):  
    dataMat = [] 
    labelMat = []
    with open(fileName) as f:
        for line in f.readlines():
            line = line.strip().split()
            dataMat.append([float(line[0
]),float(line[1])]) labelMat.append(int(line[2])) return dataMat,labelMat data,label = loadDataSet('testSet.txt') data = np.array(data) label = np.array(label) clf = svm.SVC(kernel='linear') clf.fit(data,label) fig = plt.figure(0) ax = fig.add_subplot(111) ax.scatter(data[:,0],data[:,1
],c=label, s=30, cmap=plt.cm.Paired) xx = ax.get_xlim() yy = ax.get_ylim() XX = np.linspace(xx[0],xx[1],30) YY = np.linspace(yy[0],yy[1],30) xxx, yyy = np.meshgrid(XX,YY) xy = np.dstack((xxx,yyy)).reshape(np.size(xxx),2) xy_labels = clf.decision_function(xy).reshape(xxx.shape) ax.contour(xxx,yyy,xy_labels,colors = 'b'
,levels = [-1,0,1],linestyles=['--','-','--']) plt.show()