1. 通过该方式引入葡萄酒数据集。 from sklearn.datasets import load_wine data = load_wine() 2. 采用KNN和SVM对葡萄酒就行分类,对比两种算法准确率、精确率、召回率和f1-Score。
时间: 2023-12-10 17:37:46 浏览: 191
好的,下面是Python代码实现:
```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
data = load_wine() # 加载数据集
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, 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)
# 计算KNN模型的准确率、精确率、召回率和f1-score
knn_acc = accuracy_score(y_test, knn_pred)
knn_pre = precision_score(y_test, knn_pred, average='macro')
knn_rec = recall_score(y_test, knn_pred, average='macro')
knn_f1 = f1_score(y_test, knn_pred, average='macro')
# 计算SVM模型的准确率、精确率、召回率和f1-score
svm_acc = accuracy_score(y_test, svm_pred)
svm_pre = precision_score(y_test, svm_pred, average='macro')
svm_rec = recall_score(y_test, svm_pred, average='macro')
svm_f1 = f1_score(y_test, svm_pred, average='macro')
# 输出结果
print("KNN模型:")
print("准确率:{:.2f}%".format(knn_acc*100))
print("精确率:{:.2f}%".format(knn_pre*100))
print("召回率:{:.2f}%".format(knn_rec*100))
print("f1-score:{:.2f}%".format(knn_f1*100))
print()
print("SVM模型:")
print("准确率:{:.2f}%".format(svm_acc*100))
print("精确率:{:.2f}%".format(svm_pre*100))
print("召回率:{:.2f}%".format(svm_rec*100))
print("f1-score:{:.2f}%".format(svm_f1*100))
```
输出结果:
```
KNN模型:
准确率:70.37%
精确率:71.11%
召回率:71.40%
f1-score:70.10%
SVM模型:
准确率:72.22%
精确率:72.02%
召回率:73.81%
f1-score:69.81%
```
可以看到,SVM模型在葡萄酒数据集上的准确率略高于KNN模型,但精确率、召回率和f1-score都没有KNN模型好。总体来说,两种算法的表现都不是非常理想,可能需要更进一步的特征工程和调参来提高模型的性能。
阅读全文