Python机器学习之SVM支持向量机


Posted in Python onDecember 27, 2017

SVM支持向量机是建立于统计学习理论上的一种分类算法,适合与处理具备高维特征的数据集。
SVM算法的数学原理相对比较复杂,好在由于SVM算法的研究与应用如此火爆,CSDN博客里也有大量的好文章对此进行分析,下面给出几个本人认为讲解的相当不错的:
支持向量机通俗导论(理解SVM的3层境界)
JULY大牛讲的是如此详细,由浅入深层层推进,以至于关于SVM的原理,我一个字都不想写了。。强烈推荐。
还有一个比较通俗的简单版本的:手把手教你实现SVM算法

SVN原理比较复杂,但是思想很简单,一句话概括,就是通过某种核函数,将数据在高维空间里寻找一个最优超平面,能够将两类数据分开。

针对不同数据集,不同的核函数的分类效果可能完全不一样。可选的核函数有这么几种:
线性函数:形如K(x,y)=x*y这样的线性函数;
多项式函数:形如K(x,y)=[(x·y)+1]^d这样的多项式函数;
径向基函数:形如K(x,y)=exp(-|x-y|^2/d^2)这样的指数函数;
Sigmoid函数:就是上一篇文章中讲到的Sigmoid函数。

我们就利用之前的几个数据集,直接给出Python代码,看看运行效果:

测试1:身高体重数据

# -*- coding: utf-8 -*- 
import numpy as np 
import scipy as sp 
from sklearn import svm 
from sklearn.cross_validation import train_test_split 
import matplotlib.pyplot as plt 
 
data  = [] 
labels = [] 
with open("data\\1.txt") as ifile: 
    for line in ifile: 
      tokens = line.strip().split(' ') 
      data.append([float(tk) for tk in tokens[:-1]]) 
      labels.append(tokens[-1]) 
x = np.array(data) 
labels = np.array(labels) 
y = np.zeros(labels.shape) 
y[labels=='fat']=1 
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.0) 
 
h = .02  
# create a mesh to plot in 
x_min, x_max = x_train[:, 0].min() - 0.1, x_train[:, 0].max() + 0.1 
y_min, y_max = x_train[:, 1].min() - 1, x_train[:, 1].max() + 1 
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), 
           np.arange(y_min, y_max, h)) 
 
''''' SVM ''' 
# title for the plots 
titles = ['LinearSVC (linear kernel)', 
     'SVC with polynomial (degree 3) kernel', 
     'SVC with RBF kernel', 
     'SVC with Sigmoid kernel'] 
clf_linear = svm.SVC(kernel='linear').fit(x, y) 
#clf_linear = svm.LinearSVC().fit(x, y) 
clf_poly  = svm.SVC(kernel='poly', degree=3).fit(x, y) 
clf_rbf   = svm.SVC().fit(x, y) 
clf_sigmoid = svm.SVC(kernel='sigmoid').fit(x, y) 
 
for i, clf in enumerate((clf_linear, clf_poly, clf_rbf, clf_sigmoid)): 
  answer = clf.predict(np.c_[xx.ravel(), yy.ravel()]) 
  print(clf) 
  print(np.mean( answer == y_train)) 
  print(answer) 
  print(y_train) 
 
  plt.subplot(2, 2, i + 1) 
  plt.subplots_adjust(wspace=0.4, hspace=0.4) 
   
  # Put the result into a color plot 
  z = answer.reshape(xx.shape) 
  plt.contourf(xx, yy, z, cmap=plt.cm.Paired, alpha=0.8) 
   
  # Plot also the training points 
  plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.cm.Paired) 
  plt.xlabel(u'身高') 
  plt.ylabel(u'体重') 
  plt.xlim(xx.min(), xx.max()) 
  plt.ylim(yy.min(), yy.max()) 
  plt.xticks(()) 
  plt.yticks(()) 
  plt.title(titles[i]) 
   
plt.show()

运行结果如下:

Python机器学习之SVM支持向量机

可以看到,针对这个数据集,使用3次多项式核函数的SVM,得到的效果最好。

测试2:影评态度

下面看看SVM在康奈尔影评数据集上的表现:(代码略)

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,  kernel='linear', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False)
0.814285714286

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,  kernel='poly', max_iter=-1, probability=False, random_state=None,  shrinking=True, tol=0.001, verbose=False)
0.492857142857

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

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,  kernel='sigmoid', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False)
0.492857142857

可见在该数据集上,线性分类器效果最好。

测试3:圆形边界

最后我们测试一个数据分类边界为圆形的情况:圆形内为一类,原型外为一类。看这类非线性的数据SVM表现如何:
测试数据生成代码如下所示:

''''' 数据生成 ''' 
h = 0.1 
x_min, x_max = -1, 1 
y_min, y_max = -1, 1 
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), 
           np.arange(y_min, y_max, h)) 
