支持向量机SVM分类实现(Kernel-Tricks, 正则化,Gridsearch) python

本文介绍了SVM的支持向量机分类,包括线性划分、核技巧(如RBF核函数)以及正则化参数C的作用。通过Gridsearch方法寻找最佳超参数,以提升模型性能。
摘要由CSDN通过智能技术生成
1. 线性划分

从最简单的开始,即存在超平面可以完美分割两个label的数据。此时不需要使用正则化(C取很大)就可以通过一个线性核函数训练SVM。即点不会出现在分离超平面以内。
在这里插入图片描述
在这里插入图片描述

2. 核技巧 Kernel-Tricks

当线性核函数无法满足数据分类的情况时(例如同心圆数据集),SVM允许使用核技巧Kernel-Tricks,也就是说选择适当的核函数,使得数据可以线性分割。
最常用的核函数就是径向基核函数RBF
https://baike.baidu.com/item/%E5%BE%84%E5%90%91%E5%9F%BA%E5%87%BD%E6%95%B0

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3. 正则化

C是svm.SVC()的重要参数,

Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. The penalty is a squared l2 penalty.

可以理解为当数据在超平面以内的时候的罚函数。当C很大的时候,也就意味着几乎不可能有数据出现在超平面以内。C越小意味着对训练集误分类的容忍度越高。

在这里插入图片描述
在这里插入图片描述
yth
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

1-3代码如下, Gridsearch内容在后面

#!/usr/bin/env python
# coding: utf-8
# ## Referenzen
#  [1] C. Cortes and V. Vapnik. „Support-Vector Networks“. In: Machine Learning 20.3 (1995), pp. 273–297
from sklearn import svm
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import utils

sns.set(
    context="notebook",
    style="whitegrid",
    rc={
   "figure.dpi": 120, "scatter.edgecolors": "k"},
)


def plot_data(X, y):
    """Plots the data and label assignment as a scatter plot."""
    plt.scatter(X[:,0],X[:,1],c=y,cmap=plt.cm.Paired, edgecolors="k",zorder=10)
    plt.xticks([])
    plt.yticks([])
    plt.axis("tight")
    plt.show()


def fit_linear_svm(X, y):
    """Fits a svm with a linear kernel and no regularization to the data."""
    clf = svm.SVC(kernel="linear", C=1e10, max_iter=10000)
    clf.fit(X,y)
    return clf


def fit_rbf_svm(X, y):
    """Fits a svm with a rbf kernel and no regularization to the data."""
    clf = svm.SVC(kernel="rbf", C=1e10, gamma="auto")
    clf.fit(X,y)
    return clf


def plot_svm_C(X, y):
    """Plot the decision boundaries and support vectors for regularization constants:
    C=[2^-6, 2^-3, 1, 2^3, 2^6, 2^12]."""
    for C in range(-6,13,3):
        # Create an SVC object with the rbf kernel parameter
        clf = svm.SVC(kernel="rbf", C
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>