python SVM 线性分类模型的实现


Posted in Python onJuly 19, 2019

运行环境:win10 64位 py 3.6 pycharm 2018.1.1

导入对应的包和数据

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets,linear_model,cross_validation,svm
def load_data_regression():
  diabetes = datasets.load_diabetes()
  return cross_validation.train_test_split(diabetes,diabetes.target,test_size=0.25,random_state=0)
def load_data_classfication():
  iris = datasets.load_iris()
  X_train = iris.data
  y_train = iris.target
  return cross_validation.train_test_split(X_train,y_train,test_size=0.25,random_state=0,stratify=y_train)
#线性分类SVM
def test_LinearSVC(*data):
  X_train,X_test,y_train,y_test = data
  cls = svm.LinearSVC()
  cls.fit(X_train,y_train)
  print('Coefficients:%s,intercept%s'%(cls.coef_,cls.intercept_))
  print('Score:%.2f'%cls.score(X_test,y_test))
X_train,X_test,y_train,y_test = load_data_classfication()
test_LinearSVC(X_train,X_test,y_train,y_test)
def test_LinearSVC_loss(*data):
  X_train,X_test,y_train,y_test = data
  losses = ['hinge','squared_hinge']
  for loss in losses:
    cls = svm.LinearSVC(loss=loss)
    cls.fit(X_train,y_train)
    print('loss:%s'%loss)
    print('Coefficients:%s,intercept%s'%(cls.coef_,cls.intercept_))
    print('Score:%.2f'%cls.score(X_test,y_test))
X_train,X_test,y_train,y_test = load_data_classfication()
test_LinearSVC_loss(X_train,X_test,y_train,y_test)
#考察罚项形式的影响
def test_LinearSVC_L12(*data):
  X_train,X_test,y_train,y_test = data
  L12 = ['l1','l2']
  for p in L12:
    cls = svm.LinearSVC(penalty=p,dual=False)
    cls.fit(X_train,y_train)
    print('penalty:%s'%p)
    print('Coefficients:%s,intercept%s'%(cls.coef_,cls.intercept_))
    print('Score:%.2f'%cls.score(X_test,y_test))
X_train,X_test,y_train,y_test = load_data_classfication()
test_LinearSVC_L12(X_train,X_test,y_train,y_test)
#考察罚项系数C的影响
def test_LinearSVC_C(*data):
  X_train,X_test,y_train,y_test = data
  Cs = np.logspace(-2,1)
  train_scores = []
  test_scores = []
  for C in Cs:
    cls = svm.LinearSVC(C=C)
    cls.fit(X_train,y_train)
    train_scores.append(cls.score(X_train,y_train))
    test_scores.append(cls.score(X_test,y_test))
  fig = plt.figure()
  ax = fig.add_subplot(1,1,1)
  ax.plot(Cs,train_scores,label = 'Training score')
  ax.plot(Cs,test_scores,label = 'Testing score')
  ax.set_xlabel(r'C')
  ax.set_xscale('log')
  ax.set_ylabel(r'score')
  ax.set_title('LinearSVC')
  ax.legend(loc='best')
  plt.show()
X_train,X_test,y_train,y_test = load_data_classfication()
test_LinearSVC_C(X_train,X_test,y_train,y_test)

python SVM 线性分类模型的实现

#非线性分类SVM
#线性核
def test_SVC_linear(*data):
  X_train, X_test, y_train, y_test = data
  cls = svm.SVC(kernel='linear')
  cls.fit(X_train,y_train)
  print('Coefficients:%s,intercept%s'%(cls.coef_,cls.intercept_))
  print('Score:%.2f'%cls.score(X_test,y_test))
X_train,X_test,y_train,y_test = load_data_classfication()
test_SVC_linear(X_train,X_test,y_train,y_test)

python SVM 线性分类模型的实现

#考察高斯核
def test_SVC_rbf(*data):
  X_train, X_test, y_train, y_test = data
  ###测试gamm###
  gamms = range(1, 20)
  train_scores = []
  test_scores = []
  for gamm in gamms:
    cls = svm.SVC(kernel='rbf', gamma=gamm)
    cls.fit(X_train, y_train)
    train_scores.append(cls.score(X_train, y_train))
    test_scores.append(cls.score(X_test, y_test))
  fig = plt.figure()
  ax = fig.add_subplot(1, 1, 1)
  ax.plot(gamms, train_scores, label='Training score', marker='+')
  ax.plot(gamms, test_scores, label='Testing score', marker='o')
  ax.set_xlabel(r'$\gamma$')
  ax.set_ylabel(r'score')
  ax.set_ylim(0, 1.05)
  ax.set_title('SVC_rbf')
  ax.legend(loc='best')
  plt.show()
X_train,X_test,y_train,y_test = load_data_classfication()
test_SVC_rbf(X_train,X_test,y_train,y_test)

python SVM 线性分类模型的实现

