def svmModel(x_train,x_test,y_train,y_test,type): if type=='rbf': svmmodel=svm.SVC(C=15,kernel='rbf',gamma=10,decision_function_shape='ovr') else: svmmodel=svm.SVC(C=0.1,kernel='linear',decision_function_shape='ovr') svmmodel.fit(x_train,y_train.ravel()) print('SVM模型:',svmmodel) train_accscore=svmmodel.score(x_train,y_train) test_accscore=svmmodel.score(x_test,y_test) n_support_numbers=svmmodel.n_support_ return svmmodel,train_accscore,test_accscore,n_support_numbers if __name__=='__main__': iris_feature='花萼长度','花萼宽度','花瓣长度','花瓣宽度' path="D:\data\iris(1).data" data=pd.read_csv(path,header=None) x,y=data[[0,1]],pd.Categorical(data[4]).codes x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=3,train_size=0.6) type='linear' svmmodel,train_accscore,test_accscore,n_support_numbers=svmModel(x_train,x_test,y_train,y_test,type) print('训练集准确率:',train_accscore) print('测试机准确率:',test_accscore) print('支持向量的数目:',n_support_numbers) print('-' * 50) if __name__=='__main__': path='D:/data/iris1-100.data' data=pd.read_csv(path,header=None) x=data[list(range(2,4))] y=data[4].replace(['Iris-versicolor','Iris-virginica'],[0,1]) svmmodel_param=(('linear',0.1),('rbf',1,0.1),('rbf',5,5),('rbf',10,10)) for i, param in enumerate(svmmodel_param): svmmodel,title,accuracyscore=svmModel(x,y,param[0]) y_predict=svmmodel.predict(x) print(title) print('准确率:',accuracyscore) print('支持向量的数目:',svmmodel.n_support_) plt.scatter(x[2],x[3],c=y,edgecolors='k',s=40,cmap=cm_dark) plt.scatter(x.loc[svmmodel.support_,2],x.loc[svmmodel.support_,3],degecolor='k',facecolors='none',s=100,marker='o') z=svmmodel.decision_function(grid_test) z=z.reshape(x1.shape) plt.contour(x1,x2,z,colors=list('kbrbk'),linestyles=['--','--','-','--','--'],linewidths=[1,0.5,11.5,0.5,1],levels=[-1,-0.5,0,0.5,1])检查错误
时间: 2024-01-29 14:03:49 浏览: 136
SVM.zip_Poly RBF_SVM poly_SVM_RBF_linear svm_svm rbf
这段代码有两个主要问题:
1. 在调用 svmModel 函数时,传入的参数与函数定义的参数不一致。函数定义的参数为 (x_train, x_test, y_train, y_test, type),但在调用时只传入了前四个参数,没有传入 type 参数。
2. 在画图时,使用了未定义的变量 grid_test,应该先定义这个变量。
阅读全文