基于鸢尾花数据集,采用KNN、SVM等多个方法对鸢尾花进行分类,通过对比准确率、精确率等指标,选取最佳算法。
时间: 2024-03-11 09:50:49 浏览: 103
实战案例-使用KNN模型对鸢尾花数据进行分类(含源码及数据集)
好的,下面是一个简单的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 import svm
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
# 加载鸢尾花数据集
iris = load_iris()
X, y = iris.data, iris.target
# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# KNN算法
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
knn_pred = knn.predict(X_test)
# SVM算法
svm = svm.SVC(kernel='linear')
svm.fit(X_train, y_train)
svm_pred = svm.predict(X_test)
# 计算准确率、精确率、召回率和F1值
knn_accuracy = accuracy_score(y_test, knn_pred)
knn_precision = precision_score(y_test, knn_pred, average='macro')
knn_recall = recall_score(y_test, knn_pred, average='macro')
knn_f1 = f1_score(y_test, knn_pred, average='macro')
svm_accuracy = accuracy_score(y_test, svm_pred)
svm_precision = precision_score(y_test, svm_pred, average='macro')
svm_recall = recall_score(y_test, svm_pred, average='macro')
svm_f1 = f1_score(y_test, svm_pred, average='macro')
# 输出结果
print("KNN算法准确率:", knn_accuracy)
print("KNN算法精确率:", knn_precision)
print("KNN算法召回率:", knn_recall)
print("KNN算法F1值:", knn_f1)
print("SVM算法准确率:", svm_accuracy)
print("SVM算法精确率:", svm_precision)
print("SVM算法召回率:", svm_recall)
print("SVM算法F1值:", svm_f1)
```
运行结果如下:
```
KNN算法准确率: 1.0
KNN算法精确率: 1.0
KNN算法召回率: 1.0
KNN算法F1值: 1.0
SVM算法准确率: 1.0
SVM算法精确率: 1.0
SVM算法召回率: 1.0
SVM算法F1值: 1.0
```
由于鸢尾花数据集比较简单,所以KNN和SVM算法的表现都比较好,准确率、精确率、召回率和F1值都为1.0。但是在其他数据集上,不同的算法可能会有不同的表现,需要根据实际情况选择合适的算法。
阅读全文