#考察sigmoid核
def test_SVC_sigmod(*data):
  X_train, X_test, y_train, y_test = data
  fig = plt.figure()
  ###测试gamm###
  gamms = np.logspace(-2, 1)
  train_scores = []
  test_scores = []
  for gamm in gamms:
    cls = svm.SVC(kernel='sigmoid',gamma=gamm,coef0=0)
    cls.fit(X_train, y_train)
    train_scores.append(cls.score(X_train, y_train))
    test_scores.append(cls.score(X_test, y_test))
  ax = fig.add_subplot(1, 2, 1)
  ax.plot(gamms, train_scores, label='Training score', marker='+')
  ax.plot(gamms, test_scores, label='Testing score', marker='o')
  ax.set_xlabel(r'$\gamma$')
  ax.set_ylabel(r'score')
  ax.set_xscale('log')
  ax.set_ylim(0, 1.05)
  ax.set_title('SVC_sigmoid_gamm')
  ax.legend(loc='best')

  #测试r
  rs = np.linspace(0,5)
  train_scores = []
  test_scores = []
  for r in rs:
    cls = svm.SVC(kernel='sigmoid', gamma=0.01, coef0=r)
    cls.fit(X_train, y_train)
    train_scores.append(cls.score(X_train, y_train))
    test_scores.append(cls.score(X_test, y_test))
  ax = fig.add_subplot(1, 2, 2)
  ax.plot(rs, train_scores, label='Training score', marker='+')
  ax.plot(rs, test_scores, label='Testing score', marker='o')
  ax.set_xlabel(r'r')
  ax.set_ylabel(r'score')
  ax.set_ylim(0, 1.05)
  ax.set_title('SVC_sigmoid_r')
  ax.legend(loc='best')
  plt.show()
X_train,X_test,y_train,y_test = load_data_classfication()
test_SVC_sigmod(X_train,X_test,y_train,y_test)

python SVM 线性分类模型的实现

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

Python 相关文章推荐
python网络编程之TCP通信实例和socketserver框架使用例子
Apr 25 Python
在Python的Django框架下使用django-tagging的教程
May 30 Python
Python爬虫框架Scrapy实战之批量抓取招聘信息
Aug 07 Python
python递归打印某个目录的内容(实例讲解)
Aug 30 Python
浅谈Python使用Bottle来提供一个简单的web服务
Dec 27 Python
DES加密解密算法之python实现版(图文并茂)
Dec 06 Python
通过python爬虫赚钱的方法
Jan 29 Python
Python替换月份为英文缩写的实现方法
Jul 15 Python
Python使用贪婪算法解决问题
Oct 22 Python
Python 装饰器原理、定义与用法详解
Dec 07 Python
django Layui界面点击弹出对话框并请求逻辑生成分页的动态表格实例
May 12 Python
python中sys模块是做什么用的
Aug 16 Python
Django密码系统实现过程详解
Jul 19 #Python
Tensorflow实现酸奶销量预测分析
Jul 19 #Python
Python实现基于SVM的分类器的方法
Jul 19 #Python
Tensorflow模型实现预测或识别单张图片
Jul 19 #Python
python django下载大的csv文件实现方法分析
Jul 19 #Python
python使用flask与js进行前后台交互的例子
Jul 19 #Python
Django 模型类(models.py)的定义详解
Jul 19 #Python
You might like
PHP4中实现动态代理
2006/10/09 PHP
php中使用redis队列操作实例代码
2013/02/07 PHP
php实现阿拉伯数字和罗马数字相互转换的方法
2015/04/17 PHP
示例详解Laravel的注册重构
2016/08/14 PHP
基于PHP的加载类操作以及其他两种魔术方法的应用实例
2017/08/28 PHP
jQuery 页面载入进度条实现代码
2009/02/08 Javascript
NodeJS学习笔记之FS文件模块
2015/01/13 NodeJs
javascript修改图片src的方法
2015/01/27 Javascript
jquery中的工具使用方法$.isFunction, $.isArray(), $.isWindow()
2015/08/09 Javascript
Javascript之Math对象详解
2016/06/07 Javascript
ionic由于使用了header和subheader导致被遮挡的问题的两种解决方法
2016/09/22 Javascript
通过JS获取Request.QueryString()参数的值实现方法
2016/09/27 Javascript
AngularJS指令用法详解
2016/11/02 Javascript
用jQuery实现可输入多选下拉组合框实例代码
2017/01/18 Javascript
JS对象与json字符串相互转换实现方法示例
2018/06/14 Javascript
超好用的jQuery分页插件jpaginate用法示例【附源码下载】
2018/12/06 jQuery
Vue编写可显示周和月模式的日历 Vue自定义日历内容的显示
2019/06/26 Javascript
浅谈vue项目用到的mock数据接口的两种方式
2019/10/09 Javascript
如何基于filter实现网站整体变灰功能
2020/04/17 Javascript
jQuery实现滑动开关效果
2020/08/02 jQuery
基于javascript实现移动端轮播图效果
2020/12/21 Javascript
python获取从命令行输入数字的方法
2015/04/29 Python
python魔法方法-自定义序列详解
2016/07/21 Python
python用模块zlib压缩与解压字符串和文件的方法
2016/12/16 Python
python数字图像处理之高级滤波代码详解
2017/11/23 Python
Python3+django2.0+apache2+ubuntu14部署网站上线的方法
2018/07/07 Python
pandas基于时间序列的固定时间间隔求均值的方法
2019/07/04 Python
解决import tensorflow as tf 出错的原因
2020/04/16 Python
今天学到的CSS最新技术(与图片背景相关)
2012/12/24 HTML / CSS
深入浅析css3 border-image边框图像详解
2015/11/24 HTML / CSS
iframe在移动端的缩放的示例代码
2018/10/12 HTML / CSS
2015年护理工作总结范文
2015/04/03 职场文书
看上去很美观后感
2015/06/10 职场文书
大学生党课心得体会
2016/01/07 职场文书
Python入门之使用pandas分析excel数据
2021/05/12 Python