SVM→8.SVM实战→1.训练一个基本的SVM

《SVM→8.SVM实战→1.训练一个基本的SVM》


描述 代码
  1. 导入模块
1
2
3
4
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from sklearn.svm import SVC # "Support vector classifier"
import numpy as np
  1. 生成数据集
    1. 使用make_blobs函数生成用于聚类的数据,主要参数有:
      1. n_samples:样本个数
      2. centers:样本中心(类别)数
      3. random_state:随机种子(被指定后,每次构造数据相同)
      4. cluster_std:数据离散程度
      5. n_features:特征数,默认是2
    2. 返回值有样本数据集X和标签y,且都是ndarray对象
1
2
3
4
In[3]: type(make_blobs)
Out[3]: function
In[4]: X, y = make_blobs(n_samples=50, centers=2,random_state=0, cluster_std=0.60)
In[5]: plt.scatter(X[:, 0], X[:, 1], c=y,  s=50, cmap='autumn')
  1. 模型选择
    1. 使用svm.SVC(C=1.0, kernel=’rbf’)来创建一个SVC对象,C是惩罚参数,默认是1,kernel是核函数,默认是rbf核函数。主要的属性有:
      1. support_vectors_:支持向量
    2. 主要的方法有:
      1. fit(X,y):根据给定的训练集X及标签y,拟合SVM模型
      2. decision_function(X)
        1
        2
        3
        4
        In[10]: model = SVC(kernel='linear')
           ...: model.fit(X, y)
           ...: type(model.fit(X, y))
        Out[10]: sklearn.svm.classes.SVC
        1
        2
        3
        4
        5
        In[8]: model.support_vectors_
        Out[8]: 
        array([[0.44359863, 3.11530945],
               [2.33812285, 3.43116792],
               [2.06156753, 1.96918596]])
  1. 绘制图形
    1. 调用函数  
      1
      plot_svc_decision_function(model)
    2. 结果显示                
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      def plot_svc_decision_function(model, ax=None, plot_support=True):
          """Plot the decision function for a 2D SVC"""
          if ax is None:
              ax = plt.subplot(111)
          xlim = ax.get_xlim()
          ylim = ax.get_ylim()
      
          # create grid to evaluate model
          x = np.linspace(xlim[0], xlim[1], 30)
          y = np.linspace(ylim[0], ylim[1], 30)
          X,Y = np.meshgrid(x, y)
          xy = np.vstack([X.flatten(), Y.flatten()]).T
          P = model.decision_function(xy).reshape(X.shape)
      
          # plot decision boundary and margins
          #levels是等高线高度 alpha是透明度 linestyles与levels对应
          ax.contour(X, Y, P, colors='k',
                     levels=[-1, 0, 1], alpha=0.5,
                     linestyles=['--', '-', '--'])
      
          # plot support vectors
          if plot_support:
              ax.scatter(model.support_vectors_[:, 0],
                         model.support_vectors_[:, 1],
                         s=500,c='',edgecolors='black')





猜你喜欢

转载自www.cnblogs.com/LeisureZhao/p/9752450.html
svm
今日推荐