写一个用支持向量机分类以为数据的代码
时间: 2024-03-11 12:47:57 浏览: 23
好的,以下是一个用支持向量机分类二维数据的 Python 代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
# 生成数据
np.random.seed(0)
X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]]
Y = [0] * 20 + [1] * 20
# 拟合 SVM 模型
clf = svm.SVC(kernel='linear')
clf.fit(X, Y)
# 画出决策边界和支持向量
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
plt.axis('tight')
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, 0.02), np.arange(y_min, y_max, 0.02))
Z = clf.predict(np.c_[XX.ravel(), YY.ravel()])
Z = Z.reshape(XX.shape)
plt.contourf(XX, YY, Z, cmap=plt.cm.Paired, alpha=0.5)
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors='none')
plt.show()
```
上面的代码中,我们首先生成了一些二维数据,其中包含两个类别,每个类别包含20个样本。然后,我们使用 `svm.SVC` 类来拟合一个线性 SVM 模型,并用 `fit` 方法拟合数据。最后,我们使用 `plt.scatter` 函数画出数据点,使用 `plt.contourf` 函数画出决策边界和支持向量。