基於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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM