wine数据集SVM分类并可视化代码
时间: 2023-09-03 20:16:51 浏览: 398
以下是wine数据集的SVM分类并可视化代码,使用了Scikit-learn库和Matplotlib库:
```python
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
import matplotlib.pyplot as plt
import numpy as np
# 加载数据集
wine = load_wine()
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(wine.data[:, :2], wine.target, test_size=0.3, random_state=42)
# 训练SVM模型
svm = SVC(kernel='linear', C=1.0)
svm.fit(X_train, y_train)
# 可视化
plt.figure(figsize=(8, 6))
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap='viridis')
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# 生成网格点进行预测
xx = np.linspace(xlim[0], xlim[1], 30)
yy = np.linspace(ylim[0], ylim[1], 30)
YY, XX = np.meshgrid(yy, xx)
xy = np.vstack([XX.ravel(), YY.ravel()]).T
Z = svm.decision_function(xy).reshape(XX.shape)
# 绘制决策边界和支持向量
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])
ax.scatter(svm.support_vectors_[:, 0], svm.support_vectors_[:, 1], s=100, linewidth=1, facecolors='none', edgecolors='k')
plt.show()
```
运行后,会显示出wine数据集的散点图和SVM分类的决策边界和支持向量。
阅读全文