支持向量机(SVM)代码实现学习记录

导入所需要的库

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

#use seaborn plotting defaults
import seaborn as sns; sns.set()

支持向量基本原理

一个低维不可分的问题,进行转换成为高维可分得问题
在这里插入图片描述
如何解决这个线性不可分?转换成高维试试
z = x 2 + y 2 z=x^2+y^2

案例(对比在支持向量机中会出现的知识点)

导入sklear,用其构造了一个数据集

在datasets模块中有samples_generator(数据点的生成器),我们可以去自己生成一些数据并对其定义各种结构

#随机来点数据
from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=50, centers=2,                       #n_samples多少个样本点,    centers画成多少个堆
                  random_state=0, cluster_std=0.60)              #random_state指定随机的种子为0相当于每次随机构造的数据都是一样的:    cluster_std相当于簇的离散程度
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')          #画散点图

在这里插入图片描述

画几条线进行切分

xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plt.plot([0.6], [2.1], 'x', color='red', markeredgewidth=2, markersize=10)

for m, b in [(1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:
    plt.plot(xfit, m * xfit + b, '-k')

plt.xlim(-1, 3.5);

在这里插入图片描述

构造出一个隔离带(最小化 雷区)

xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')

for m, b, d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:
    yfit = m * xfit + b
    plt.plot(xfit, yfit, '-k')
    plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='none',
                     color='#AAAAAA', alpha=0.4)

plt.xlim(-1, 3.5);

在这里插入图片描述

有基本原理,首先去找一条线,使得离这条线最近的样本点能够到这条线的距离越远越好

训练一个基本的SVM

在sklearn下有一个svm模块,次模块中有SVC是支持向量机的一个分类器

from sklearn.svm import SVC     # "支持向量分类器"
model = SVC(kernel='linear')    #构造一个最基本的支持向量机
model.fit(X, y)

输出为
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma=‘auto’, kernel=‘linear’,
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)

绘图函数,可直接当成模板运用
#绘图函数
def plot_svc_decision_function(model, ax=None, plot_support=True):
    """绘制2D SVC的决策函数"""
    if ax is None:
        ax = plt.gca()
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    
    # 创建网格以评估模型
    x = np.linspace(xlim[0], xlim[1], 30)
    y = np.linspace(ylim[0], ylim[1], 30)
    Y, X = np.meshgrid(y, x)
    xy = np.vstack([X.ravel(), Y.ravel()]).T
    P = model.decision_function(xy).reshape(X.shape)
    
    # 绘制决策边界和边距
    ax.contour(X, Y, P, colors='k',
               levels=[-1, 0, 1], alpha=0.5,
               linestyles=['--', '-', '--'])
    
    # 绘制支持向量机
    if plot_support:
        ax.scatter(model.support_vectors_[:, 0],
                   model.support_vectors_[:, 1],
                   s=300, linewidth=1, facecolors='none');
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plot_svc_decision_function(model);

在这里插入图片描述

支持向量机构造完成后,构造出了决策边界,离决策边界最近的3个点,这三个点就是支持向量(support vectors)

边界上的点α值是非0的,非边界上的点α是等于0的



在Scikit_Learn中,有一个属性support_vectors_可以把支持向量直接调入存储位置

扫描二维码关注公众号,回复: 9906788 查看本文章
model.support_vectors_

输出为
array([[ 0.44359863, 3.11530945],
   [ 2.33812285, 3.43116792],
   [ 2.06156753, 1.96918596]])

此处是将这三个点的坐标拿到手

支持向量对决策边界的构造产生了影响,其他的点都不影响,尝试对比一下验证这句话

def plot_svm(N=10, ax=None):
    X, y = make_blobs(n_samples=200, centers=2,
                      random_state=0, cluster_std=0.60)
    X = X[:N]
    y = y[:N]
    model = SVC(kernel='linear', C=1E10)
    model.fit(X, y)

    ax = ax or plt.gca()
    ax.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
    ax.set_xlim(-1, 4)
    ax.set_ylim(-1, 6)
    plot_svc_decision_function(model, ax)

