采用KNN,SVM,决策树、集成学习方法实现中鸢尾花数据集分类请给出具体代码实现
时间: 2024-02-23 09:00:16 浏览: 81
KNN算法实现鸢尾花数据集分类 C语言实现.zip
好的,下面我将给出具体的代码实现。首先需要从sklearn库中导入所需的算法模型和数据集。
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import VotingClassifier
```
然后,加载中鸢尾花数据集,并将其分成训练集和测试集。
```python
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
```
接着,定义KNN算法模型,并对训练集进行训练。
```python
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
```
然后,定义SVM算法模型,并对训练集进行训练。
```python
svm = SVC(kernel='linear', C=1, random_state=42)
svm.fit(X_train, y_train)
```
接着,定义决策树算法模型,并对训练集进行训练。
```python
tree = DecisionTreeClassifier(max_depth=3, random_state=42)
tree.fit(X_train, y_train)
```
最后,定义集成学习算法模型,并对训练集进行训练。
```python
estimators = [('knn', knn), ('svm', svm), ('tree', tree)]
ensemble = VotingClassifier(estimators=estimators, voting='hard')
ensemble.fit(X_train, y_train)
```
完成算法模型的训练之后,接下来对测试集进行预测,并计算预测准确率。
```python
from sklearn.metrics import accuracy_score
knn_pred = knn.predict(X_test)
svm_pred = svm.predict(X_test)
tree_pred = tree.predict(X_test)
ensemble_pred = ensemble.predict(X_test)
print('KNN accuracy: {:.3f}'.format(accuracy_score(y_test, knn_pred)))
print('SVM accuracy: {:.3f}'.format(accuracy_score(y_test, svm_pred)))
print('Decision Tree accuracy: {:.3f}'.format(accuracy_score(y_test, tree_pred)))
print('Ensemble accuracy: {:.3f}'.format(accuracy_score(y_test, ensemble_pred)))
```
以上就是采用KNN,SVM,决策树、集成学习方法实现中鸢尾花数据集分类的具体代码实现。
阅读全文