深入解析python版SVM源码系列(一)

这部分的代码是python版实现SVM分类器的源码,采集于《Machine Learning in Action》的作者公布代码。本文的工作就是深入解析为什么这样实现SVM,以及其中涉及到的python函数。 这部分的源码如下:

”’Created on Nov 22, 2010@author: Peter”’from numpy import *import matplotlibimport matplotlib.pyplot as pltfrom matplotlib.patches import Circlexcord0 = []ycord0 = []xcord1 = []ycord1 = []markers =[]colors =[]fr = open(‘testSet.txt’)#this file was generated by 2normalGen.pyfor line in fr.readlines(): # 按行读取文件lineSplit = line.strip().split(‘\t’) # 划分,使用字符串中的split()和strip()函数,它们经常在一起出现,注意:划分之后是list形式xPt = float(lineSplit[0]) # the first featureyPt = float(lineSplit[1]) # the second featurelabel = int(lineSplit[2]) # the target label if (label == -1): # the first classxcord0.append(xPt) # 注意list类型有append()函数,数据的第一维特征ycord0.append(yPt) # 数据的第二维特征else:xcord1.append(xPt)ycord1.append(yPt)fr.close() # 关闭文件,其中的数据都已经copy到list中了fig = plt.figure() # 句柄取出来ax = fig.add_subplot(111) # 定义只有一个视图ax.scatter(xcord0,ycord0, marker=’s’, s=90) # 散点图,负类用正方形ax.scatter(xcord1,ycord1, marker=’o’, s=50, c=’red’) # 正类用圆形plt.title(‘Support Vectors Circled’) # 名称#下面的circle圈出了SVM中的支持向量circle = Circle((4.6581910000000004, 3.507396), 0.5, facecolor=’none’, edgecolor=(0,0.8,0.8), linewidth=3, alpha=0.5)ax.add_patch(circle)circle = Circle((3.4570959999999999, -0.082215999999999997), 0.5, facecolor=’none’, edgecolor=(0,0.8,0.8), linewidth=3, alpha=0.5)ax.add_patch(circle)circle = Circle((6.0805730000000002, 0.41888599999999998), 0.5, facecolor=’none’, edgecolor=(0,0.8,0.8), linewidth=3, alpha=0.5)ax.add_patch(circle)#plt.plot([2.3,8.5], [-6,6]) #seperating hyperplaneb = -3.75567; w0=0.8065; w1=-0.2761x = arange(-2.0, 12.0, 0.1) # 从-2到12,中间间隔0.1,现在一般用rangey = (-w0*x – b)/w1ax.plot(x,y) # plot函数的输入也是两个list:x and yax.axis([-2,12,-8,6]) # 定义界面大小plt.show() # 最后展示效果,,而图像的内容要在ax上面操作,最后才会plt.show(),这一点和MATLAB有区别

其中有下面几个点需要留意:

文件按行读取 先open一个文件给file, 然后for line in file.readlines()按行读取,处理之后,需要file.close()list的append 增加一个元素用append,增加一个list用extended。 append和extend区别figure的绘制方式 python中绘图的方法。 首先:import matplotlibimport matplotlib.pyplot as plt

然后:

fig = plt.figure() # 句柄取出来ax = fig.add_subplot(111) # 定义只有一个视图,也可以多个视图

接着: ax.plot(),ax.scatter(),ax.axis()都要在ax上面操作。

走过一个又一个陌生的城市,去感受旖旎的自然风光,

深入解析python版SVM源码系列(一)

相关文章:

你感兴趣的文章:

标签云: