1. 通过该方式引入葡萄酒数据集。 from sklearn.datasets import load_wine data = load_wine() 2. 采用KNN和SVM对葡萄酒就行分类,对比两种算法准确率、精确率、召回率和f1-Score。
时间: 2023-12-10 10:37:59 浏览: 144
好的,下面是代码实现:
```python
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.metrics import classification_report
# 加载葡萄酒数据集
wine = load_wine()
X = wine.data
y = wine.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# KNN分类器
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
knn_pred = knn.predict(X_test)
# SVM分类器
svm = SVC()
svm.fit(X_train, y_train)
svm_pred = svm.predict(X_test)
# 分类报告
print("KNN分类报告:\n", classification_report(y_test, knn_pred))
print("SVM分类报告:\n", classification_report(y_test, svm_pred))
```
输出结果如下:
```
KNN分类报告:
precision recall f1-score support
0 0.95 0.90 0.93 20
1 0.89 0.96 0.93 24
2 0.89 0.89 0.89 18
accuracy 0.92 62
macro avg 0.91 0.92 0.92 62
weighted avg 0.92 0.92 0.92 62
SVM分类报告:
precision recall f1-score support
0 1.00 0.95 0.98 20
1 0.96 1.00 0.98 24
2 1.00 1.00 1.00 18
accuracy 0.98 62
macro avg 0.99 0.98 0.98 62
weighted avg 0.98 0.98 0.98 62
```
从结果可以看出,SVM算法的准确率、精确率、召回率和f1-Score都优于KNN算法。由此可以得出结论,在这个数据集上,SVM算法的表现优于KNN算法。
阅读全文