import numpy as np,matplotlib.pyplot as plt from sklearn.svm import SVC#(分类),SVR#(回归) import sklearn.datasets as dts from sklearn.metrics import confusion_matrix,classification_report # 3、加载乳腺癌数据集 data=dts.load_iris() x=data.data[:,:2] y=data.target print(y) # 5、对特征数据进行归一化缩放处理 x_mean=np.mean(x,axis=0) x_std=np.std(x,axis=0,ddof=1) x=(x-x_mean)/x_std # 6、洗牌,并按照8:2切分训练集与测试集 np.random.seed(5) m=len(x) order=np.random.permutation(m) x=x[order] y=y[order] num=int(m*0.8) train_x,test_x=np.split(x,[num]) train_y,test_y=np.split(y,[num]) # 1、创建支持向量机(SVM)分类模型 # 2、要求惩罚项系数为2.0,核函数为高斯核函数rbf, 线性核函数linear,多项式核函数poly,核函数sigmoid svm_model=SVC(C=2.0,kernel='linear') # 7、进行SVM模型训练和预测 svm_model.fit(train_x,train_y) test_h=svm_model.predict(test_x) # 8、输出训练集精度 print('训练集精度:',svm_model.score(train_x,train_y)) # 9、输出测试集分类报告,混淆矩阵h print('混淆矩阵:\n',confusion_matrix(test_y,test_h)) print('测试集分类报告:\n',classification_report(test_y,test_h)) # 10、绘图展示真实分类,用星型*标注预测分类情况 #画真实样本散点图 plt.scatter(test_x[:,0],test_x[:,1],c=test_y) plt.scatter(test_x[:,0],test_x[:,1],c=test_h,marker='*') plt.show() print('支持向量在样本中的索引:',svm_model.support_)#属性 print('所有支持向量的坐标:',svm_model.support_vectors_) print('每一类中支持向量的个数:',svm_model.n_support_)#0类44,1类43 print('权重:',svm_model.coef_)#除了theta0之外的其它特征,只有线性核函数linear有 print('超平面参数:',svm_model.intercept_)#theta0 #等高线图 #确定画布的大小 x1_min,x1_max=x[:,0].min(),x[:,0].max() x2_min,x2_max=x[:,1].min(),x[:,1].max() #切分网格 #横纵轴各切分200份 x1_lin=np.linspace(x1_min,x1_max,200) x2_lin=np.linspace(x2_min,x2_max,200) #网格化(轴上划分后进行一个延伸) x1_mat,x2_mat=np.meshgrid(x1_lin,x2_lin) #分别展开网格化横纵坐标并按列拼接 x1_x2=np.c_[x1_mat.ravel(),x2_mat.ravel()]#降为一维 #对40000个点坐标进行类别预测并重整成200*200的矩阵 h=svm_model.predict(x1_x2).reshape(200,200)#预测特征数必须和训练特证数一致 #画轮廓色 plt.contourf(x1_mat,x2_mat,h) #画轮廓线 plt.contour(x1_mat,x2_mat,h) #画样本点 plt.scatter(x[:,0],x[:,1],c=y.ravel(),edgecolors='k',s=20)#点描边,防止和背景色容为一体,s=20是为了控制点的大小 plt.show()
svm支持向量机调库代码
最新推荐文章于 2024-07-28 15:37:27 发布