Python实现基于SVM的分类器的方法-创新互联
本文代码来之《数据分析与挖掘实战》,在此基础上补充完善了一下~
创新互联长期为数千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为辽阳企业提供专业的成都网站设计、成都做网站,辽阳网站改版等技术服务。拥有十多年丰富建站经验和众多成功案例,为您定制开发。代码是基于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
新闻标题:Python实现基于SVM的分类器的方法-创新互联
网页URL:http://lswzjz.com/article/cechci.html