基于鸢尾花数据集,采用KNN、SVM等多个方法对鸢尾花进行分类,通过对比准确率、精确率等指标,选取最佳算法,代码实现
时间: 2024-03-12 08:43:13 浏览: 109
好的,以下是基于Python语言,使用Scikit-learn库实现KNN和SVM算法对鸢尾花数据集进行分类的代码示例:
```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.metrics import accuracy_score, precision_score, recall_score, f1_score
iris = 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)
# 使用KNN算法进行分类,并计算评估指标
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
y_pred_knn = knn.predict(X_test)
acc_knn = accuracy_score(y_test, y_pred_knn)
pre_knn = precision_score(y_test, y_pred_knn, average='macro')
rec_knn = recall_score(y_test, y_pred_knn, average='macro')
f1_knn = f1_score(y_test, y_pred_knn, average='macro')
# 使用SVM算法进行分类,并计算评估指标
svm = SVC(kernel='linear')
svm.fit(X_train, y_train)
y_pred_svm = svm.predict(X_test)
acc_svm = accuracy_score(y_test, y_pred_svm)
pre_svm = precision_score(y_test, y_pred_svm, average='macro')
rec_svm = recall_score(y_test, y_pred_svm, average='macro')
f1_svm = f1_score(y_test, y_pred_svm, average='macro')
# 输出评估指标
print('KNN accuracy: {:.2f}'.format(acc_knn))
print('KNN precision: {:.2f}'.format(pre_knn))
print('KNN recall: {:.2f}'.format(rec_knn))
print('KNN F1 score: {:.2f}'.format(f1_knn))
print('SVM accuracy: {:.2f}'.format(acc_svm))
print('SVM precision: {:.2f}'.format(pre_svm))
print('SVM recall: {:.2f}'.format(rec_svm))
print('SVM F1 score: {:.2f}'.format(f1_svm))
```
运行以上代码,即可得到KNN和SVM算法在鸢尾花数据集上的准确率、精确率、召回率和F1值等评估指标,并根据结果选择最佳算法。
阅读全文