• 基于SVM的分类器Python实现


    本文代码来之《数据分析与挖掘实战》,在此基础上补充完善了一下~

    代码是基于SVM的分类器Python实现,原文章节题目和code关系不大,或者说给出已处理好数据的方法缺失、源是图像数据更是不见踪影,一句话就是练习分类器(▼㉨▼メ)

    源代码直接给好了K=30,就试了试怎么选的,挑选规则设定比较单一,有好主意请不吝赐教哟

     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Sun Aug 12 12:19:34 2018
     4 
     5 @author: Luove
     6 """
     7 from sklearn import svm
     8 from sklearn import metrics
     9 import pandas as pd 
    10 import numpy as np
    11 from numpy.random import shuffle
    12 #from random import seed
    13 #import pickle #保存模型和加载模型
    14 import os
    15 
    16 
    17 os.getcwd()
    18 os.chdir('D:/Analyze/Python Matlab/Python/BookCodes/Python数据分析与挖掘实战/图书配套数据、代码/chapter9/demo/code')
    19 inputfile = '../data/moment.csv'
    20 data=pd.read_csv(inputfile)
    21 
    22 data.head()
    23 data=data.as_matrix()
    24 #seed(10)
    25 shuffle(data) #随机重排,按列,同列重排,因是随机的每次运算会导致结果有差异,可在之前设置seed
    26 n=0.8
    27 train=data[:int(n*len(data)),:]
    28 test=data[int(n*len(data)):,:]
    29 
    30 #建模数据 整理
    31 #k=30 
    32 m=100
    33 record=pd.DataFrame(columns=['acurrary_train','acurrary_test']) 
    34 for k in range(1,m+1):
    35     # k特征扩大倍数,特征值在0-1之间,彼此区分度太小,扩大以提高区分度和准确率
    36     x_train=train[:,2:]*k
    37     y_train=train[:,0].astype(int)
    38     x_test=test[:,2:]*k
    39     y_test=test[:,0].astype(int)
    40     
    41     model=svm.SVC()
    42     model.fit(x_train,y_train)
    43     #pickle.dump(model,open('../tmp/svm1.model','wb'))#保存模型
    44     #model=pickle.load(open('../tmp/svm1.model','rb'))#加载模型
    45     #模型评价 混淆矩阵
    46     cm_train=metrics.confusion_matrix(y_train,model.predict(x_train))
    47     cm_test=metrics.confusion_matrix(y_test,model.predict(x_test))
    48     
    49     pd.DataFrame(cm_train,index=range(1,6),columns=range(1,6))
    50     accurary_train=np.trace(cm_train)/cm_train.sum()      #准确率计算
    51 #    accurary_train=model.score(x_train,y_train)                          #使用model自带的方法求准确率
    52     pd.DataFrame(cm_test,index=range(1,6),columns=range(1,6))
    53     accurary_test=np.trace(cm_test)/cm_test.sum()
    54     record=record.append(pd.DataFrame([accurary_train,accurary_test],index=['accurary_train','accurary_test']).T)
    55 
    56 record.index=range(1,m+1)
    57 find_k=record.sort_values(by=['accurary_train','accurary_test'],ascending=False) # 生成一个copy 不改变原变量
    58 find_k[(find_k['accurary_train']>0.95) & (find_k['accurary_test']>0.95) & (find_k['accurary_test']>=find_k['accurary_train'])]
    59 #len(find_k[(find_k['accurary_train']>0.95) & (find_k['accurary_test']>0.95)])
    60 ''' k=33
    61     accurary_train  accurary_test
    62 33        0.950617        0.95122
    63 '''
    64 ''' 计算一下整体 
    65  accurary_data
    66  0.95073891625615758
    67 '''
    68 k=33
    69 x_train=train[:,2:]*k
    70 y_train=train[:,0].astype(int)
    71 model=svm.SVC()
    72 model.fit(x_train,y_train)
    73 model.score(x_train,y_train)
    74 model.score(datax_train,datay_train)
    75 datax_train=data[:,2:]*k
    76 datay_train=data[:,0].astype(int)
    77 cm_data=metrics.confusion_matrix(datay_train,model.predict(datax_train))
    78 pd.DataFrame(cm_data,index=range(1,6),columns=range(1,6))
    79 accurary_data=np.trace(cm_data)/cm_data.sum()
    80 accurary_data

    REF:

    《数据分析与挖掘实战》

    源代码及数据需要可自取:https://github.com/Luove/Data

  • 相关阅读:
    JSON.parse()与JSON.stringify()的区别
    响应式布局
    document.selection
    jQuery $.proxy() 方法
    <转> 键值表
    jquery-jqzoom 插件 用例
    jquery 笔记
    前端表单验证常用的15个JS正则表达式<转>
    css 问题解决
    <转>break与continue
  • 原文地址:https://www.cnblogs.com/amoor/p/9463139.html
Copyright © 2020-2023  润新知