https://blog.csdn.net/OliverkingLi/article/details/80660830
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.preprocessing import StandardScaler
from matplotlib.colors import ListedColormap
# 导入数据集
iris = datasets.load_iris()
X = iris.data[:, :2] # 只取前两维特征
y = iris.target
stdScaler = StandardScaler()
stdScaler.fit(X)
X = stdScaler.transform(X)
# 创建支持向量机实例,并拟合出数据
C = 0.01 # 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) #线性核
# 创建网格,以绘制图像
# 图的标题
titles = ['SVC with linear kernel',
'LinearSVC (linear kernel)',
'SVC with RBF kernel',
'SVC with polynomial (degree 3) kernel']
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
axis=[x_min,x_max,y_min,y_max]
xx, yy = np.meshgrid(np.linspace(axis[0],axis[1],int((axis[1]-axis[0])*100)).reshape(1,-1),
np.linspace(axis[2],axis[3],int((axis[3]-axis[2])*100)).reshape(1,-1))
for i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)):
# 绘出决策边界,不同的区域分配不同的颜色
plt.subplot(2, 2, i + 1) # 创建一个2行2列的图,并以第i个图为当前图
plt.subplots_adjust(wspace=0.4, hspace=0.4) # 设置子图间隔
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) #将xx和yy中的元素组成一对对坐标,作为支持向量机的输入,返回一个array
custom_cmap = ListedColormap(["#EF9A9A", "#FFF59D", "#90CAF9"])
# plt.contourf(x0, x1, zz, linewidth=5, cmap=custom_cmap)
# 把分类结果绘制出来
Z = Z.reshape(xx.shape) #(220, 280)
plt.contourf(xx, yy, Z, cmap=custom_cmap, alpha=0.8) #使用等高线的函数将不同的区域绘制出来
# 将训练数据以离散点的形式绘制出来
plt.scatter(X[y==0,0],X[y==0,1],color='red')
plt.scatter(X[y==1,0],X[y==1,1],color="blue")
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.show()
SVM_01
猜你喜欢
转载自blog.csdn.net/qq_38662930/article/details/83626603
今日推荐
周排行