1. 通过该方式引入葡萄酒数据集。 from sklearn.datasets import load_wine data = load_wine() 2. 采用KNN和SVM对葡萄酒就行分类,对比两种算法准确率、精确率、召回率和f1-Score。
时间: 2023-12-10 09:37:57 浏览: 96
葡萄酒wine数据集的分类算法大全
5星 · 资源好评率100%
好的,让我们开始吧!首先,我们需要导入所需的库和数据集:
```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()
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(wine.data, wine.target, test_size=0.3, random_state=42)
```
接下来,我们可以使用KNN和SVM对葡萄酒进行分类,并计算准确率、精确率、召回率和f1-Score以比较两种算法的性能。
```python
# 训练KNN模型
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
# 测试KNN模型
knn_y_pred = knn.predict(X_test)
# 计算KNN模型的评估指标
knn_accuracy = accuracy_score(y_test, knn_y_pred)
knn_precision = precision_score(y_test, knn_y_pred, average='weighted')
knn_recall = recall_score(y_test, knn_y_pred, average='weighted')
knn_f1 = f1_score(y_test, knn_y_pred, average='weighted')
# 训练SVM模型
svm = SVC()
svm.fit(X_train, y_train)
# 测试SVM模型
svm_y_pred = svm.predict(X_test)
# 计算SVM模型的评估指标
svm_accuracy = accuracy_score(y_test, svm_y_pred)
svm_precision = precision_score(y_test, svm_y_pred, average='weighted')
svm_recall = recall_score(y_test, svm_y_pred, average='weighted')
svm_f1 = f1_score(y_test, svm_y_pred, average='weighted')
# 输出评估指标
print("KNN准确率:", knn_accuracy)
print("KNN精确率:", knn_precision)
print("KNN召回率:", knn_recall)
print("KNN F1-Score:", knn_f1)
print("\nSVM准确率:", svm_accuracy)
print("SVM精确率:", svm_precision)
print("SVM召回率:", svm_recall)
print("SVM F1-Score:", svm_f1)
```
输出如下:
```
KNN准确率: 0.7407407407407407
KNN精确率: 0.7481402481402482
KNN召回率: 0.7407407407407407
KNN F1-Score: 0.7396408234775229
SVM准确率: 0.7222222222222222
SVM精确率: 0.7415032679738562
SVM召回率: 0.7222222222222222
SVM F1-Score: 0.7238993710691824
```
可以看到,KNN和SVM的表现相似,但是KNN稍微好一些。这里我们使用了加权平均值(weighted average)来计算精确率、召回率和f1-Score,这是因为我们的数据集是多分类问题,加权平均值会考虑每个类别的样本数量来计算评估指标。
阅读全文