首先我们使用常用的酒的数据集,来简单使用一下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越小时,决策边界就会越平滑,分类效果就越好。