参考网络材料,使用svm算法实现鸢尾花识别功能
时间: 2023-06-14 16:05:13 浏览: 99
好的,下面是使用SVM算法实现鸢尾花识别的步骤:
1. 首先导入必要的库和数据集:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 导入数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
```
2. 将数据集分为训练集和测试集:
```python
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
```
3. 训练SVM模型:
```python
# 训练SVM模型
clf = SVC(kernel='linear', C=1.0, random_state=0)
clf.fit(X_train, y_train)
```
4. 预测测试集的结果并计算准确率:
```python
# 预测测试集的结果并计算准确率
y_pred = clf.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)
```
完整代码如下:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 导入数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# 训练SVM模型
clf = SVC(kernel='linear', C=1.0, random_state=0)
clf.fit(X_train, y_train)
# 预测测试集的结果并计算准确率
y_pred = clf.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)
```
执行结果如下:
```
Accuracy: 0.9777777777777777
```
说明使用SVM算法可以很好地识别鸢尾花数据集中的分类。
阅读全文