唐宇迪《python数据分析与机器学习实战》学习笔记
18案例:SVM调参实例
看SVM的参数,及其基本使用
1.导入模块
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
#统计函数库scipy.stats,包含了多种概率分布的随机变量,随机变量分为连续的和离散的两种。
# use seaborn plotting defaults
import seaborn as sns; sns.set()
2.构造数据实验
#随机来点数据
from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=50, centers=2,
random_state=0, cluster_std=0.60)
#多少个样本点、多少堆、每次随机构造一致、离散程度,X形状[50,2],y为50个0/1
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')#散点图,y传入区分0/1颜色
接下来两块代码直观展示下原理:先画几条分割线看一下
xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plt.plot([0.6], [2.1], 'x', color='red', markeredgewidth=2, markersize=10) ##画了一个X点
##以X点画几条切分线
for m, b in [(1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:
plt.plot(xfit, m * xfit + b, '-k')
## m为斜率
plt.xlim(-1, 3.5);
增加阴影看隔离带效果:
xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
for m, b, d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:
yfit = m * xfit + b
plt.plot(xfit, yfit, '-k')
plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='none',
color='#AAAAAA', alpha=0.4)
plt.xlim(-1, 3.5);
3.训练SVM
基本思路:先找到距离决策边界最近的样本点,然后使该点到该边界的距离越远越好
3.1 训练基本模型
from sklearn.svm import SVC # 支持向量机的SVC分类器
model = SVC(kernel='linear', C=1E10)#核函数选用线性分类 C为惩罚系数
model.fit(X, y)#训练基本SVM模型
SVC(C=10000000000.0, break_ties=False, cache_size=200, class_weight=None,
coef0=0.0, decision_function_shape=‘ovr’, degree=3, gamma=‘scale’,
kernel=‘linear’, max_iter=-1, probability=False, random_state=None,
shrinking=True, tol=0.001, verbose=False)
备注:kernel: str参数 默认为‘rbf’、‘linear’:线性核函数、‘poly’:多项式核函数、‘rbf’:径像核函数/高斯核、‘sigmod’:sigmod核函数、‘precomputed’:核矩阵
# 绘图的模块,平时直接用就是
#边界上的点才是支持向量,系数不等于0,非边界上的系数值等于0.
def plot_svc_decision_function(model, ax=None, plot_support=True):
"""Plot the decision function for a 2D SVC"""
if ax is None:
ax