目录

一、SVM案例:线性支持向量机

SVM:支持向量机

支持向量基本原理

例子

Support Vector Machines: 最小化 雷区

训练一个基本的SVM

对比实验

二、软间隔C值对结果的影响

引入核函数的SVM

高维核变换

调节SVM参数: Soft Margin问题

调节C参数

三、模型复杂度的权衡

四、人脸识别实例

Example: Face Recognition

1、下载数据

2、降维后再SVM

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

4、测试

5、查看

6、热度图


一、SVM案例:线性支持向量机

SVM:支持向量机

  • 与传统算法进行对比,看看SVM究竟能带来什么样的效果

  • 软间隔的作用,这么复杂的算法肯定会导致过拟合现象,如何来进行解决呢?

  • 核函数的作用,如果只是做线性分类,好像轮不到SVM登场了,核函数才是它的强大之处!

支持向量基本原理

 如何解决这个线性不可分问题呢?咱们给它映射到高维来试试。

导包

%matplotlib inline
#为了在notebook中画图展示
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns; sns.set()

例子

#随机来点数据
#其中 cluster_std是数据的离散程度
from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=50, centers=2,random_state=0, cluster_std=0.60)
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')for m, b in [(1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:plt.plot(xfit, m * xfit + b, '-k')
#限制一下X的取值范围
plt.xlim(-1, 3.5);

Support Vector Machines: 最小化 雷区

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 + bplt.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

#分类任务
from sklearn.svm import SVC
#线性核函数 相当于不对数据进行变换
model = SVC(kernel='linear')
model.fit(X, y)

绘图函数(模板)

#绘图函数
def plot_svc_decision_function(model, ax=None, plot_support=True):if ax is None:ax = plt.gca()xlim = ax.get_xlim()ylim = ax.get_ylim()# 用SVM自带的decision_function函数来绘制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()]).TP = 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, alpha=0.2);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(支持向量)

  • 在Scikit-Learn中, 它们存储在这个位置 support_vectors_(一个属性)

model.support_vectors_

  • 观察可以发现,只需要支持向量我们就可以把模型构建出来

  • 接下来我们尝试一下,用不同多的数据点,看看效果会不会发生变化

  • 分别使用60个和120个数据点

对比实验

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]):plot_svm(N, axi)axi.set_title('N = {0}'.format(N))

  • 左边是60个点的结果,右边的是120个点的结果
  • 观察发现,只要支持向量没变,其他的数据怎么加无所谓!

二、软间隔C值对结果的影响

引入核函数的SVM

  • 首先我们先用线性的核来看一下在下面这样比较难的数据集上还能分了吗?
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')
clf.fit(X, y)
#这回厉害了!
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趋近于很小的时:意味着可以有更大的错误容忍
# 这份数据集中cluster_std稍微大一些,这样才能体现出软间隔的作用
X, y = make_blobs(n_samples=100, centers=2,random_state=0, cluster_std=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')

c=10和0.1 

#加大游戏难度的数据集
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)
# 选择两个C参数来进行对别实验,分别为10和0.1
for axi, C in zip(ax, [10.0, 0.1]):model = SVC(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)

三、模型复杂度的权衡

gamma值对结果的影响

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)
# 选择不同的gamma值来观察建模效果
for axi, gamma in zip(ax, [10.0, 0.1]):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)

gamma值大,构建复杂模型,容易过拟合。

gamma值小,简单模型。

四、人脸识别实例

Example: Face Recognition

As an example of support vector machines in action, let's take a look at the facial recognition problem. We will use the Labeled Faces in the Wild dataset, which consists of several thousand collated photos of various public figures. A fetcher for the dataset is built into Scikit-Learn.

1、下载数据

#读取数据集
from sklearn.datasets import fetch_lfw_people
faces = fetch_lfw_people(min_faces_per_person=60)
#看一下数据的规模
print(faces.target_names)
print(faces.images.shape)

  • 每个图的大小是 [62×47]
  • 在这里我们就把每一个像素点当成了一个特征,但是这样特征太多了,用PCA降维一下吧!

2、降维后再SVM

from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline#降维到150维
pca = PCA(n_components=150, whiten=True, random_state=42)
svc = SVC(kernel='rbf', class_weight='balanced')
#先降维然后再SVM
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)

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

from sklearn.model_selection import GridSearchCV
param_grid = {'svc__C': [1, 5, 10],'svc__gamma': [0.0001, 0.0005, 0.001]}
grid = GridSearchCV(model, param_grid)%time grid.fit(Xtrain, ytrain)
print(grid.best_params_)

4、测试

model = grid.best_estimator_
yfit = model.predict(Xtest)
yfit.shape

5、查看

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精度召回率/(精度+召回率)

6、热度图

from sklearn.metrics import 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');

 这样显示出来能帮助我们查看哪些人更容易弄混

