SVM(Support Vector Machine)指的是支持向量机,是常见的一种判别方法。在机器学习领域,是一个有监督的学习模型,通常用来进行模式识别、分类以及回归分析。在n维空间中找到一个分类超平面,将空间上的点分类。一般而言,一个点距离超平面的远近可以表示为分类预测的确信或准确程度。SVM就是要最大化这个间隔值。而在虚线上的点便叫做支持向量Supprot Verctor。通过本任务,您将掌握以下内容:1、理解支持向量机(support vector machine)算法思想。2、掌握sklearn库对SVM的用法。3、熟悉机器学习构建模型并预测数据的思想。4、理解训练集和测试集的作用。5、掌握如何通过matplotlib库绘制图形。6、学会评估模型好坏的方法。

实验原理:

支持向量机(support vector machine)是一种分类算法,通过寻求结构化风险最小来提高学习机泛化能力,实现经验风险和置信范围的最小化,从而达到在统计样本量较少的情况下,亦能获得良好统计规律的目的。通俗来讲,它是一种二类分类模型,其基本模型定义为特征空间上的间隔最大的线性分类器,即支持向量机的学习策略便是间隔最大化,最终可转化为一个凸二次规划问题的求解。

具体原理:

1. 在n维空间中找到一个分类超平面,将空间上的点分类。如下图是线性分类的例子。

2. 一般而言,一个点距离超平面的远近可以表示为分类预测的确信或准确程度。SVM就是要最大化这个间隔值。而在虚线上的点便叫做支持向量Supprot Verctor。

3. 实际中,我们会经常遇到线性不可分的样例,此时,我们的常用做法是把样例特征映射到高维空间中去(如下图);

3. 线性不可分映射到高维空间,可能会导致维度大小高到可怕的(19维乃至无穷维的例子),导致计算复杂。核函数的价值在于它虽然也是讲特征进行从低维到高维的转换,但核函数绝就绝在它事先在低维上进行计算,而将实质上的分类效果表现在了高维上,也就如上文所说的避免了直接在高维空间中的复杂计算。

4.使用松弛变量处理数据噪音

sklearn中SVM的结构,及各个参数说明如下

sklearn.svm.SVC :

view plain copy

  1. sklearn.svm.SVC(C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, shrinking=True, probability=False,tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_shape=None,random_state=None)

参数说明:

