这里我使用sklearn.svm.SVC函数,首先介绍一下函数参数。
sklearn.svm.SVC(C=1.0, kernel=‘rbf’, degree=3, gamma=‘auto’,
coef0=0.0, shrinking=True, probability=False,tol=0.001,
cache_size=200, class_weight=None, verbose=False, max_iter=-1,
decision_function_shape=None,random_state=None)
C:C-SVC的惩罚参数C?默认值是1.0。C越大,相当于惩罚松弛变量,希望松弛变量接近0,即对误分类的惩罚增大,趋向于对训练集全分对的情况,这样对训练集测试时准确率很高,但泛化能力弱。C值小,对误分类的惩罚减小,允许容错,将他们当成噪声点,泛化能力较强。
Kernel:核函数,默认是rbf,可以是‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’‘precomputed’
degree :多项式poly函数的维度,默认是3,选择其他核函数时会被忽略。
gamma :‘rbf’,‘poly’ 和‘sigmoid’的核函数参数。默认是’auto’,则会选择1/n_features
coef0 :核函数的常数项。对于‘poly’和 ‘sigmoid’有用。
probability :是否采用概率估计?.默认为False
shrinking :是否采用shrinking heuristic方法,默认为true
tol :停止训练的误差值大小,默认为1e-3
cache_size :核函数cache缓存大小,默认为200
class_weight :类别的权重,字典形式传递。设置第几类的参数C为weightC(C-SVC中的C)
verbose :允许冗余输出?
max_iter :最大迭代次数。-1为无限制。
decision_function_shape :‘ovo’, ‘ovr’ or None, default=None3
random_state :数据洗牌时的种子值,int值
主要调节的参数有:C、kernel、degree、gamma、coef0。*
创造数据集函数
make_blobs
x为特征y为标签
X, y = make_blobs(n_samples=200, centers=2, random_state=0, cluster_std=0.3)
画图
from sklearn import svm
from sklearn.datasets import make_blobs
from matplotlib import pyplot as plt
import numpy as np
X, y = make_blobs(n_samples=300, centers=2, random_state=0, cluster_std=0.3)
clf = svm.SVC(kernel='linear', C=1.0)
clf.fit(X, y)
plt.figure(figsize=(12, 4), dpi=144)
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
# 使用np.meshgrid()扩充为两轴的所有可能取值的组合
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap='hot', alpha=0.1)
markers = ['o', 's', '**']
colors = ['r', 'g', 'y']
labels = np.unique(y)
for label in labels:
plt.scatter(X[y == label][:, 0],
X[y == label][:, 1],
c=colors[label],
marker=markers[label])
sv = clf.support_vectors_
# 绘制为白色'x',这样就会贴在之前的有色点上了
plt.scatter(sv[:, 0], sv[:, 1], c='y', marker='x')
plt.style.use("ggplot")
plt.title('svm')
plt.xlabel('X1 ')
plt.ylabel('X2 ')
plt.show()