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中的__init__()方法
May 02 Python
详解python 拆包可迭代数据如tuple, list
Dec 29 Python
Python实现自定义顺序、排列写入数据到Excel的方法
Apr 23 Python
Python2和Python3中urllib库中urlencode的使用注意事项
Nov 26 Python
python画图系列之个性化显示x轴区段文字的实例
Dec 13 Python
使用python实现语音文件的特征提取方法
Jan 09 Python
浅谈Python 列表字典赋值的陷阱
Jan 20 Python
打包python 加icon 去掉cmd黑窗口方法
Jun 24 Python
django多个APP的urls设置方法(views重复问题解决)
Jul 19 Python
django2.2 和 PyMySQL版本兼容问题
Feb 17 Python
python 写函数在一定条件下需要调用自身时的写法说明
Jun 01 Python
PyQt5中QSpinBox计数器的实现
Jan 18 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 购物车的例子
2009/05/04 PHP
函数中使用require_once问题深入探讨 优雅的配置文件定义方法推荐
2014/07/02 PHP
Yii的Srbac插件用法详解
2016/07/14 PHP
PHP获取当前执行php文件名的代码
2017/03/02 PHP
PHP字典树(Trie树)定义与实现方法示例
2017/10/09 PHP
PHP与Web页面交互操作实例分析
2020/06/02 PHP
javascript英文日期(有时间)选择器
2007/05/02 Javascript
图片轮换效果实现代码(点击按钮停止执行)
2013/04/12 Javascript
js字符串日期yyyy-MM-dd转化为date示例代码
2014/03/06 Javascript
JavaScript中使用Object.create()创建对象介绍
2014/12/30 Javascript
javascript递归回溯法解八皇后问题
2015/04/22 Javascript
AngularJS 自定义指令详解及示例代码
2016/08/17 Javascript
jQuery实现点击后高亮背景固定显示的菜单效果【附demo源码下载】
2016/09/21 Javascript
JavaScript切换搜索引擎的导航网页搜索框实例代码
2017/06/11 Javascript
写给小白看的JavaScript异步
2017/11/29 Javascript
vue配置请求本地json数据的方法
2018/04/11 Javascript
vue实现直播间点赞飘心效果的示例代码
2019/09/20 Javascript
使用webpack和rollup打包组件库的方法
2021/02/25 Javascript
python实现ping的方法
2015/07/06 Python
python编程实现随机生成多个椭圆实例代码
2018/01/03 Python
实例讲解python中的序列化知识点
2018/10/08 Python
python傅里叶变换FFT绘制频谱图
2019/07/19 Python
django框架基于queryset和双下划线的跨表查询操作详解
2019/12/11 Python
Python递归求出列表(包括列表中的子列表)的最大值实例
2020/02/27 Python
Python实现疫情通定时自动填写功能(附代码)
2020/05/27 Python
如何使用pycharm连接Databricks的步骤详解
2020/09/23 Python
应届毕业生个人求职信范文
2014/01/29 职场文书
学生宿舍管理制度
2014/01/30 职场文书
小学生考试获奖感言
2014/01/30 职场文书
艺人经纪人岗位职责
2014/04/15 职场文书
公司授权委托书范本
2014/09/18 职场文书
汽车转让协议书
2015/01/29 职场文书
摘录式读书笔记
2015/07/01 职场文书
2016应届毕业生实习心得体会
2015/10/09 职场文书
Django REST framework 限流功能的使用
2021/06/24 Python
vue3.0 数字翻牌组件的使用方法详解
2022/04/20 Vue.js