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计算文本文件行数的方法
Jul 06 Python
详解在Python的Django框架中创建模板库的方法
Jul 20 Python
Python实现周期性抓取网页内容的方法
Nov 04 Python
解决Python安装后pip不能用的问题
Jun 12 Python
Python将list中的string批量转化成int/float的方法
Jun 26 Python
Django发送邮件功能实例详解
Sep 02 Python
Python 求数组局部最大值的实例
Nov 26 Python
Windows上安装tensorflow  详细教程(图文详解)
Feb 04 Python
python 通过邮件控制实现远程控制电脑操作
Mar 16 Python
pip安装tensorflow的坑的解决
Apr 19 Python
Django静态资源部署404问题解决方案
May 11 Python
解决virtualenv -p python3 venv报错的问题
Feb 05 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/05/07 PHP
php中使用Ajax时出现Error(c00ce56e)的详细解决方案
2014/11/03 PHP
php调用mysql存储过程实例分析
2014/12/29 PHP
PHP实现会员账号单唯一登录的方法分析
2019/03/07 PHP
[原创]提供复制本站内容时出现,该文章转自脚本之家等字样的js代码
2007/03/27 Javascript
JQuery Ajax通过Handler访问外部XML数据的代码
2010/06/01 Javascript
用js控制组织结构图可以任意拖拽到指定位置
2014/01/17 Javascript
css与javascript跨浏览器兼容性总结
2014/09/15 Javascript
angularJS 中$attrs方法使用指南
2015/02/09 Javascript
AngularJS实现表单手动验证和表单自动验证
2015/12/09 Javascript
jQuery滚动新闻实现代码
2016/06/26 Javascript
JavaScript学习小结之被嫌弃的eval函数和with语句实例详解
2016/08/01 Javascript
javascript 删除数组元素和清空数组的简单方法
2017/02/24 Javascript
Angularjs单选框相关的示例代码
2017/08/17 Javascript
详解react阻止无效重渲染的多种方式
2018/12/11 Javascript
vue如何自动化打包测试环境和正式环境的dist/test文件
2019/06/06 Javascript
在Vue环境下利用worker运行interval计时器的步骤
2019/08/01 Javascript
使用vscode快速建立vue模板过程详解
2019/10/10 Javascript
javascript实现弹幕墙效果
2019/11/28 Javascript
ES6使用 Array.includes 处理多重条件用法实例分析
2020/03/02 Javascript
在Python中用split()方法分割字符串的使用介绍
2015/05/20 Python
SVM基本概念及Python实现代码
2017/12/27 Python
python 矩阵增加一行或一列的实例
2018/04/04 Python
对python 匹配字符串开头和结尾的方法详解
2018/10/27 Python
Python如何调用JS文件中的函数
2019/08/16 Python
IE支持HTML5的解决方法
2009/10/20 HTML / CSS
详解h5页面在不同ios设备上的问题总结
2019/03/01 HTML / CSS
Linux如何修改文件和文件夹的权限
2013/09/05 面试题
学生周末长期请假条
2014/02/15 职场文书
应届毕业生如何写求职信
2014/02/16 职场文书
士力架广告词
2014/03/20 职场文书
合同意向书范本
2014/07/30 职场文书
王兆力在市委党的群众路线教育实践活动总结大会上的讲话稿
2014/10/25 职场文书
2014年员工工作总结范文
2014/11/18 职场文书
婚内分居协议书范文
2014/11/26 职场文书
2016年党校科级干部培训班学习心得体会
2016/01/06 职场文书