view plain copy

  1. C:C-SVC的惩罚参数C?默认值是1.0

  2. C越大,相当于惩罚松弛变量,希望松弛变量接近0,即对误分类的惩罚增大,趋向于对训练集全分对的情况,这样对训练集测试时准确率很高,但泛化能力弱。C值小,对误分类的惩罚减小,允许容错,将他们当成噪声点,泛化能力较强。

  3. kernel :核函数,默认是rbf,可以是‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’

  4.   0 – 线性:u'v

  5.     1 – 多项式:(gamma*u'*v + coef0)^degree

  6.   2 – RBF函数:exp(-gamma|u-v|^2)

  7.   3 –sigmoid:tanh(gamma*u'*v + coef0)

  8. degree :多项式poly函数的维度,默认是3,选择其他核函数时会被忽略。

  9. gamma : ‘rbf’,‘poly’ 和‘sigmoid’的核函数参数。默认是’auto’,则会选择1/n_features

  10. coef0 :核函数的常数项。对于‘poly’和 ‘sigmoid’有用。

  11. probability :是否采用概率估计?.默认为False

  12. shrinking :是否采用shrinking heuristic方法,默认为true

  13. tol :停止训练的误差值大小,默认为1e-3

  14. cache_size :核函数cache缓存大小,默认为200

  15. class_weight :类别的权重,字典形式传递。设置第几类的参数C为weight*C(C-SVC中的C)

  16. verbose :允许冗余输出?

  17. max_iter :最大迭代次数。-1为无限制。

  18. decision_function_shape :‘ovo’, ‘ovr’ or None, default=None3

  19. random_state :数据洗牌时的种子值,int值

主要调节的参数有:C、kernel、degree、gamma、coef0。

系统环境

Linux Ubuntu 16.04

Python3.6

任务内容

用SVM算法对fetch_lfw_people数据进行人脸识别,并将预测结果可视化。

任务步骤

1.创建目录并下载实验所需的数据。

view plain copy

  1. mkdir -p /home/zhangyu/scikit_learn_data/lfw_home

  2. cd /home/zhangyu/scikit_learn_data/lfw_home

  3. wget http://192.168.1.100:60000/allfiles/ma_learn/lfwfunneled.tgz

  4. wget http://192.168.1.100:60000/allfiles/ma_learn/pairsDevTest.txt

  5. wget http://192.168.1.100:60000/allfiles/ma_learn/pairsDevTrain.txt

  6. wget http://192.168.1.100:60000/allfiles/ma_learn/pairs.txt

  7. tar xzvf lfwfunneled.tgz

2.新建Python project ,名为python15.

在python15项目下,新建Python file,名为SVM

3.用SVM算法对fetch_lfw_people数据进行人脸识别,并将预测结果可视化,完整代码如下:

view plain copy

  1. from __future__ import print_function

  2. from time import time

  3. import logging

  4. import matplotlib.pyplot as plt

  5. from sklearn.model_selection import train_test_split

  6. from sklearn.datasets import fetch_lfw_people

  7. from sklearn.model_selection import GridSearchCV

  8. from sklearn.metrics import classification_report

  9. from sklearn.metrics import confusion_matrix

  10. from sklearn.decomposition import PCA

  11. from sklearn.svm import SVC

  12. # Display progress logs on stdout

  13. logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')

  14. ###############################################################################

  15. # Download the data, if not already on disk and load it as numpy arrays

  16. lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)

  17. # introspect the images arrays to find the shapes (for plotting)

  18. n_samples, h, w = lfw_people.images.shape

  19. # for machine learning we use the 2 data directly (as relative pixel

  20. # positions info is ignored by this model)

  21. X = lfw_people.data

  22. n_features = X.shape[1]

  23. # the label to predict is the id of the person

  24. y = lfw_people.target

  25. target_names = lfw_people.target_names

  26. n_classes = target_names.shape[0]

  27. print("Total dataset size:")

  28. print("n_samples: %d" % n_samples)

  29. print("n_features: %d" % n_features)

  30. print("n_classes: %d" % n_classes)

  31. ###############################################################################

  32. # Split into a training set and a test set using a stratified k fold

  33. # split into a training and testing set

  34. X_train, X_test, y_train, y_test = train_test_split(

  35. X, y, test_size=0.25)

  36. ###############################################################################

  37. # Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled

  38. # dataset): unsupervised feature extraction / dimensionality reduction

  39. n_components = 150

  40. print("Extracting the top %d eigenfaces from %d faces"

  41. % (n_components, X_train.shape[0]))

  42. t0 = time()

  43. pca = PCA(svd_solver='randomized',n_components=n_components, whiten=True).fit(X_train)

  44. print("done in %0.3fs" % (time() - t0))

  45. eigenfaces = pca.components_.reshape((n_components, h, w))

  46. print("Projecting the input data on the eigenfaces orthonormal basis")

  47. t0 = time()

  48. X_train_pca = pca.transform(X_train)

  49. X_test_pca = pca.transform(X_test)

  50. print("done in %0.3fs" % (time() - t0))

  51. ###############################################################################

  52. # Train a SVM classification model

  53. print("Fitting the classifier to the training set")

  54. t0 = time()

  55. param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],

  56. 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }

  57. clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)

  58. clf = clf.fit(X_train_pca, y_train)

  59. print("done in %0.3fs" % (time() - t0))

  60. print("Best estimator found by grid search:")

  61. print(clf.best_estimator_)

  62. ###############################################################################

  63. # Quantitative evaluation of the model quality on the test set

  64. print("Predicting people's names on the test set")

  65. t0 = time()

  66. y_pred = clf.predict(X_test_pca)

  67. print("done in %0.3fs" % (time() - t0))

  68. print(classification_report(y_test, y_pred, target_names=target_names))

  69. print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))

  70. ###############################################################################

  71. # Qualitative evaluation of the predictions using matplotlib

  72. def plot_gallery(images, titles, h, w, n_row=3, n_col=4):

  73. """Helper function to plot a gallery of portraits"""

  74. plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))

  75. plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)

  76. for i in range(n_row * n_col):

  77. plt.subplot(n_row, n_col, i + 1)

  78. plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)

  79. plt.title(titles[i], size=12)

  80. plt.xticks(())

  81. plt.yticks(())

  82. # plot the result of the prediction on a portion of the test set

  83. def title(y_pred, y_test, target_names, i):

  84. pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]

  85. true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]

  86. return 'predicted: %s\ntrue:      %s' % (pred_name, true_name)

  87. prediction_titles = [title(y_pred, y_test, target_names, i)

  88. for i in range(y_pred.shape[0])]

  89. plot_gallery(X_test, prediction_titles, h, w)

  90. # plot the gallery of the most significative eigenfaces

  91. eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]

  92. plot_gallery(eigenfaces, eigenface_titles, h, w)

  93. plt.show()

4.对完整代码进行分部描述,用import导入实验所用到的包

