用svm算法对鸢尾花分类代码python
时间: 2024-09-20 14:14:21 浏览: 45
当然,我们可以使用Python的Scikit-Learn库来实现支持向量机(SVM)对鸢尾花数据集的分类。首先,你需要安装必要的库,例如`scikit-learn`。以下是使用SVM对鸢尾花数据集做分类的一个简单示例:
```python
# 导入所需的库
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 加载鸢尾花数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 数据预处理:标准化特征
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# 使用线性核SVM
svm_model = SVC(kernel='linear') # 如果你想用非线性的核,可以改为'sigmoid' 或 'rbf'
svm_model.fit(X_train, y_train)
# 预测并评估模型性能
y_pred = svm_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
# 查看决策边界(仅适用于简单的线性SVM)
if svm_model.kernel == 'linear':
from matplotlib import pyplot as plt
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=plt.cmviridis)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.plot(svm_model.support_vectors_[:, 0], svm_model.support_vectors_[:, 1], 'o', fillstyle='none',
color='k', markersize=10)
plt.show()
```
阅读全文