python SVM 线性分类模型的实现

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • python实现感知机线性分类模型示例代码

    前言 感知器是分类的线性分类模型,其中输入为实例的特征向量,输出为实例的类别,取+1或-1的值作为正类或负类.感知器对应于输入空间中对输入特征进行分类的超平面,属于判别模型. 通过梯度下降使误分类的损失函数最小化,得到了感知器模型. 本节为大家介绍实现感知机实现的具体原理代码: 运 行结果如图所示: 总结 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持.

  • python实现最小二乘法线性拟合

    本文python代码实现的是最小二乘法线性拟合,并且包含自己造的轮子与别人造的轮子的结果比较. 问题:对直线附近的带有噪声的数据进行线性拟合,最终求出w,b的估计值. 最小二乘法基本思想是使得样本方差最小. 代码中self_func()函数为自定义拟合函数,skl_func()为调用scikit-learn中线性模块的函数. import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Li

  • python如何实现数据的线性拟合

    实验室老师让给数据画一张线性拟合图.不会matlab,就琢磨着用python.参照了网上的一些文章,查看了帮助文档,成功的写了出来 这里用到了三个库 import numpy as np import matplotlib.pyplot as plt from scipy import optimize def f_1(x, A, B): return A * x + B plt.figure() # 拟合点 x0 = [75, 70, 65, 60, 55,50,45,40,35,30] y0

  • python数据结构学习之实现线性表的顺序

    本文实例为大家分享了python实现线性表顺序的具体代码,供大家参考,具体内容如下 线性表 1.抽象数据类型表示(ADT) 类型名称:线性表 数据对象集:线性表是n(>=0)个元素构成的有序序列(a1,a2,-.,an) 操作集: 2.线性表的顺序实现 1.表示方法: 其中100可以自己规定,last代表线性表的长度 # 线性表定义 class Lnode(object): def __init__(self,last): self.data = [None for i in range(100

  • python3 线性回归验证方法

    如下所示: #-*- coding: utf-8 -*- import pandas as pd import numpy as np from patsy.highlevel import dmatrices #2.7里面是from patsy import dmatrices from statsmodels.stats.outliers_influence import variance_inflation_factor import statsmodels.api as sm impor

  • Python实现的简单线性回归算法实例分析

    本文实例讲述了Python实现的简单线性回归算法.分享给大家供大家参考,具体如下: 用python实现R的线性模型(lm)中一元线性回归的简单方法,使用R的women示例数据,R的运行结果: > summary(fit) Call: lm(formula = weight ~ height, data = women) Residuals:     Min      1Q  Median      3Q     Max -1.7333 -1.1333 -0.3833  0.7417  3.116

  • Python实现分段线性插值

    本文实例为大家分享了Python实现分段线性插值的具体代码,供大家参考,具体内容如下 函数: 算法 这个算法不算难.甚至可以说是非常简陋.但是在代码实现上却比之前的稍微麻烦点.主要体现在分段上. 图像效果 代码 import numpy as np from sympy import * import matplotlib.pyplot as plt def f(x): return 1 / (1 + x ** 2) def cal(begin, end): by = f(begin) ey =

  • Python实现基于SVM的分类器的方法

    本文代码来之<数据分析与挖掘实战>,在此基础上补充完善了一下~ 代码是基于SVM的分类器Python实现,原文章节题目和code关系不大,或者说给出已处理好数据的方法缺失.源是图像数据更是不见踪影,一句话就是练习分类器(▼㉨▼メ) 源代码直接给好了K=30,就试了试怎么选的,挑选规则设定比较单一,有好主意请不吝赐教哟 # -*- coding: utf-8 -*- """ Created on Sun Aug 12 12:19:34 2018 @author: L

  • 8种用Python实现线性回归的方法对比详解

    前言 说到如何用Python执行线性回归,大部分人会立刻想到用sklearn的linear_model,但事实是,Python至少有8种执行线性回归的方法,sklearn并不是最高效的. 今天,让我们来谈谈线性回归.没错,作为数据科学界元老级的模型,线性回归几乎是所有数据科学家的入门必修课.抛开涉及大量数统的模型分析和检验不说,你真的就能熟练应用线性回归了么?未必! 在这篇文章中,文摘菌将介绍8种用Python实现线性回归的方法.了解了这8种方法,就能够根据不同需求,灵活选取最为高效的方法实现线

  • Python实现的线性回归算法示例【附csv文件下载】

    本文实例讲述了Python实现的线性回归算法.分享给大家供大家参考,具体如下: 用python实现线性回归 Using Python to Implement Line Regression Algorithm 小菜鸟记录学习过程 代码: #encoding:utf-8 """ Author: njulpy Version: 1.0 Data: 2018/04/09 Project: Using Python to Implement LineRegression Algor

随机推荐