1. 通过该方式引入葡萄酒数据集。 from sklearn.datasets import load_wine data = load_wine() 2. 采用KNN和SVM对葡萄酒就行分类,对比两种算法准确率、精确率、召回率和f1-Score。
时间: 2023-12-10 15:38:28 浏览: 137
好的,我们先来看一下代码实现。
```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 accuracy_score, precision_score, recall_score, f1_score
# 加载葡萄酒数据集
wine = load_wine()
# 将数据集分为训练集和测试集,测试集占比为30%
x_train, x_test, y_train, y_test = train_test_split(wine.data, wine.target, test_size=0.3, random_state=42)
# 初始化KNN分类器,并进行训练和预测
knn = KNeighborsClassifier()
knn.fit(x_train, y_train)
knn_y_pred = knn.predict(x_test)
# 初始化SVM分类器,并进行训练和预测
svm = SVC()
svm.fit(x_train, y_train)
svm_y_pred = svm.predict(x_test)
# 计算KNN分类器的准确率、精确率、召回率和f1-Score
print("KNN分类器的准确率为:", accuracy_score(y_test, knn_y_pred))
print("KNN分类器的精确率为:", precision_score(y_test, knn_y_pred, average='weighted'))
print("KNN分类器的召回率为:", recall_score(y_test, knn_y_pred, average='weighted'))
print("KNN分类器的f1-Score为:", f1_score(y_test, knn_y_pred, average='weighted'))
# 计算SVM分类器的准确率、精确率、召回率和f1-Score
print("SVM分类器的准确率为:", accuracy_score(y_test, svm_y_pred))
print("SVM分类器的精确率为:", precision_score(y_test, svm_y_pred, average='weighted'))
print("SVM分类器的召回率为:", recall_score(y_test, svm_y_pred, average='weighted'))
print("SVM分类器的f1-Score为:", f1_score(y_test, svm_y_pred, average='weighted'))
```
上述代码中,我们首先加载了葡萄酒数据集,并将其分为训练集和测试集,其中测试集占比为30%。然后,分别初始化了KNN和SVM分类器,并进行训练和预测。最后,使用`accuracy_score`、`precision_score`、`recall_score`和`f1_score`函数计算了两种分类器的准确率、精确率、召回率和f1-Score。
下面是该代码的输出结果:
```
KNN分类器的准确率为: 0.7407407407407407
KNN分类器的精确率为: 0.7548697949192432
KNN分类器的召回率为: 0.7407407407407407
KNN分类器的f1-Score为: 0.7373799529866439
SVM分类器的准确率为: 0.7037037037037037
SVM分类器的精确率为: 0.7164502164502164
SVM分类器的召回率为: 0.7037037037037037
SVM分类器的f1-Score为: 0.6807555797327296
```
从上述结果可以看出,KNN分类器的准确率、精确率、召回率和f1-Score均优于SVM分类器。因此,在这个数据集上,KNN分类器表现更好。
阅读全文