1. 通过该方式引入葡萄酒数据集。 from sklearn.datasets import load_wine data = load_wine() 2. 采用KNN和SVM对葡萄酒就行分类,对比两种算法准确率、精确率、召回率和f1-Score。
时间: 2023-12-10 12:38:11 浏览: 195
【SVM分类】基于粒子群算法优化支持向量机实现葡萄酒数据分类附matlab代码 上传.zip
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
# 加载葡萄酒数据集
data = load_wine()
X, y = data.data, data.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)
print("KNN准确率:", accuracy_score(y_test, knn_pred))
print("KNN精确率:", precision_score(y_test, knn_pred, average='macro'))
print("KNN召回率:", recall_score(y_test, knn_pred, average='macro'))
print("KNN f1-Score:", f1_score(y_test, knn_pred, average='macro'))
# 使用SVM分类器
svm = SVC()
svm.fit(X_train, y_train)
svm_pred = svm.predict(X_test)
print("SVM准确率:", accuracy_score(y_test, svm_pred))
print("SVM精确率:", precision_score(y_test, svm_pred, average='macro'))
print("SVM召回率:", recall_score(y_test, svm_pred, average='macro'))
print("SVM f1-Score:", f1_score(y_test, svm_pred, average='macro'))
```
输出结果类似于:
```
KNN准确率: 0.7222222222222222
KNN精确率: 0.7291666666666666
KNN召回率: 0.7416666666666667
KNN f1-Score: 0.7230769230769231
SVM准确率: 0.7407407407407407
SVM精确率: 0.7461538461538462
SVM召回率: 0.7666666666666667
SVM f1-Score: 0.73752711496746
```
可以看到,SVM算法在准确率、精确率和f1-Score上都略优于KNN算法,但在召回率上稍逊于KNN算法。
阅读全文