view plain copy

  1. from __future__ import print_function

  2. from time import time

  3. import logging

  4. import matplotlib.pyplot as plt

  5. from sklearn.model_selection import train_test_split

  6. from sklearn.datasets import fetch_lfw_people

  7. from sklearn.model_selection import GridSearchCV

  8. from sklearn.metrics import classification_report

  9. from sklearn.metrics import confusion_matrix

  10. from sklearn.decomposition import PCA

  11. from sklearn.svm import SVC

5.提取数据

view plain copy

  1. lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)

  2. # introspect the images arrays to find the shapes (for plotting)

  3. n_samples, h, w = lfw_people.images.shape

  4. # for machine learning we use the 2 data directly (as relative pixel

  5. # positions info is ignored by this model)

  6. X = lfw_people.data

  7. n_features = X.shape[1]

  8. # the label to predict is the id of the person

  9. y = lfw_people.target

  10. target_names = lfw_people.target_names

  11. n_classes = target_names.shape[0]

  12. print("Total dataset size:")

  13. print("n_samples: %d" % n_samples)

  14. print("n_features: %d" % n_features)

  15. print("n_classes: %d" % n_classes)

运行结果:

6.特征提取

view plain copy

  1. X_train, X_test, y_train, y_test = train_test_split(

  2. X, y, test_size=0.25)

  3. ###############################################################################

  4. # Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled

  5. # dataset): unsupervised feature extraction / dimensionality reduction

  6. n_components = 150

  7. print("Extracting the top %d eigenfaces from %d faces"

  8. % (n_components, X_train.shape[0]))

  9. t0 = time()

  10. pca = PCA(svd_solver='randomized',n_components=n_components, whiten=True).fit(X_train)

  11. print("done in %0.3fs" % (time() - t0))

  12. eigenfaces = pca.components_.reshape((n_components, h, w))

  13. print("Projecting the input data on the eigenfaces orthonormal basis")

  14. t0 = time()

  15. X_train_pca = pca.transform(X_train)

  16. X_test_pca = pca.transform(X_test)

  17. print("done in %0.3fs" % (time() - t0))

运行结果:

7.建立SVM分类模型

view plain copy

  1. print("Fitting the classifier to the training set")

  2. t0 = time()

  3. param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],

  4. 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }

  5. clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)

  6. clf = clf.fit(X_train_pca, y_train)

  7. print("done in %0.3fs" % (time() - t0))

  8. print("Best estimator found by grid search:")

  9. print(clf.best_estimator_)

运行结果:

8.模型评估

view plain copy

  1. print("Predicting people's names on the test set")

  2. t0 = time()

  3. y_pred = clf.predict(X_test_pca)

  4. print("done in %0.3fs" % (time() - t0))

  5. print(classification_report(y_test, y_pred, target_names=target_names))

  6. print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))

运行结果:

9.预测结果可视化

view plain copy

  1. def plot_gallery(images, titles, h, w, n_row=3, n_col=4):

  2. """Helper function to plot a gallery of portraits"""

  3. plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))

  4. plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)

  5. for i in range(n_row * n_col):

  6. plt.subplot(n_row, n_col, i + 1)

  7. plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)

  8. plt.title(titles[i], size=12)

  9. plt.xticks(())

  10. plt.yticks(())

  11. # plot the result of the prediction on a portion of the test set

  12. def title(y_pred, y_test, target_names, i):

  13. pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]

  14. true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]

  15. return 'predicted: %s\ntrue:      %s' % (pred_name, true_name)

  16. prediction_titles = [title(y_pred, y_test, target_names, i)

  17. for i in range(y_pred.shape[0])]

  18. plot_gallery(X_test, prediction_titles, h, w)

  19. # plot the gallery of the most significative eigenfaces

  20. eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]

  21. plot_gallery(eigenfaces, eigenface_titles, h, w)

  22. plt.show()

运行结果:

eigenface:

