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 相关文章推荐
django与小程序实现登录验证功能的示例代码
Feb 19 Python
Python实现打砖块小游戏代码实例
May 18 Python
python文件转为exe文件的方法及用法详解
Jul 08 Python
django页面跳转问题及注意事项
Jul 18 Python
python通过txt文件批量安装依赖包的实现步骤
Aug 13 Python
Django自定义模板过滤器和标签的实现方法
Aug 21 Python
Python中输入和输出(打印)数据实例方法
Oct 13 Python
Pandas 缺失数据处理的实现
Nov 04 Python
PyCharm如何导入python项目的方法
Feb 06 Python
Python获取android设备cpu和内存占用情况
Nov 15 Python
python基于openpyxl生成excel文件
Dec 23 Python
Python 中的函数装饰器和闭包详解
Feb 06 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 与 MySQL 数据库操作函数详解
2006/12/06 PHP
PHP无刷新上传文件实现代码
2011/09/19 PHP
简单的方法让你的后台登录更加安全(php中加session验证)
2012/08/22 PHP
是 WordPress 让 PHP 更流行了 而不是框架
2016/02/03 PHP
Laravel学习教程之View模块详解
2017/09/18 PHP
Z-Blog中用到的js代码
2007/03/15 Javascript
javascript 在firebug调试时用console.log的方法
2012/05/10 Javascript
ajax异步刷新实现更新数据库
2012/12/03 Javascript
简体中文转换繁体中文(实现代码)
2013/12/25 Javascript
引用外部脚本时script标签关闭的写法
2014/01/20 Javascript
JavaScript获取网页表单提交方式的方法
2015/04/02 Javascript
深入理解AngularJS中的ng-bind-html指令和$sce服务
2016/09/08 Javascript
JavaScript中关于for循环删除数组元素内容时出现的问题
2016/11/21 Javascript
Bootstrap基本组件学习笔记之进度条(15)
2016/12/08 Javascript
AngularJS表格样式简单设置方法示例
2017/03/03 Javascript
微信小程序 获取二维码实例详解
2017/06/23 Javascript
微信小程序开发中的疑问解答汇总
2017/07/03 Javascript
基于vue.js快速搭建图书管理平台
2017/10/29 Javascript
JS+HTML5本地存储Localstorage实现注册登录及验证功能示例
2020/02/10 Javascript
Vue执行方法,方法获取data值,设置data值,方法传值操作
2020/08/05 Javascript
vue 如何使用递归组件
2020/10/23 Javascript
简单实现python爬虫功能
2015/12/31 Python
Python编程实现的简单神经网络算法示例
2018/01/26 Python
Python基于SMTP协议实现发送邮件功能详解
2018/08/14 Python
python 读取鼠标点击坐标的实例
2018/12/29 Python
PyQt5 QListWidget选择多项并返回的实例
2019/06/17 Python
解决tensorflow打印tensor有省略号的问题
2020/02/04 Python
html5使用canvas画一条线
2014/12/15 HTML / CSS
Nasty Gal英国:美国女性服饰销售网站
2021/03/02 全球购物
新闻系毕业生推荐信
2013/11/16 职场文书
大学生职业生涯规划书参考模板
2014/03/05 职场文书
大四学生找工作的自荐信
2014/03/27 职场文书
《草原的早晨》教学反思
2014/04/08 职场文书
技术入股合作协议书
2014/10/07 职场文书
统计员岗位职责范本
2015/04/14 职场文书
教你使用Ubuntu搭建DNS服务器
2022/09/23 Servers