深入解析python版SVM源碼系列(一)——添加資料庫和繪製效果圖,pythonsvm

來源:互聯網
上載者:User

深入解析python版SVM源碼系列(一)——添加資料庫和繪製,pythonsvm

這部分的代碼是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 feature    yPt = float(lineSplit[1])  # the second feature    label = int(lineSplit[2])  # the target label     if (label == -1):  # the first class        xcord0.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有區別

其中有下面幾個點需要留意:

import matplotlibimport matplotlib.pyplot as plt

然後:

fig = plt.figure()  # 控制代碼取出來ax = fig.add_subplot(111)  # 定義只有一個視圖,也可以多個視圖

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.