fig, ax = plt.subplots(1, 2, figsize=(16, 6))
fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)
for axi, N in zip(ax, [60, 120]):           #一侧的数据是60个样本点,另一侧的数据是120个样本点
    plot_svm(N, axi)
    axi.set_title('N = {0}'.format(N))

在这里插入图片描述

·左边是60个点的结果,右边是120个点的结果,但决策边界都一样
·观察发现,只要支持向量没变,其他数据怎么加都无所谓





引入的核函数

重新构造了一个数据集

from sklearn.datasets.samples_generator import make_circles
X, y = make_circles(100, factor=.1, noise=.1)

clf = SVC(kernel='linear').fit(X, y)            #线性的支持向量机

plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plot_svc_decision_function(clf, plot_support=False);

在这里插入图片描述

·无法用线进行分割,可以尝试高维核变换方法
·我们可以使用三维图来可视化这个额外的数据维度:

#加入了新的维度r
from mpl_toolkits import mplot3d
r = np.exp(-(X ** 2).sum(1))
def plot_3D(elev=30, azim=30, X=X, y=y):
    ax = plt.subplot(projection='3d')
    ax.scatter3D(X[:, 0], X[:, 1], r, c=y, s=50, cmap='autumn')
    ax.view_init(elev=elev, azim=azim)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('r')

plot_3D(elev=45, azim=45, X=X, y=y)

此处核变换就相当于是让红色点往下,黄色点往上,在中间切一?

在这里插入图片描述

实际上要怎么去做呢?

在此处引入一个径向基函数

#加入径向基函数
clf = SVC(kernel='rbf', C=1E6)
clf.fit(X, y)

输出为
SVC(C=1000000.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma=‘auto’, kernel=‘rbf’,
 max_iter=-1, probability=False, random_state=None, shrinking=True,
 tol=0.001, verbose=False)

plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plot_svc_decision_function(clf)
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
            s=300, lw=1, facecolors='none');

在这里插入图片描述

之前我们是线性的,就表现为是一条直线。
此时将它做成了非线性,在此处是画了一个圆,但其实它不一定就是圆,也可以是很多种非线性的模型
我们把一个线性不可分的问题做了一个非线性变换,非线性的模型就可以去拟合这个数据。

调节SVM参数:Soft Margin问题

调节C参数

·当C趋近于无穷大时,意味着分类严格不能有错误
·当C趋近于很小时,意味着可以有很大的错误容忍

X, y = make_blobs(n_samples=100, centers=2,
                  random_state=0, cluster_std=0.8)    #同样的数据集,在这里调整了离散程度cluster_std(此处使离散程度更大了)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn');

在这里插入图片描述

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

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

for axi, C in zip(ax, [10.0, 0.1]):       #此处一个10和一个0.1表示一个对应一个比较大的C参数,一个对应比较小的C参数
    model =VC(kernel='linear', C=C).fit(X, y)
    axi.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
    plot_svc_decision_function(model, axi)
    axi.scatter(model.support_vectors_[:, 0],
                model.support_vectors_[:, 1],
                s=300, lw=1, facecolors='none');
    axi.set_title('C = {0:.1f}'.format(C), size=14)
  

在这里插入图片描述

此时情况不好评估C大好还是C小好,需要通过交叉验证去尝试,尝试在验证集中哪个效果高

另一个参数γ值

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

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

for axi, gamma in zip(ax, [10.0, 0.1]):          # gama值控制着模型的复杂程度
    model = SVC(kernel='rbf', gamma=gamma).fit(X, y)
    axi.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
    plot_svc_decision_function(model, axi)
    axi.scatter(model.support_vectors_[:, 0],
                model.support_vectors_[:, 1],
                s=300, lw=1, facecolors='none');
    axi.set_title('gamma = {0:.1f}'.format(gamma), size=14)

在这里插入图片描述
大的γ值分类效果明显好,但是决策边界形状很复杂,边界越复杂,泛化能力就越低
小的γ值决策边界更平稳模型更精简,分错了很多点,但是泛化能力强

γ值只会在RBF和函数中会使用

C值无论线性还是高斯都是可以的

