利用python实现支持向量机算法

上一节介绍了支持向量机的推导原理和名字由来,本文小记一下用python实现支持向量机的代码(依然是学习笔记):
1,实现线性分类

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets.samples_generator import make_blobs
from sklearn.svm import SVC

#随机生成点,n_samples:样本点个数;centers:样本点分为几类;random_state:每次随机生成一致;cluster_std:每类样本点间的离散程度,值越大离散程度越大。
X,y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)
#画出所有样本点
plt.scatter(X[:,0],X[:,1],c=y,cmap='summer')

#使用线性分类SVC拟合
#svc函数还可以包括以下参数(具体例子见文章最后):
#1,C(C越大意味着分类越严格不能有错误;当C趋近于很小的时意味着可以有更大的错误容忍)
#2,kernel(kernel必须是[‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’]中的一个,默认为’rbf’)
#3,gamma(gamma越大模型越复杂,会导致过拟合,对线性核函数无影响)
model = SVC(kernel='linear')
model.fit(X,y)
plot_svc_decision_function(model)

这里用到绘制边界线及圈出支持向量的函数plot_svc_decision_function()

def plot_svc_decision_function(model, ax=None, plot_support=True):
    #Plot the decision function for a 2D SVC
    if ax is None:
        ax = plt.gca()
    #找出图片x轴y轴的边界
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    
    # create grid to evaluate model
    x = np.linspace(xlim[0], xlim[1], 30)
    y = np.linspace(ylim[0], ylim[1], 30)
    Y, X = np.meshgrid(y, x)
    #形成图片上所有坐标点(900,2),900个二维点
    xy = np.vstack([X.ravel(), Y.ravel()]).T
    #计算每点到边界的距离(30,30)
    P = model.decision_function(xy).reshape(X.shape)
    
    #绘制等高线(距离边界线为0的实线,以及距离边界为1的过支持向量的虚线)
    ax.contour(X, Y, P, colors='k',levels=[-1, 0, 1], alpha=0.5,linestyles=['--', '-', '--'])
    
    # 圈出支持向量
    if plot_support:
    	#model.support_vectors_函数可打印出所有支持向量坐标
        ax.scatter(model.support_vectors_[:, 0],model.support_vectors_[:, 1],s=200,c='',edgecolors='k')
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

绘制效果图如下:
在这里插入图片描述

2,实现非线性分类–引入核函数
有时候线性核函数不能很好的划分边界比如:

from sklearn.datasets.samples_generator import make_circles

X,y = make_circles(100, factor=.1, noise=.1)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')
clf = SVC(kernel='linear').fit(X, y)
plot_svc_decision_function(clf, plot_support=False)

分类结果如下:
在这里插入图片描述
此时,需加入径向基函数rbf(高斯)

X,y = make_circles(100, factor=.1, noise=.1)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')
clf = SVC(kernel='rbf', C=1E6)
clf.fit(X,y)
plot_svc_decision_function(clf)

分类结果如下:
在这里插入图片描述
好啦,今天就先写到这里吧,之后还有用支持向量机实现人脸识别的例子。

————————————————————————————————————————————
补充一下C值和gamma值对结果的影响

1,C值(C越大意味着分类越严格不能有错误)

X, y = make_blobs(n_samples=100, centers=2,
                  random_state=0, cluster_std=0.8)

fig, ax = plt.subplots(1, 3, figsize=(16, 5))
fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)

for axi, C in zip(ax, [10.0,3.0, 0.1]):
    model = SVC(kernel='linear', C=C).fit(X, y)
    axi.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')
    plot_svc_decision_function(model, axi)
    axi.set_title('C = {0:.1f}'.format(C), size=14)

在这里插入图片描述

2,gamma值(gamma越大模型越复杂,会导致过拟合)

X, y = make_blobs(n_samples=100, centers=2,
                  random_state=0, cluster_std=1.1)

fig, ax = plt.subplots(1, 3, figsize=(16, 5))
fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)

for axi, gamma in zip(ax, [10.0,3.0, 0.1]):
    model = SVC(kernel='rbf', gamma=gamma).fit(X, y)
    axi.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='summer')
    plot_svc_decision_function(model, axi)
    axi.set_title('gamma = {0:.1f}'.format(gamma), size=14)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39860046/article/details/82959598