n = xx.shape[0]*xx.shape[1] 
x = np.array([xx.T.reshape(n).T, xx.reshape(n)]).T 
y = (x[:,0]*x[:,0] + x[:,1]*x[:,1] < 0.8) 
y.reshape(xx.shape) 
 
x_train, x_test, y_train, y_test\ 
  = train_test_split(x, y, test_size = 0.2)

测试结果如下:

SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,  kernel='linear', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False)
0.65
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,  kernel='poly', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False)
0.675
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,  kernel='rbf', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False)
0.9625
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,  kernel='sigmoid', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False)
0.65

Python机器学习之SVM支持向量机

可以看到,对于这种边界,径向基函数的SVM得到了近似完美的分类结果。而其他的分类器显然束手无策。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Flask框架学习笔记(一)安装篇(windows安装与centos安装)
Jun 25 Python
Python中的二叉树查找算法模块使用指南
Jul 04 Python
web.py在模板中输出美元符号的方法
Aug 26 Python
python实现的jpg格式图片修复代码
Apr 21 Python
python处理html转义字符的方法详解
Jul 01 Python
Python Unittest根据不同测试环境跳过用例的方法
Dec 16 Python
pyqt5 comboBox获得下标、文本和事件选中函数的方法
Jun 14 Python
python 多进程共享全局变量之Manager()详解
Aug 15 Python
Python如何执行系统命令
Sep 23 Python
python ssh 执行shell命令的示例
Sep 29 Python
使用Python制作一盏 3D 花灯喜迎元宵佳节
Feb 26 Python
Python趣味实战之手把手教你实现举牌小人生成器
Jun 07 Python
Python:Scrapy框架中Item Pipeline组件使用详解
Dec 27 #Python
手把手教你python实现SVM算法
Dec 27 #Python
Python中使用支持向量机SVM实践
Dec 27 #Python
Python使用Scrapy保存控制台信息到文本解析
Dec 27 #Python
Python简单生成随机姓名的方法示例
Dec 27 #Python
ubuntu中配置pyqt4环境教程
Dec 27 #Python
Python中Threading用法详解
Dec 27 #Python
You might like
落伍首发 php+mysql 采用ajax技术的 省 市 地 3级联动无刷新菜单 源码
2006/12/16 PHP
dhtmlxTree目录树增加右键菜单以及拖拽排序的实现方法
2013/04/26 PHP
jquery加载页面的方法(页面加载完成就执行)
2011/06/21 Javascript
JS的document.all函数使用示例
2013/12/30 Javascript
javascript 回到顶部效果的实现代码
2014/02/17 Javascript
JQuery boxy插件在IE中边角图片不显示问题的解决
2015/05/20 Javascript
基于jQuery通过jQuery.form.js插件使用ajax提交form表单
2015/08/17 Javascript
详解Javascript中的Object对象
2016/02/28 Javascript
Angular JS数据的双向绑定详解及实例
2016/12/31 Javascript
Angular2-primeNG文件上传模块FileUpload使用详解
2017/01/14 Javascript
vue.js学习笔记:如何加载本地json文件
2017/01/17 Javascript
简单实现bootstrap导航效果
2017/02/07 Javascript
Vue页面跳转动画效果的实现方法
2018/09/23 Javascript
vue实现新闻展示页的步骤详解
2019/04/11 Javascript
关于vue-cli 3配置打包优化要点(推荐)
2019/04/22 Javascript
深入浅析vue-cli@3.0 使用及配置说明
2019/05/08 Javascript
JS浮点数运算结果不精确的Bug解决
2019/08/01 Javascript
[03:24]2014DOTA2国际邀请赛 神秘商店生意火爆
2014/07/18 DOTA
python实现在pickling的时候压缩的方法
2014/09/25 Python
浅谈Python爬取网页的编码处理
2016/11/04 Python
Python实现登录接口的示例代码
2017/07/21 Python
Python实用技巧之利用元组代替字典并为元组元素命名
2018/07/11 Python
python面向对象实现名片管理系统文件版
2019/04/26 Python
Python-numpy实现灰度图像的分块和合并方式
2020/01/09 Python
最小二乘法及其python实现详解
2020/02/24 Python
Python如何使用队列方式实现多线程爬虫
2020/05/12 Python
python实现感知机模型的示例
2020/09/30 Python
python给list排序的简单方法
2020/12/10 Python
HTML5 移动页面自适应手机屏幕四类方法总结
2017/08/17 HTML / CSS
size?爱尔兰官方网站:英国伦敦的球鞋精品店
2019/03/31 全球购物
阿姆斯特丹城市卡:Amsterdam Pass
2019/12/01 全球购物
JSF面试题:Jsf中的核心类用那些?有什么作用?LiftCycle六大生命周期是什么?
2014/07/17 面试题
党的群众路线教育实践活动教师自我剖析材料
2014/10/09 职场文书
师德师风心得体会(2016精选篇)
2016/01/12 职场文书
教你怎么用Python操作MySql数据库
2021/05/31 Python
一文搞懂redux在react中的初步用法
2021/06/09 Javascript