Python实现基于实现基于SVM的分类器的方法的分类器的方法
本文代码来之《数据分析与挖掘实战》,在此基础上补充完善了一下~
代码是基于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
评论0
最新资源