









PR4SVM.py
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
def main(n):
# 导入数据集
iris = datasets.load_iris()
X = iris.data[:,n*2:n*2+2] # 只取前两维特征
y = iris.target
h = .02 # 网格中的步长
# 创建支持向量机实例,并拟合出数据
C = 1.0 # SVM正则化参数
svc = svm.SVC(kernel='linear', C=C).fit(X, y) # 线性核
rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, y) # 径向基核
poly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, y) # 多项式核
# lin_svc = svm.LinearSVC(C=C).fit(X, y) #线性核
# SVC : 1/2||w||^2 + C SUM xi_i 均方误差
# LinearSVC: 1/2||[w b]||^2 + C SUM xi_i normal hinge
# 创建网格,以绘制图像
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
# 图的标题
titles = ['SVC with linear kernel',
# 'LinearSVC (linear kernel)',
'SVC with RBF kernel',
'SVC with polynomial (degree 3) kernel']
for i, clf in enumerate((svc, rbf_svc, poly_svc)):
# 绘出决策边界,不同的区域分配不同的颜色
# plt.subplot(3, 1, i + 1) # 创建一个2行2列的图,并以第i个图为当前图
# plt.subplots_adjust(wspace=0.4, hspace=0.4) # 设置子图间隔
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# 把分类结果绘制出来
Z = Z.reshape(xx.shape) #(220, 280)
plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) #使用等高线的函数将不同的区域绘制出来
# 将训练数据以离散点的形式绘制出来
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xticks(())
plt.yticks(())
plt.title(titles[i])
plt.savefig('%d%d'%(n,i))
plt.show()
plt.cla()
if __name__ == '__main__':
main(0)
main(1)
process_data.py
import numpy as np
import csv
#%%
# To->process_data
#---usps
def get_data():
with open('usps_all.csv','r') as f:
reader=csv.reader(f)
# for line in reader:
file=np.array(list(map(np.array,reader)))
N=len(file)
t_N=int(0.9*N)
data={'train':{'x':0,'y':0},'val':{'x':0,'y':0}}
data['train']['x']=file[:t_N,:-1]
data['train']['y']=file[:t_N,-1:]
data['val']['x']=file[t_N:,:-1]
data['val']['y']=file[t_N:,-1:]
print('hello')
return data
SVM_usps.py
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
import process_data as pd
from sklearn.externals import joblib #jbolib模块
from os import listdir
import os
from copy import deepcopy
#读取Model
model_dir='save/'
titles = ['SVC with linear kernel',
'SVC with RBF kernel',
'SVC with polynomial (degree 3) kernel']
def main():
# 读取数据
data=pd.get_data()
## 验证集
x,y=data['val']['x'],data['val']['y'].ravel()
y_num=len(y)
model_list=listdir(model_dir)
if(model_list==[]):
## 训练集
X = data['train']['x']
Y = data['train']['y'].ravel()
# 创建支持向量机实例,并拟合出数据
C = 1.0 # SVM正则化参数
print('trianing:', titles[0])
svc = svm.SVC(kernel='linear', C=C).fit(X, Y) # 线性核
joblib.dump(svc, 'save/0.pkl',compress=1)
print('trianing:', titles[1])
rbf_svc = svm.SVC(kernel='rbf').fit(X, Y) # 径向基核
joblib.dump(rbf_svc, 'save/1.pkl',compress=1)
print('trianing:', titles[2])
poly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, Y) # 多项式核
joblib.dump(poly_svc, 'save/2.pkl',compress=1)
exit(0)
else:
os.chdir(model_dir)
svc,rbf_svc,poly_svc=list(map(joblib.load,model_list))
# 预测
for i, clf in enumerate((svc, rbf_svc, poly_svc)):
y_=clf.predict(x)
acc=sum(y_==y)/y_num
print(titles[i]+' accuracy: ',acc)
if __name__ == '__main__':
main()
网友评论