使用knn对sklearn wine数据集 进行分类。
时间: 2023-11-24 22:07:11 浏览: 74
好的,我来给你介绍一下如何使用knn对sklearn wine数据集进行分类。
首先,我们需要导入需要的库和数据集。代码如下:
```python
from sklearn.datasets import load_wine
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 = load_wine()
X = wine.data
y = wine.target
```
然后,我们需要将数据集分成训练集和测试集。这可以通过使用train_test_split()函数来完成。代码如下:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
接下来,我们需要对数据集进行标准化处理,这可以使用StandardScaler()函数来进行。代码如下:
```python
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
然后,我们可以使用KNeighborsClassifier()函数来创建一个knn分类器,并且使用fit()函数将训练集的数据和标签传递给分类器。代码如下:
```python
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
```
最后,我们可以使用predict()函数来预测测试集的标签,并且使用accuracy_score()函数来计算模型的准确率。代码如下:
```python
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
这样,我们就可以使用knn对sklearn wine数据集进行分类了。完整代码如下:
```python
from sklearn.datasets import load_wine
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 = 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)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文