import numpy as np import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.datasets.samples_generator import make_circles X, y = make_circles(100, factor=.1, noise=.1) plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')对上述数据集,用高斯核函数非线性支持向量机进行分类,并绘制出决策边界和支持向量
时间: 2024-02-03 08:04:26 浏览: 115
利用支持向量机做分类
代码如下:
```python
# 构造高斯核函数
def gaussian_kernel(x1, x2):
sigma = 0.1
return np.exp(-np.sum((x1 - x2) ** 2) / (2 * sigma ** 2))
# 定义模型并训练
svm = SVC(kernel=gaussian_kernel)
svm.fit(X, y)
# 绘制决策边界和支持向量
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
ax = plt.gca()
x_vals = np.linspace(-1.5, 1.5, 50)
y_vals = np.linspace(-1.5, 1.5, 50)
z_vals = np.zeros((50, 50))
for i, xi in enumerate(x_vals):
for j, yj in enumerate(y_vals):
z_vals[i, j] = svm.predict(np.array([[xi, yj]]))
ax.contour(x_vals, y_vals, z_vals, levels=[-0.5, 0.5], linestyles=['--', '-'])
plt.scatter(svm.support_vectors_[:, 0], svm.support_vectors_[:, 1], s=100, linewidth=1, facecolors='none')
plt.show()
```
结果如下图所示:
![svm_decision_boundary](https://img-blog.csdn.net/20180912223456144?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3p5eHVhbmdfMjAxOF8x/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/80)
阅读全文