sklearn SVM

1. SVM iris案例

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from sklearn import datasets
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

"""
加载数据
"""
iris = datasets.load_iris()
X_data, y_data = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.25)

"""
特征归一化
"""
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

"""
训练
"""
clf = SVC()
clf.fit(X_train, y_train)

"""
评估
"""
print("train score: ", clf.score(X_train, y_train))
print("test score: ", clf.score(X_test, y_test))

"""
网格搜索
"""
param_grid = [
{
'kernel': ['rbf', 'poly', 'linear'],
'C': [0.01, 0.1, 1],
'gamma': [0.125, 0.25, 0.5, 1, 2, 4]
}
]
clf = SVC()
grid_search = GridSearchCV(clf, param_grid)
grid_search.fit(X_train, y_train)
print("Best set score: {:.2f}".format(grid_search.best_score_))
print("Best parameters: {}".format(grid_search.best_params_))
print("Test set score: {:.2f}".format(grid_search.score(X_test, y_test)))

2. SVC参数

(1)C: 目标函数的惩罚系数C,用来平衡分类间隔margin和错分样本的,default C = 1.0;
(2)kernel:参数选择有RBF, Linear, Poly, Sigmoid, 默认的是”RBF”;
(3)degree:if you choose ‘Poly’ in param 2, this is effective, degree决定了多项式的最高次幂;
(4)gamma:核函数的系数(‘Poly’, ‘RBF’ and ‘Sigmoid’), 默认是gamma = 1 / n_features;
(5)coef0:核函数中的独立项,’RBF’ and ‘Poly’有效;
(6)probablity: 可能性估计是否使用(true or false);
(7)shrinking:是否进行启发式;
(8)tol(default = 1e - 3): svm结束标准的精度;
(9)cache_size: 制定训练所需要的内存(以MB为单位);
(10)class_weight: 每个类所占据的权重,不同的类设置不同的惩罚参数C, 缺省的话自适应;
(11)verbose: 跟多线程有关,不大明白啥意思具体;
(12)max_iter: 最大迭代次数,default = 1, if max_iter = -1, no limited;
(13)decision_function_shape : ‘ovo’ 一对一, ‘ovr’ 多对多 or None 无, default=None
(14)random_state :用于概率估计的数据重排时的伪随机数生成器的种子。

panchaoxin wechat
关注我的公众号
支持一下