SVM→8.SVM实战→2.引入核函数的SVM

SVM→8.SVM实战→2.引入核函数的SVM

《SVM→8.SVM实战→2.引入核函数的SVM》


描述代码
  1. 导入模块
1
2
3
4
from sklearn.datasets.samples_generator import make_circles
import matplotlib.pyplot as plt
from sklearn.svm import SVC # "Support vector classifier"
import numpy as np
  1. 生成数据集
    1. 使用make_circles函数生成用于一个大圈和一个小圈的数据,用于聚类或分类可视化,主要参数有:
      1. n_samples:样本个数
      2. random_state:随机种子(被指定后,每次构造数据相同)
      3. factor:内圈相对外圈的缩放系数,值越小,内圈越小
      4. noise:给数据添加的高斯噪声,越大数据分散得越开,小圈和大圈数据交集越多
    2. 返回值有样本数据集X只能是2个特征和标签y,且都是ndarray对象
1
2
3
4
In[3]: type(make_circles)
Out[3]: function
In[4]: X, y = make_circles(n_samples=100,random_state=10,factor=.1, noise=.1)
In[5]: plt.scatter(X[:, 0], X[:, 1], c=y,  s=50, cmap='autumn')
paste-186178242347011.jpg
  1. 模型选择
    1. 使用svm.SVC(C=1.0, kernel=’rbf’)分别创建线性核和高斯核SVC对象,并绘制图像绘图函数参考见扩展
  • liear核函数
paste-192921341001731.jpg
  • rbf核函数
paste-193037305118723.jpg
  • liear核函数
1
2
3
4
In[35]: plt.scatter(X[:, 0], X[:, 1], c=y,  s=50, cmap='autumn')
In[33]: clf = SVC(kernel='linear', C=1E6)
   ...: clf.fit(X, y)
In[34]: plot_svc_decision_function(clf)
  • rbf核函数
1
2
3
4
In[35]: plt.scatter(X[:, 0], X[:, 1], c=y,  s=50, cmap='autumn')
In[31]: clf = SVC(kernel='rbf', C=1E6)
   ...: clf.fit(X, y)
In[34]: plot_svc_decision_function(clf)

扩展

参考见SVM→8.SVM实战→1.训练一个基本的SVM
 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
    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 09:40 LeisureZhao 阅读(...) 评论(...) 编辑 收藏

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值