使用python对鸢尾花训练集采用支持向量机的方法实现散点图三划分
时间: 2024-10-14 13:10:44 浏览: 30
在Python中,使用Scikit-Learn库中的支持向量机(SVM)和matplotlib库来实现鸢尾花数据集的三维散点图三划分,可以按照以下步骤进行:
1. **导入所需库**:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.svm import SVC
from mpl_toolkits.mplot3d import Axes3D
```
2. **加载鸢尾花数据集**:
```python
iris = datasets.load_iris()
X = iris.data[:, :3] # 取前三个特征维度
y = iris.target
```
3. **选择和支持向量机模型**:
```python
model = SVC(kernel='linear') # 使用线性核函数,也可以尝试其他核函数如'rbf'
model.fit(X, y)
```
4. **绘制三维散点图**:
```python
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 颜色编码标签
cmap = plt.cm.get_cmap('viridis', 3)
colors = [cmap(i) for i in y]
# 绘制数据点
for l, c, m in zip(range(3), colors, 'rsbo'): # r, g, b, o代表各分类
ax.scatter(X[y == l, 0], X[y == l, 1], X[y == l, 2], c=c, marker=m)
# 添加超平面
xlim, ylim, zlim = ax.get_xlim(), ax.get_ylim(), ax.get_zlim()
xx, yy = np.meshgrid(np.linspace(xlim[0], xlim[1]), np.linspace(ylim[0], ylim[1]))
Z = model.predict(np.c_[xx.ravel(), yy.ravel(), np.zeros_like(xx)])
Z = Z.reshape(xx.shape)
ax.plot_surface(xx, yy, Z, alpha=0.5, color='k')
ax.set_xlabel('Feature 1')
ax.set_ylabel('Feature 2')
ax.set_zlabel('Feature 3')
plt.show()
```
阅读全文