使用knn对sklearn wine数据集 进行分类
时间: 2023-11-24 09:07:11 浏览: 97
code_knn_python_scale_balancescale_SVM_
好的,我们可以按照以下步骤使用KNN算法对sklearn中的wine数据集进行分类:
1. 导入所需的库和数据集:
```python
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
wine = load_wine()
X = wine.data
y = wine.target
```
2. 将数据集划分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
3. 创建KNN模型并进行训练:
```python
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
```
4. 使用训练好的模型进行预测并计算准确率:
```python
y_pred = knn.predict(X_test)
accuracy = knn.score(X_test, y_test)
print("预测结果:", y_pred)
print("准确率:", accuracy)
```
完整代码如下:
```python
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
wine = load_wine()
X = wine.data
y = wine.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
accuracy = knn.score(X_test, y_test)
print("预测结果:", y_pred)
print("准确率:", accuracy)
```
阅读全文