使用k近邻算法实现葡萄酒分类python代码
时间: 2024-10-23 11:08:13 浏览: 22
K近邻(K-Nearest Neighbors, KNN)是一种基于实例的学习方法,常用于分类任务。下面是使用Python的scikit-learn库实现葡萄酒分类的一个简单示例,假设我们已经有了一个葡萄酒数据集(如UCI Wine Dataset):
```python
# 导入所需的库
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# 加载葡萄酒数据集
wine = datasets.load_wine()
X = wine.data
y = wine.target
# 数据预处理:标准化特征值
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# 设置KNN模型,这里取k=3为例
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(X_train, y_train)
# 预测测试集
y_pred = knn.predict(X_test)
# 计算并打印准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
#
阅读全文