《SVM→8.SVM实战→2.引入核函数的SVM》
描述 | 代码 |
---|
- 导入模块
|
|
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
|
|
- 生成数据集
- 使用make_circles函数生成用于一个大圈和一个小圈的数据,用于聚类或分类可视化,主要参数有:
- n_samples:样本个数
- random_state:随机种子(被指定后,每次构造数据相同)
- factor:内圈相对外圈的缩放系数,值越小,内圈越小
- noise:给数据添加的高斯噪声,越大数据分散得越开,小圈和大圈数据交集越多
- 返回值有样本数据集X只能是2个特征和标签y,且都是ndarray对象
|
|
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')
|
|
- 模型选择
- 使用svm.SVC(C=1.0, kernel=’rbf’)分别创建线性核和高斯核SVC对象,并绘制图像绘图函数参考见扩展
-
|
|
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)
|
|
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')
|