您好,登錄后才能下訂單哦!
本文代碼來之《數據分析與挖掘實戰》,在此基礎上補充完善了一下~
代碼是基于SVM的分類器Python實現,原文章節題目和code關系不大,或者說給出已處理好數據的方法缺失、源是圖像數據更是不見蹤影,一句話就是練習分類器(▼㉨▼メ)
源代碼直接給好了K=30,就試了試怎么選的,挑選規則設定比較單一,有好主意請不吝賜教喲
# -*- coding: utf-8 -*- """ Created on Sun Aug 12 12:19:34 2018 @author: Luove """ from sklearn import svm from sklearn import metrics import pandas as pd import numpy as np from numpy.random import shuffle #from random import seed #import pickle #保存模型和加載模型 import os os.getcwd() os.chdir('D:/Analyze/Python Matlab/Python/BookCodes/Python數據分析與挖掘實戰/圖書配套數據、代碼/chapter9/demo/code') inputfile = '../data/moment.csv' data=pd.read_csv(inputfile) data.head() data=data.as_matrix() #seed(10) shuffle(data) #隨機重排,按列,同列重排,因是隨機的每次運算會導致結果有差異,可在之前設置seed n=0.8 train=data[:int(n*len(data)),:] test=data[int(n*len(data)):,:] #建模數據 整理 #k=30 m=100 record=pd.DataFrame(columns=['acurrary_train','acurrary_test']) for k in range(1,m+1): # k特征擴大倍數,特征值在0-1之間,彼此區分度太小,擴大以提高區分度和準確率 x_train=train[:,2:]*k y_train=train[:,0].astype(int) x_test=test[:,2:]*k y_test=test[:,0].astype(int) model=svm.SVC() model.fit(x_train,y_train) #pickle.dump(model,open('../tmp/svm1.model','wb'))#保存模型 #model=pickle.load(open('../tmp/svm1.model','rb'))#加載模型 #模型評價 混淆矩陣 cm_train=metrics.confusion_matrix(y_train,model.predict(x_train)) cm_test=metrics.confusion_matrix(y_test,model.predict(x_test)) pd.DataFrame(cm_train,index=range(1,6),columns=range(1,6)) accurary_train=np.trace(cm_train)/cm_train.sum() #準確率計算 # accurary_train=model.score(x_train,y_train) #使用model自帶的方法求準確率 pd.DataFrame(cm_test,index=range(1,6),columns=range(1,6)) accurary_test=np.trace(cm_test)/cm_test.sum() record=record.append(pd.DataFrame([accurary_train,accurary_test],index=['accurary_train','accurary_test']).T) record.index=range(1,m+1) find_k=record.sort_values(by=['accurary_train','accurary_test'],ascending=False) # 生成一個copy 不改變原變量 find_k[(find_k['accurary_train']>0.95) & (find_k['accurary_test']>0.95) & (find_k['accurary_test']>=find_k['accurary_train'])] #len(find_k[(find_k['accurary_train']>0.95) & (find_k['accurary_test']>0.95)]) ''' k=33 accurary_train accurary_test 33 0.950617 0.95122 ''' ''' 計算一下整體 accurary_data 0.95073891625615758 ''' k=33 x_train=train[:,2:]*k y_train=train[:,0].astype(int) model=svm.SVC() model.fit(x_train,y_train) model.score(x_train,y_train) model.score(datax_train,datay_train) datax_train=data[:,2:]*k datay_train=data[:,0].astype(int) cm_data=metrics.confusion_matrix(datay_train,model.predict(datax_train)) pd.DataFrame(cm_data,index=range(1,6),columns=range(1,6)) accurary_data=np.trace(cm_data)/cm_data.sum() accurary_data
REF:
《數據分析與挖掘實戰》
源代碼及數據需要可自取:https://github.com/Luove/Data
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。