用支持向量机进行鸢尾花分类
时间: 2023-11-20 20:02:08 浏览: 101
鸢尾花分类是一个经典的机器学习问题,支持向量机(Support Vector Machine,SVM)是其中一种有效的分类算法。下面是一个使用Python的Scikit-learn库进行鸢尾花分类的例子:
首先,导入所需的库和数据集:
```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, y = iris.data, iris.target
```
接着,将数据集分为训练集和测试集:
```python
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
然后,使用SVM进行训练和预测:
```python
# 创建SVM分类器
clf = SVC(kernel='linear', C=1)
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
```
最后,计算模型的准确率:
```python
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
完整的代码如下:
```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, y = iris.data, iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建SVM分类器
clf = SVC(kernel='linear', C=1)
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文