机器学习之十大经典算法(六) SVM算法
(一) SVM支持向量机简介:
全名:SupportVector Machine(支持向量机)。基于统计学习理论的一种机器学习方法。SVM是建立在统计学习理论的VC维理论和结构风险最小原理基础上的,根据有限的样本信息在模型的复杂性之间寻求最佳折衷,以期获得最好的推广能力(或泛化能力)。支持向量:支持或支撑平面上把两类类别划分开来的超平面的向量点。简单的说,就是将数据单元表示在多维空间中,然后对这个空间做划分的算法。其基本原理是(以二维数据为例):如果训练数据分布在二维平面上的点,它们按照其分类聚集在不同的区域。基于分类边界的分类算法的目标是,通过训练,找到这些分类之间的边界(直线的――称为线性划分,曲线的――称为非线性划分)。对于多维数据(如 N 维),可以将它们视为 N 维空间中的点,而分类边界就是 N 维空间中的面,称为超面(超面比 N维空间少一维)。线性分类器使用超平面类型的边界,非线性分类器使用超曲面。
支持向量机的原理是将低维空间的点映射到高维空间,使它们成为线性可分,再使用线性划分的原理来判断分类边界。在高维空间中是一种线性划分,而在原有的数据空间中,是一种非线性划分。SVM 在解决小样本、非线性及高维模式识别问题中表现出许多特有的优势,并能够推广应用到函数拟合等其他机器学习问题中。
(二) SVM支持向量机基本步骤:
这部分内容转载https://blog.csdn.net/bbbeoy/article/details/72468868,总结非常好。
(三) Sklearn中SVM应用举例。
基本步骤:
①选择数据:将你的数据分成三组:训练数据、验证数据和测试数据
②模型数据:使用训练数据来构建使用相关特征的模型
③验证模型:使用你的验证数据接入你的模型
④测试模型:使用你的测试数据检查被验证的模型的表现
⑥使用模型:使用完全训练好的模型在新数据上做预测
⑥调优模型:使用更多数据、不同的特征或调整过的参数来提升算法的性能表现
写了个SVM算法类,方便大家使用,代码如下:
import numpy as np import matplotlib.pyplot as plt from sklearn.svm import SVC class MySVM: def __init__(self,params={'kernel': 'linear'},input_file='d:\\data_multivar.txt'): self.input_file=input_file self.moduleparams=params self.module=SVC(**params) def load_data(self): X = [] y = [] with open(self.input_file, 'r') as f: for line in f.readlines(): data = [float(x) for x in line.split(',')] X.append(data[:-1]) y.append(data[-1]) self.X = np.array(X) self.y= np.array(y) def plot_data(self): class_0 = np.array([self.X[i] for i in range(len(self.X)) if self.y[i]==0]) class_1 = np.array([self.X[i] for i in range(len(self.X)) if self.y[i]==1]) # Plot the input data plt.figure() plt.scatter(class_0[:,0], class_0[:,1], facecolors='black', edgecolors='black', marker='s') plt.scatter(class_1[:,0], class_1[:,1], facecolors='None', edgecolors='black', marker='s') plt.title('Input data') plt.show() def train_test_data(self): # Train test split from sklearn import cross_validation self.X_train, self.X_test, self.y_train, self.y_test = \ cross_validation.train_test_split(self.X, self.y, test_size=0.25, random_state=5) def train_fit(self): self.module.fit(self.X_train, self.y_train) def plot_classifier(self, X, y, title='Classifier boundaries', annotate=False): # define ranges to plot the figure x_min, x_max = min(X[:, 0]) - 1.0, max(X[:, 0]) + 1.0 y_min, y_max = min(X[:, 1]) - 1.0, max(X[:, 1]) + 1.0 # denotes the step size that will be used in the mesh grid step_size = 0.01 # define the mesh grid x_values, y_values = np.meshgrid(np.arange(x_min, x_max, step_size), np.arange(y_min, y_max, step_size)) # compute the classifier output mesh_output = self.module.predict(np.c_[x_values.ravel(), y_values.ravel()]) # reshape the array mesh_output = mesh_output.reshape(x_values.shape) # Plot the output using a colored plot plt.figure() # Set the title plt.title(title) # choose a color scheme you can find all the options # here: http://matplotlib.org/examples/color/colormaps_reference.html plt.pcolormesh(x_values, y_values, mesh_output, cmap=plt.cm.gray) # Overlay the training points on the plot plt.scatter(X[:, 0], X[:, 1], c=y, s=80, edgecolors='black', linewidth=1, cmap=plt.cm.Paired) # specify the boundaries of the figure plt.xlim(x_values.min(), x_values.max()) plt.ylim(y_values.min(), y_values.max()) # specify the ticks on the X and Y axes plt.xticks(()) plt.yticks(()) if annotate: for x, y in zip(X[:, 0], X[:, 1]): # Full documentation of the function available here: # http://matplotlib.org/api/text_api.html#matplotlib.text.Annotation plt.annotate( '(' + str(round(x, 1)) + ',' + str(round(y, 1)) + ')', xy = (x, y), xytext = (-15, 15), textcoords = 'offset points', horizontalalignment = 'right', verticalalignment = 'bottom', bbox = dict(boxstyle = 'round,pad=0.6', fc = 'white', alpha = 0.8), arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=0')) def report_classifier(self): ############################################### # Evaluate classifier performance from sklearn.metrics import classification_report target_names = ['Class-' + str(int(i)) for i in set(self.y)] print("=================%s=============================\n"%(self.moduleparams)) print("\n" + "#"*30) print("\nClassifier performance on training dataset\n") print(classification_report(self.y_train, self.module.predict(self.X_train), target_names=target_names)) print("#"*30 + "\n") print("#"*30) print("\nClassification report on test dataset\n") print(classification_report(self.y_test, self.module.predict(self.X_test), target_names=target_names)) print("#"*30 + "\n") print("==============================================\n") params1 ={'kernel': 'linear'} params2 = {'kernel': 'poly', 'degree': 3} params3 = {'kernel': 'rbf'} paramsList=[params1,params2,params3] for yy in paramsList: # classifier = SVC(**yy) MySVM1=MySVM(params=yy) MySVM1.load_data() print(MySVM1.X,MySVM1.y) MySVM1.plot_data() MySVM1.train_test_data() MySVM1.train_fit() MySVM1.plot_classifier(MySVM1.X,MySVM1.y,title='%s Classifier boundaries'%MySVM1.moduleparams) MySVM1.report_classifier() plt.show()