上面两个部分展现了γ的值和C的值对模型的影响



人脸识别

作为运行中的支持向量机的示例,让我们看一下面部识别问题。 我们将在“野生”数据集中使用“带标签的面孔”,该数据集由数千张各种公众人物的整理照片组成。 Scikit-Learn内置了数据集的提取程序:

from sklearn.datasets import fetch_lfw_people       #lfw是一个人脸数据集
faces = fetch_lfw_people(min_faces_per_person=60)   #小于60的人脸就被过滤掉了
print(faces.target_names)
print(faces.images.shape)

输出为
[‘Ariel Sharon’ ‘Colin Powell’ ‘Donald Rumsfeld’ ‘George W Bush’
‘Gerhard Schroeder’ ‘Hugo Chavez’ ‘Junichiro Koizumi’ ‘Tony Blair’]
(1348, 62, 47)


fig, ax = plt.subplots(3, 5)
for i, axi in enumerate(ax.flat):
    axi.imshow(faces.images[i], cmap='bone')
    axi.set(xticks=[], yticks=[],
            xlabel=faces.target_names[faces.target[i]])

在这里插入图片描述
每个图的大小是[62×47]
在这里我们就把每一个像素点当成了一个特征,但是这样特征大多了,用PCA降维

从3000维降到150维

from sklearn.svm import SVC
#从sklearn.decomposition导入RandomizedPCA
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline

pca = PCA(n_components=150, whiten=True, random_state=42)
svc = SVC(kernel='rbf', class_weight='balanced')     #用SVC进行分类
model = make_pipeline(pca, svc)
from sklearn.model_selection import train_test_split
Xtrain, Xtest, ytrain, ytest = train_test_split(faces.data, faces.target,
                                                random_state=40)

使用grid search cross-validation来选择我们的参数

from sklearn.model_selection import GridSearchCV   #GridSearch用来做模型参数的选择
param_grid = {'svc__C': [1, 5, 10],
              'svc__gamma': [0.0001, 0.0005, 0.001]}   #遍历C和gamma的几个数,选到哪个数在验证集中的精度比较高,就用这个参数
grid = GridSearchCV(model, param_grid)

%time grid.fit(Xtrain, ytrain)
print(grid.best_params_)

输出为:
Wall time: 51.5 s
{‘svc__C’: 5, ‘svc__gamma’: 0.001}

意思为
在51.5秒后得到C值为5,γ值为0.001

model = grid.best_estimator_
yfit = model.predict(Xtest)    #用模型进行预测
yfit.shape

在此处画了一个图,如果预测对了,用黑色表示,如果预测错了,用红色表示

fig, ax = plt.subplots(4, 6)
for i, axi in enumerate(ax.flat):
    axi.imshow(Xtest[i].reshape(62, 47), cmap='bone')
    axi.set(xticks=[], yticks=[])
    axi.set_ylabel(faces.target_names[yfit[i]].split()[-1],
                   color='black' if yfit[i] == ytest[i] else 'red')
fig.suptitle('Predicted Names; Incorrect Labels in Red', size=14);

在这里插入图片描述

from sklearn.metrics import classification_report
print(classification_report(ytest, yfit,
                            target_names=faces.target_names))
                       

精度(precision) = 正确预测的个数(TP)/被预测正确的个数(TP+FP)
召回率(recall)=正确预测的个数(TP)/预测个数(TP+FN)
F1 = 2精度召回率/(精度+召回率)

在这里插入图片描述

from sklearn.metrics import confusion_matrix     #confusion_matrix的意思是混淆矩阵
mat = confusion_matrix(ytest, yfit)
sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False,
            xticklabels=faces.target_names,
            yticklabels=faces.target_names)
plt.xlabel('true label')
plt.ylabel('predicted label');

在这里插入图片描述

想知道一个人预测的对不对,横轴和纵轴都是人名,主对角线就是把这个人预测正确了,非主对角线就是把横轴的人预测成了纵轴的人。

发布了19 篇原创文章 · 获赞 0 · 访问量 411

猜你喜欢

转载自blog.csdn.net/MercuryG/article/details/102724487
今日推荐