侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   341

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() 

运行结果如下:

可以看到,针对这个数据集,使用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

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

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


  • 上一条:
    Python实现连接postgresql数据库的方法分析
    下一条:
    Python:Scrapy框架中Item Pipeline组件使用详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客