svm rbf人脸识别 yale_实操课——机器学习之人脸识别相关推荐

  1. 抖音起号技巧实操课:可以直接上手的注册与养号的方法和技巧

    抖音起号技巧实操课:可以直接上手的注册与养号的方法和技巧 前面讲了关于怎么做好账号定位,账号起名,账号资料准备等等,今天给大家讲的是账号起号技巧实操,这里全是干货,大家一定要做好笔记,然后认真的按照我 ...

  2. 计算机应用基础简单实操,浅谈《计算机应用基础》实操课的教学管理

    [摘 要] 本文就如何提高学生的计算机基本操作能力,以计算机实操课的教学管理为主线,通过严谨的课堂组织和科学的辅导方法两方面进行论述. [关键词] 计算机 基本操作能力 课堂组织 辅导方法 随着全球信 ...

  3. 短视频底层实操课,让你迅速从短视频新手变成高手

    课程来自增长黑客董十一的短视频底层实操课,价值1999元. 课程内容均为董十一老师自身总结提炼的硬核运营实战技巧和方法论,真实可靠,贴合行业,课程讲解深入浅出,内容实用,运营模式可复制实操.短视频逐渐 ...

  4. 计算机文档制作教程,计算机实操课:用word制作电子小报教程.doc

    计算机实操课:用word制作电子小报教程 制作电子小报 教学目标: 1.学生综合运用Word中的文字.图片.表格等工具,发挥自主性,设计电子报纸. 2.通过讨论.设计和分工合作的方式,设计报纸版面,组 ...

  5. 一堂计算机课,“星愿”第一堂电脑实操课

    原标题:"星愿"第一堂电脑实操课 2019年7月23日岭南师范学院物理科学与技术学院 "星愿"社会实践队在湛江市廉江市石城镇山头小学实践的第九天. 下午,调研组 ...

  6. java人脸识别_Python 实现在 App 端的人脸识别!手机解锁人脸识别

    最近闲来无事,研究研究在安卓上跑 Python,想起以前玩过的 kivy 技术,kivy 是一个跨平台的 UI 框架,当然对我们最有用的是,kivy 可以把 Python 代码打包成安卓应用. 但是由 ...

  7. 【项目实战-MATLAB】:基于机器学习的虹膜识别系统设计

    基于机器学习的虹膜识别系统设计 设计的虹膜识别系统流程图如图 1 所示,在图像的预处理过程中主要包括虹膜定位.虹膜区域提取.虹膜区域极坐标变换和归一化处理.最后采用SVM识别方法实现虹膜识别. 图1 ...

  8. 计算机培训微课设计与实现,微课制作相关软件的实操培训

    为全面提升我校教师信息技术应用能力,促进教师转变教育教学方式,推动广大教师在课堂教学和日常工作中有效应用信息技术,实现信息技术与教育教学深度融合.5月9日下午,教师发展中心在计算机基础实验教学中心组织 ...

  9. 【优秀课设】基于OpenCV-Python的树莓派人脸识别及89C52单片机控制系统设计(指定照片进行识别、遍历目录下所有照片依次识别)

    基于OpenCV-Python的树莓派人脸识别及89C52单片机控制系统设计 (指定照片进行识别) 参照之前的文章所改进 增加视频随时标注功能 https://blog.csdn.net/weixin ...

最新文章

  1. 模板路径,模板变量,过滤器和静态文件的引用
  2. 人类为什么会同情机器人,是否需要禁止虐待机器人
  3. fastjson 循环json字符串_FastJson拒绝服务漏洞分析
  4. luogu P5292 [HNOI2019]校园旅行
  5. 在mac下安装matplotlib,xlrd
  6. 韦东山驱动视频笔记——3.字符设备驱动程序之poll机制
  7. 2、MyEclipse和Eclipse调优,MyEclipse配置(tomcat和jdk的内存设置),jar引入相关知识点,将Java项目编程web项目的办法
  8. js实现svg图形转存为图片下载[转]
  9. 晶振,数字电路的心脏~
  10. 对特朗普获胜感到意外? 那你是被社交媒体迷惑了
  11. Kibana 的安装(Windows版本)新手入门
  12. 送书 | 生物信息学习的一点体会
  13. Oracle数据库导入csv文件(sqlldr命令行)
  14. iOS 推送 获取手机设备的 deviceToken
  15. 大数组情况下栈溢出解决
  16. java登录网站_如何使用Java登录网站
  17. php 中文逗号 转英文,PHP把空格、换行符、中文逗号等替换成英文逗号的正则表达式...
  18. plc中int数据类型范围_AB的PLC中,这些数据类型:INT、DINT、SINT、REAL和BOOL,分别代表什么意思?...
  19. 一个国企老兵给后辈们的忠告:三十岁之前远离国企
  20. day2-运算符和分支

热门文章

  1. 认清自己,愉快度过每一天
  2. Conv1D和Conv2D的区别
  3. 嵌入式开发在过去20年中是如何演变的
  4. 未来几年自动驾驶预测(下)
  5. 端口号被占用怎么解决
  6. 2021年大数据Hadoop(二十二):MapReduce的自定义分组
  7. 2021年大数据Spark(十六):Spark Core的RDD算子练习
  8. android.mk 里面内容介绍
  9. python 2x xlrd使用merged_cells 读取的合并单元格为空
  10. css 伪元素::after与::before的使用