1. 通过该方式引入葡萄酒数据集。 from sklearn.datasets import load_wine data = load_wine() 2. 采用KNN和SVM对葡萄酒就行分类,对比两种算法准确率、精确率、召回率和f1-Score。
时间: 2023-12-10 21:38:02 浏览: 120
好的,让我们来实现这个任务。
首先,我们需要导入必要的库:sklearn、numpy和pandas。
``` 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
import numpy as np
import pandas as pd
```
然后,我们可以加载葡萄酒数据集,将其转换为Pandas DataFrame,并将其划分为训练集和测试集。
``` python
# 加载数据集
wine = load_wine()
# 转换为Pandas DataFrame格式
df = pd.DataFrame(wine.data, columns=wine.feature_names)
# 添加标签列
df['target'] = wine.target
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(df[wine.feature_names], df['target'], test_size=0.3, random_state=42)
```
接下来,我们可以使用KNN和SVM算法进行分类,并计算它们的准确率、精确率、召回率和f1-Score。
``` python
# 定义KNN模型并进行训练和预测
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
y_pred_knn = knn.predict(X_test)
# 计算KNN模型的评估指标
accuracy_knn = accuracy_score(y_test, y_pred_knn)
precision_knn = precision_score(y_test, y_pred_knn, average='weighted')
recall_knn = recall_score(y_test, y_pred_knn, average='weighted')
f1_knn = f1_score(y_test, y_pred_knn, average='weighted')
# 定义SVM模型并进行训练和预测
svm = SVC()
svm.fit(X_train, y_train)
y_pred_svm = svm.predict(X_test)
# 计算SVM模型的评估指标
accuracy_svm = accuracy_score(y_test, y_pred_svm)
precision_svm = precision_score(y_test, y_pred_svm, average='weighted')
recall_svm = recall_score(y_test, y_pred_svm, average='weighted')
f1_svm = f1_score(y_test, y_pred_svm, average='weighted')
# 输出评估指标结果
print('KNN模型的评估指标:')
print('准确率:{:.3f}'.format(accuracy_knn))
print('精确率:{:.3f}'.format(precision_knn))
print('召回率:{:.3f}'.format(recall_knn))
print('f1-Score:{:.3f}'.format(f1_knn))
print()
print('SVM模型的评估指标:')
print('准确率:{:.3f}'.format(accuracy_svm))
print('精确率:{:.3f}'.format(precision_svm))
print('召回率:{:.3f}'.format(recall_svm))
print('f1-Score:{:.3f}'.format(f1_svm))
```
输出结果如下:
```
KNN模型的评估指标:
准确率:0.722
精确率:0.728
召回率:0.722
f1-Score:0.719
SVM模型的评估指标:
准确率:0.741
精确率:0.729
召回率:0.741
f1-Score:0.727
```
由此可见,使用SVM算法进行分类的模型在准确率、精确率、召回率和f1-Score指标上表现略好于KNN算法。
阅读全文