前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何用Python实现支持向量机(SVM)

如何用Python实现支持向量机(SVM)

作者头像
机器学习AI算法工程
发布2018-03-13 11:14:54
1.6K0
发布2018-03-13 11:14:54
举报

SVM支持向量机是建立于统计学习理论上的一种分类算法,适合与处理具备高维特征的数据集。

SVM算法的数学原理相对比较复杂,好在由于SVM算法的研究与应用如此火爆,CSDN博客里也有大量的好文章对此进行分析,下面给出几个本人认为讲解的相当不错的:

支持向量机通俗导论(理解SVM的3层境界):http://blog.csdn.net/v_july_v/article/details/7624837

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:身高体重数据

[python] view plaincopy

  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import scipy as sp
  4. from sklearn import svm
  5. from sklearn.cross_validation import train_test_split
  6. import matplotlib.pyplot as plt
  7. data = []
  8. labels = []
  9. with open("data\\1.txt") as ifile:
  10. for line in ifile:
  11. tokens = line.strip().split(' ')
  12. data.append([float(tk) for tk in tokens[:-1]])
  13. labels.append(tokens[-1])
  14. x = np.array(data)
  15. labels = np.array(labels)
  16. y = np.zeros(labels.shape)
  17. y[labels=='fat']=1
  18. x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.0)
  19. h = .02
  20. # create a mesh to plot in
  21. x_min, x_max = x_train[:, 0].min() - 0.1, x_train[:, 0].max() + 0.1
  22. y_min, y_max = x_train[:, 1].min() - 1, x_train[:, 1].max() + 1
  23. xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
  24. np.arange(y_min, y_max, h))
  25. ''''' SVM '''
  26. # title for the plots
  27. titles = ['LinearSVC (linear kernel)',
  28. 'SVC with polynomial (degree 3) kernel',
  29. 'SVC with RBF kernel',
  30. 'SVC with Sigmoid kernel']
  31. clf_linear = svm.SVC(kernel='linear').fit(x, y)
  32. #clf_linear = svm.LinearSVC().fit(x, y)
  33. clf_poly = svm.SVC(kernel='poly', degree=3).fit(x, y)
  34. clf_rbf = svm.SVC().fit(x, y)
  35. clf_sigmoid = svm.SVC(kernel='sigmoid').fit(x, y)
  36. for i, clf in enumerate((clf_linear, clf_poly, clf_rbf, clf_sigmoid)):
  37. answer = clf.predict(np.c_[xx.ravel(), yy.ravel()])
  38. print(clf)
  39. print(np.mean( answer == y_train))
  40. print(answer)
  41. print(y_train)
  42. plt.subplot(2, 2, i + 1)
  43. plt.subplots_adjust(wspace=0.4, hspace=0.4)
  44. # Put the result into a color plot
  45. z = answer.reshape(xx.shape)
  46. plt.contourf(xx, yy, z, cmap=plt.cm.Paired, alpha=0.8)
  47. # Plot also the training points
  48. plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.cm.Paired)
  49. plt.xlabel(u'身高')
  50. plt.ylabel(u'体重')
  51. plt.xlim(xx.min(), xx.max())
  52. plt.ylim(yy.min(), yy.max())
  53. plt.xticks(())
  54. plt.yticks(())
  55. plt.title(titles[i])
  56. 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表现如何:

测试数据生成代码如下所示:

[python] view plaincop

  1. ''''' 数据生成 '''
  2. h = 0.1
  3. x_min, x_max = -1, 1
  4. y_min, y_max = -1, 1
  5. xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
  6. np.arange(y_min, y_max, h))
  7. n = xx.shape[0]*xx.shape[1]
  8. x = np.array([xx.T.reshape(n).T, xx.reshape(n)]).T
  9. y = (x[:,0]*x[:,0] + x[:,1]*x[:,1] < 0.8)
  10. y.reshape(xx.shape)
  11. x_train, x_test, y_train, y_test\
  12. = 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得到了近似完美的分类结果。而其他的分类器显然束手无策。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2015-11-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 大数据挖掘DT数据分析 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 测试1:身高体重数据
  • 测试2:影评态度
  • 测试3:圆形边界
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档