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

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')
paste-223913825009667.jpg
  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)paste-93037581565955.jpg
        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. 结果显示                paste-291843027763203.jpg
 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')





posted on 2018-10-08 08:44 LeisureZhao 阅读(...) 评论(...) 编辑 收藏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值