机器学习——python scikit-learn SVC分类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/guanyuqiu/article/details/85109441

scikit-learn SVC例子:https://scikit-learn.org/stable/modules/svm.html

SVM可以用于分类、回归、异常检测。SVM库中包括SVC、LinearSVC接口

1.导入svm库

from sklearn import svm

2.制作训练集和测试集

x, y = np.split(data, (4,), axis=1)
x = x[:, :2]
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, train_size=0.6)

split(数据,分割位置,轴=1(水平分割) or 0(垂直分割))。

x = x[:, :2]是为方便后期画图更直观,故只取了前两列特征值向量训练

sklearn.model_selection.train_test_split随机划分训练集和测试集。

3.训练SVM

 clf = svm.SVC(C=0.8, kernel='rbf', gamma=20, decision_function_shape='ovr')
    clf.fit(x_train, y_train.ravel())

C:惩罚参数

默认值为1,惩罚参数是由于松弛变量而加入的,它表征的是对错误分类的惩罚程度,也就是不允许分类出错的程度。

       C越大,表明越不允许分类出错,但是C越大越可能过拟合。

        C太小的话趋于0的话,分类将不会关注分类是否正确的问题,只要求间隔 越大越好,此时分类也没有意义。

Kernel:核函数

作用:核函数的引入是为了解决线性不可分的问题,讲分类点映射的高维空间中以后,转化为可线性分割的问题。

  1. kernel=‘linear’时,为线性核,C越大分类效果越好,但可能会过拟合;
  2. kernel='rbf'时,为高斯核,gamma值越小,分类界面越连续;gamma值越大,分类界面越“散”,分类效果越好,但可能会过拟合;
  3. kernel='poly':多项式核
  4. kernel=sigmoid’:Sigmoid核函数 

decision_function_shape参数

  1. decision_function_shape='ovr'时,为one v rest,即一个类别与其他ov类别进行划分;
  2. decision_function_shape='ovo'时,为one v one,即将类别两两进行划分,用二分类的方法模拟多分类的结果;

4.计算SVC分类器的准确率

print clf.score(x_train, y_train)  # 精度
y_hat = clf.predict(x_train)
show_accuracy(y_hat, y_train, '训练集')
print clf.score(x_test, y_test)
y_hat = clf.predict(x_test)
show_accuracy(y_hat, y_test, '测试集')

如果想查看决策函数,可以通过decision_function()实现

print 'decision_function:\n', clf.decision_function(x_train)
print '\npredict:\n', clf.predict(x_train)

猜你喜欢

转载自blog.csdn.net/guanyuqiu/article/details/85109441
今日推荐