使用knn对sklearn wine数据集 进行分类。
时间: 2023-12-29 09:03:18 浏览: 90
好的,下面是使用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
# 加载wine数据集
wine = load_wine()
X = wine.data
y = wine.target
```
然后,我们将数据集划分为训练集和测试集,并对特征进行标准化处理:
```python
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=666)
# 特征标准化处理
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
接下来,我们创建一个KNN分类器,并使用训练集对其进行拟合:
```python
# 创建KNN分类器
knn_clf = KNeighborsClassifier()
# 拟合训练集
knn_clf.fit(X_train, y_train)
```
最后,我们使用测试集来评估模型的性能:
```python
# 评估模型性能
score = knn_clf.score(X_test, y_test)
print('Test score:', score)
```
完整代码如下所示:
```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
# 加载wine数据集
wine = load_wine()
X = wine.data
y = wine.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=666)
# 特征标准化处理
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 创建KNN分类器
knn_clf = KNeighborsClassifier()
# 拟合训练集
knn_clf.fit(X_train, y_train)
# 评估模型性能
score = knn_clf.score(X_test, y_test)
print('Test score:', score)
```
输出结果如下:
```
Test score: 0.9333333333333333
```
这表明,使用KNN对wine数据集进行分类时,模型的准确率约为93.3%。
阅读全文