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读文件逐行处理的示例代码分享
Dec 27 Python
python爬虫爬取淘宝商品信息(selenum+phontomjs)
Feb 24 Python
python实现决策树ID3算法的示例代码
May 30 Python
对python 多个分隔符split 的实例详解
Dec 20 Python
python操作kafka实践的示例代码
Jun 19 Python
python与C、C++混编的四种方式(小结)
Jul 15 Python
Python爬虫 scrapy框架爬取某招聘网存入mongodb解析
Jul 31 Python
python中dict()的高级用法实现
Nov 13 Python
如何利用Python 进行边缘检测
Oct 14 Python
python如何快速拼接字符串
Oct 28 Python
Python lxml库的简单介绍及基本使用讲解
Dec 22 Python
python之基数排序的实现
Jul 26 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
php 变量未定义等错误的解决方法
2011/01/12 PHP
WebQQ最新登陆协议的用法
2014/12/22 PHP
php实现数组按指定KEY排序的方法
2015/03/30 PHP
php+mongodb判断坐标是否在指定多边形区域内的实例
2016/10/28 PHP
Jquery 高亮显示文本中重要的关键字
2009/12/24 Javascript
基于jquery循环map功能的代码
2011/02/26 Javascript
jQuery中[attribute*=value]选择器用法实例
2014/12/31 Javascript
深入剖析JavaScript编程中的对象概念
2015/10/21 Javascript
jQuery Easyui学习之datagrid 动态添加、移除editor
2016/01/27 Javascript
javascript数组去重小结
2016/03/07 Javascript
JS闭包、作用域链、垃圾回收、内存泄露相关知识小结
2016/05/16 Javascript
jQuery实现的购物车物品数量加减功能代码
2016/11/16 Javascript
详解如何使用 vue-cli 开发多页应用
2017/12/16 Javascript
在vue项目中使用element-ui的Upload上传组件的示例
2018/02/08 Javascript
浅谈Angular 的变化检测的方法
2018/03/01 Javascript
浅谈TypeScript 用 Webpack/ts-node 运行的配置记录
2019/10/11 Javascript
[01:43]深扒TI7聊天轮盘语音出处4
2017/05/11 DOTA
[04:05]TI9战队采访 - Natus Vincere
2019/08/22 DOTA
Django原生sql也能使用Paginator分页的示例代码
2017/11/15 Python
利用Hyperic调用Python实现进程守护
2018/01/02 Python
Python3.6通过自带的urllib通过get或post方法请求url的实例
2018/05/10 Python
一文带你了解Python中的字符串是什么
2018/11/20 Python
VSCode Python开发环境配置的详细步骤
2019/02/22 Python
详解Matplotlib绘图之属性设置
2019/08/23 Python
python orm 框架中sqlalchemy用法实例详解
2020/02/02 Python
python如何代码集体右移
2020/07/20 Python
中粮集团旗下食品网上购物网站:我买网
2016/09/22 全球购物
澳大利亚一站式数码相机商店:CameraPro
2020/03/09 全球购物
面向对象概念面试题(.NET)
2016/11/04 面试题
大一自我鉴定范文
2013/10/04 职场文书
教师实习期自我鉴定
2013/10/06 职场文书
物业电工岗位职责
2013/11/20 职场文书
求职面试个人自我评价
2014/02/28 职场文书
实名检举信范文
2015/03/02 职场文书
年度考核表个人总结
2015/03/06 职场文书
nginx配置指令之server_name的具体使用
2022/08/14 Servers