唐宇迪学习笔记18:案例——SVM调参实例相关推荐

  1. 唐宇迪学习笔记10:项目实战-交易数据异常检测

    目录 一.任务目标解读 信用卡欺诈检测 任务流程: 主要解决问题: 二.项目挑战与解决方案制定 1.导入我们的工具包 2.数据读取 3.数据标签分布 三.数据标准化处理 四.下采样数据集制作 五.交叉 ...

  2. 唐宇迪学习笔记3:Python数据可视化库——Matplotlib

    目录 一.Matplotlib概述 最基本的图 线条格式 线条颜色 颜色与格式结合 二.子图与标注 绘制多个线 指定线条的宽度 自定义参数 子图 给图上加上注释 三.风格设置 ​四.条形图 五.条形图 ...

  3. 唐宇迪学习笔记1:Python环境安装、Pytho科学计算库——Numpy

    目录 一.AI数据分析入门 ​1.案例来源 2.Python环境配置(Python3) Python的安装 Python库安装工具 Jupyter Notebook 二.Python科学计算库--Nu ...

  4. 唐宇迪学习笔记4:Python可视化库——Seaborn

    目录 一.整体布局风格设置 五种主题风格 1.darkgrid 2.whitegrid 3.dark 4.white 5.ticks 二.风格细节设置 1.指定画图距离轴线的位置 2.指定轴的隐藏与否 ...

  5. 唐宇迪学习笔记20:聚类算法——DBSCAN

    目录 一.DBSCAN聚类算法 (Density-Based Spatial Clustering of Applications with Noise) 二.DBSCAN工作流程 工作流程 参数选择 ...

  6. 唐宇迪Pytorch笔记(附课程资料)

    目录 pytorch_tutorial 介绍 软件架构 安装教程 所需python包 使用说明 配套资料 { title = {pytorch深度学习实战}, author = {唐宇迪}, url ...

  7. DeepLearning学习笔记(1)“调参之路”_ by HZC

     Git>>> GITHUB 一.问题描述: 当我们在处理图像识别或者图像分类或者其他机器学习任务的时候,我们总是迷茫于做出哪些改进能够提升模型的性能(识别率.分类准确率)...或者 ...

  8. 机器学习之SVM调参实例

    一.任务 这次我们将了解在机器学习中支持向量机的使用方法以及一些参数的调整.支持向量机的基本原理就是将低维不可分问题转换为高维可分问题,在前面的博客具体介绍过了,这里就不再介绍了. 首先导入相关标准库 ...

  9. 23神经网络 :唐宇迪《python数据分析与机器学习实战》学习笔记

    唐宇迪<python数据分析与机器学习实战>学习笔记 23神经网络 1.初识神经网络 百度深度学习研究院的图,当数据规模较小时差异较小,但当数据规模较大时深度学习算法的效率明显增加,目前大 ...

最新文章

  1. C++标准库math
  2. C#模拟post消息,实现登陆功能(包括CAS系统)
  3. mysql创建存储时覆盖_总结到位的MySQL 的覆盖索引与回表
  4. Linux指令:tar打包与压缩
  5. 15-4 队列实现调度器
  6. poi 升级至4.x 的问题总结(POI Excel 单元格内容类型判断并取值)
  7. Bailian4094 秘密会谈【水题】
  8. Eviews 9.0新版本新功能——预测(Auto-ARIMA预测、VAR预测)
  9. 2008 China MVP Open Day 小记
  10. CopyToDataTable()、SetField()
  11. 看清喽别迷糊 英特尔本CPU型号之乱
  12. 使用ROS或Iptables作为ADSL上网路由器时,部分网站无法打开的问题
  13. 【STM32F407开发板用户手册】第14章 STM32F407的电源,复位和时钟系统
  14. 【观察】UCloud:决胜东南亚“正当时”,做出海企业“加速器”
  15. iOS voip电话和sip软电话 --网络电话
  16. HCNA之路由优先级及路由冗余备份
  17. RDL 报表 - 横向合并单元格后单元格被撑高
  18. 计算机开机主机不停地重启,电脑开机一直重启怎么办
  19. 张粤磊:从杂牌野战军到王牌正规军的蜕变
  20. 拖拽牛逼,轻松实现一个自由拖拽的组件

热门文章

  1. docker第五期 DockerFile讲解
  2. html input placeholder,HTML Input Text placeholder用法及代码示例
  3. MBP2019虚拟机解决方案
  4. Python实现调用百度API翻译文字
  5. 从零用Docker搭建CTFd动态靶场(CTFd+CTFd-whale)2023/04/01
  6. 热身赛—H - 扫雷?踩雷!!
  7. docker安装、docker容器基本用法
  8. 华为MatePad有什么好用的软件?
  9. fs-extra 操作文件
  10. 十进制转十六进制(C++)