1. 程式人生 > >SVM分類加混淆矩陣輸出

SVM分類加混淆矩陣輸出

這篇文章主要講解了如何利用SVM分類。並用在輸出分類精度的同時輸出混淆矩陣。
注意x_train,y_train,x_test,y_test,資料集需要用自己的資料,其中x為多維矩陣,y為類別列表

# coding=utf-8

import numpy as np
from PIL import Image
from sklearn import svm
# 使用交叉驗證的方法,把資料集分為訓練集合測試集
from sklearn.cross_validation import train_test_split

from merge import x_train,y_train,x_test,y_test,X_test

def
test_LinearSVC(train,label,testdata):
# 選擇模型 cls = svm.LinearSVC() # 把資料交給模型訓練 cls.fit(train,label.astype('int')) # 預測資料 #print(cls.predict(testdata)) results=cls.predict(testdata) return results #輸出混淆矩陣 from sklearn.metrics import confusion_matrix def my_confusion_matrix
(y_true, y_pred):
labels = list(set(y_true)) conf_mat = confusion_matrix(list(y_true), list(y_pred), labels = labels) print ("confusion_matrix(left labels: y_true, up labels: y_pred):") print ("labels"," ",end='') for i in range(len(labels)): print (labels[i]," ",end='') print('\n'
) for i in range(len(conf_mat)): print (i," ",end='') for j in range(len(conf_mat[i])): print (conf_mat[i][j]," ",end='') print('\n') print if __name__=="__main__": #測試集分類結果---列表 y_pred = test_LinearSVC(x_train,y_train,x_test) label_list = [int(i) for i in y_test] #測試集合的精度 kk = 0 for i in range(len(y_test)): if (y_pred[i] == y_test[i]): kk = kk + 1 print('acc rate is %f' % float(kk / len(y_test))) a = list(y_test[:40]) b = list(y_pred[:40]) my_confusion_matrix(y_test, y_pred) # 輸出混淆矩陣