基于SVM和决策树的花卉识别代码
时间: 2023-12-30 15:03:45 浏览: 114
以下是基于SVM和决策树的花卉识别代码示例:
1. SVM代码示例:
```python
# 导入必要的库
from sklearn import datasets
from sklearn import svm
from sklearn.model_selection import train_test_split
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=42)
# 创建SVM分类器
clf = svm.SVC(kernel='linear')
# 训练SVM分类器
clf.fit(X_train, y_train)
# 预测测试集的标签
y_pred = clf.predict(X_test)
# 计算分类器的准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
2. 决策树代码示例:
```python
# 导入必要的库
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
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=42)
# 创建决策树分类器
clf = DecisionTreeClassifier()
# 训练决策树分类器
clf.fit(X_train, y_train)
# 预测测试集的标签
y_pred = clf.predict(X_test)
# 计算分类器的准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
这些示例代码可以帮助您了解基于SVM和决策树的花卉识别是如何实现的。不过,请注意,这只是示例代码,具体的实现可能会根据不同的数据集和任务有所不同。
阅读全文