sklearn调包侠之支持向量机

3629157-279af5abb817cbf6.png

算法原理

对于支持向量机原理,可参考该系列博客(https://www.cnblogs.com/pinard/p/6111471.html)。

实战——乳腺癌检测

数据导入

本次实战使用前文中的乳腺癌数据集,如图所示。

from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
print(cancer.DESCR)
3629157-4c30cbc1bb44b7f0.png
切分数据集
X = cancer.data
y = cancer.target

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=33)
模型训练与评估

支持向量机算法使用sklearn.svm 模块中的SVC方法。常用的参数如下:

  • C:默认为1.0,是对于错误的惩罚项。
  • kernel:指定算法的核函数,默认为'rbf',常用的有'linear','poly','rbf','sigmoid','precomputed'。
  • degree:多项式核函数的次数('poly'),默认为3。 其他核函数会将其忽略。
  • gamma:'rbf','poly'和'sigmoid'的核系数。 如果gamma是'auto',那么将使用1 / n_features。

这里的数据较小,使用高斯核函数很容易过拟合:

from sklearn.svm import SVC
clf = SVC(C=1.0, kernel='rbf', gamma=0.1)
clf.fit(X_train, y_train)
clf.score(X_train, y_train)
clf.score(X_test, y_test)

# result
# 1.0
# 0.6228070175438597

当然我们也可以通过网格搜索获得适合的gamma值。

import numpy as np
from sklearn.model_selection import GridSearchCV

param_grid = {'gamma':np.linspace(0, 0.0003, 30)}
clf = GridSearchCV(SVC(), param_grid, cv=5)
clf.fit(X, y)
print(clf.best_params_, clf.best_score_)

# result
# {'gamma': 0.00011379310344827585} 0.936731107206

最后,使用多项式核函数拟合:

clf = SVC(C=1.0, kernel='poly', degree=2)
clf.fit(X_train, y_train)
train_score = clf.score(X_train, y_train)
test_score = clf.score(X_test, y_test)
print(train_score, test_score)

# result
# 0.98021978022 0.964912280702
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值