热门标签 | HotTags
当前位置:  开发笔记 > 开发工具 > 正文

pythonSVM线性分类模型的实现

这篇文章主要介绍了pythonSVM线性分类模型的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

运行环境: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)

#非线性分类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)

#考察高斯核
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)

#考察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入门:第一天准备与安装
    本文详细介绍了Python编程语言的基础知识和安装步骤,帮助初学者快速上手。涵盖Python的特点、应用场景以及Windows环境下Python和PyCharm的安装方法。 ... [详细]
  • 如何使用PyCharm及常用配置详解
    对于一枚pycharm工具的使用新手,正确了解这门工具的配置及其使用,在使用过程中遇到的很多问题也可以迎刃而解,文中有非常详细的介绍, ... [详细]
  • 解决PyCharm中安装PyTorch深度学习d2l包的问题
    本文详细介绍了如何在PyCharm中成功安装用于PyTorch深度学习的d2l包,包括环境配置、安装步骤及常见问题的解决方案。 ... [详细]
  • 新手指南:在Windows 10上搭建深度学习与PyTorch开发环境
    本文详细记录了一名新手在Windows 10操作系统上搭建深度学习环境的过程,包括安装必要的软件和配置环境变量等步骤,旨在帮助同样初入该领域的读者避免常见的错误。 ... [详细]
  • 解决PyCharm安装第三方库失败问题
    本文详细探讨了在使用Python 3.9.7和pip 22.3.1时,通过PyCharm安装第三方库遇到的问题及解决方法。即使更换了国内镜像源也未能解决问题,文章将介绍具体原因及有效解决方案。 ... [详细]
  • Python3 第一周学习总结
    本文总结了Python3第一周的学习内容,包括Python的主要特性、版本选择建议、开发环境配置技巧以及一些有趣的语言特性。 ... [详细]
  • 解决PyCharm中‘未解析的引用’问题的方法
    本文介绍了如何通过调整PyCharm中的项目结构设置,将指定的文件夹标记为源代码文件夹,从而有效解决‘未解析的引用’错误提示。 ... [详细]
  • Python基础入门:理解字符集与编码
    本文首先探讨了计算机的基本工作原理——二进制系统,进而深入介绍了字符集的概念及其在不同编码标准(如ASCII、GB2312、GBK、Unicode及UTF-8)中的应用。此外,文章还简要介绍了Python的安装、基本运行环境配置、变量定义、字符串处理、用户输入输出、条件判断及循环控制结构。 ... [详细]
  • 本文详细介绍了在Windows系统中安装PyCharm集成开发环境以及MySQL数据库的具体步骤,包括必要的环境配置和常见问题的解决方法。 ... [详细]
  • Python 第三天学习笔记
    本文详细介绍了 Python 编程的第三天学习内容,包括字符编码、文件处理以及函数的基本概念和使用方法。 ... [详细]
  • 本文介绍了如何在配置了virtualenv和virtualenvwrapper环境后,利用PyCharm创建新的Django项目,并将开发数据库从SQLite切换至更适用于生产环境的MySQL数据库。文章详细记录了尝试使用MySQLdb、MySQL自带Connector及pymysql等不同数据库连接库时遇到的问题及解决办法。 ... [详细]
  • Python for 循环详解及应用
    在上一篇文章中,我们探讨了 while 循环和 if 判断的使用方法。本次我们将深入讲解 for 循环,并推荐一款强大的 Python 开发工具 PyCharm,帮助你更高效地编写代码。 ... [详细]
  • 处理Pandas读取Excel文件时遇到的 'xlsx' 格式不支持错误
    本文探讨了在使用Pandas库读取Excel文件时,在PyCharm中遇到的'xlsx'文件格式不支持的问题,并提供了解决方案。 ... [详细]
  • Python3兼容性提升:Robot Framework与RIDE的最新进展
    本文介绍了Robot Framework,一个基于Python的自动化测试框架,以及其配套IDE RIDE的最新更新。随着Python3的广泛采用,RIDE终于实现了对Python3的支持,这为Robot Framework的用户带来了福音。 ... [详细]
  • 本文档详细介绍了Robot Framework的基础知识、安装配置方法及其实用技巧。从环境搭建到编写第一个测试用例,涵盖了一系列实用的操作指南和最佳实践。 ... [详细]
author-avatar
的发个地方
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有