深入浅出机器学习实战(5)-基于Python工具包的使用-SVM2

首先我们使用常用的酒的数据集,来简单使用一下SVM的分类方法。

# -*- coding:UTF-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
import warnings
warnings.filterwarnings('ignore')
# 定义画图函数
def make_meshgird(x, y, h=.02):
    xx, yy = np.meshgrid(np.arange(x.min() - 1, x.max() + 1, .02),
                         np.arange(y.min() - 1, y.max() + 1, .02))
    return xx, yy


# 定义一个绘制等高线的函数
def plot_contours(ax, clf, xx, yy, **params):
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    out = ax.contourf(xx, yy, Z, **params)
    return out


# 使用酒的数据集
wine = load_wine()
# 选取数据集的前两个特征
X = wine.data[:, :2]
y = wine.target

C = 1.0  # SVM的正则化参数
models = (svm.SVC(kernel='linear', max_iter=50000,C=C),  # 线性内核
          svm.LinearSVC(C=C,max_iter=50000), # 线性SVM,无需调参
          svm.SVC(kernel='rbf', max_iter=50000,gamma=0.7, C=C),  # 高斯内核
          svm.SVC(kernel='poly',max_iter=50000, degree=3, C=C))  # 多项式内核
# 使用交叉验证的方式对各个内核进行评分
for clf in models:
    scores=cross_val_score(clf, X, y)
    score =np.mean(scores)
    print(score)
print('\n')
models = (clf.fit(X, y) for clf in models)

# 设定标题
titles = ('SVC_linearkernel',
          'LinearSVC',
          'SVC_RBFkernel',
          'SVC_Polykernel')

# 设定子图形的个数和排列方式
fig, sub = plt.subplots(2, 2)
plt.subplots_adjust(wspace=0.4, hspace=0.4)
# 使用前面定义的函数画图
X0, X1 = X[:, 0], X[:, 1]
xx, yy = make_meshgird(X0, X1)

for clf, title, ax, in zip(models, titles, sub.flatten()):
    plot_contours(ax, clf, xx, yy,
                  cmap=plt.cm.plasma, alpha=0.8)
    ax.scatter(X0, X1, c=y, cmap=plt.cm.plasma, s=20, edgecolors='k')
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xlabel('Feature 0')
    ax.set_ylabel('Feature 1')
    ax.set_xticks(())
    ax.set_yticks(())
    ax.set_title(title)
plt.show()

'''
    RBF中重要的是正则化参数C和参数gamma
    画图显示不同的gamma值对于RBF内核的SVC有何影响
    gamma值越小,RBF内核直径越大,决策边界越平滑,更多的点会在边界中,模型就会简单
    gamma值越小越容易出现欠拟合问题,越大越容易出现过拟合问题
'''
C = 1.0  # 正则化参数
models = (svm.SVC(kernel='rbf', gamma=0.1, C=C),
          svm.SVC(kernel='rbf', gamma=1, C=C),
          svm.SVC(kernel='rbf', gamma=10, C=C))
# 使用交叉验证的方式对各个内核进行评分
for clf in models:
    scores=cross_val_score(clf, X, y)
    score =np.mean(scores)
    print(score)
models = (clf.fit(X, y) for clf in models)

# 设定图题
titles = ('gamma=0.1',
          'gamma=1',
          'gamma=10')

# 设置子图个数和格式
fig, sub = plt.subplots(1, 3, figsize=(10, 3))
X0, X1 = X[:, 0], X[:, 1]
xx, yy = make_meshgird(X0, X1)
# 使用定义好的函数进行画图
for clf, title, ax, in zip(models, titles, sub.flatten()):
    plot_contours(ax, clf, xx, yy,
                  cmap=plt.cm.plasma, alpha=0.8)
    ax.scatter(X0, X1, c=y, cmap=plt.cm.plasma, s=20, edgecolors='k')
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xlabel('Feature 0')
    ax.set_ylabel('Feature 1')
    ax.set_xticks(())
    ax.set_yticks(())
    ax.set_title(title)
plt.show()

为了方便实现可视化,我们这里只截取酒数据集中的前两个特征 ,从结果图中我们可以看到SVM的不同内核在分类结果上出现的差异以及决策边界的划分。此外我们还通过使用交叉验证的方法,查看了使用不同的SVM内核时对于整个数据集的分类效果。从结果中可以看出,使用高斯核的SVM分类的准确率要高于其他几种内核。这也是为什么在使用中我们也是经常使用高斯核。

 接下来我们对于高斯核的参数进行了一些修改,以观察不同参数对于高斯核分类的影响。 

从评分结果中可以看出当参数gamma越小的时候分类的准确率也越高,分类效果图中表示出当gamma越小时,决策边界就会越平滑,分类效果就越好。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Big-Sunny-Boy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值