给我一个KNN分类猫狗图片的代码
时间: 2023-09-16 14:14:23 浏览: 146
Hyperspectral-KNN-Classification-master_knn图像分类_knn_hyperspectra
5星 · 资源好评率100%
好的,下面是一个基于KNN的猫狗分类代码示例:
```python
import numpy as np
import cv2
import os
# 加载训练数据
train_data = []
train_labels = []
for file in os.listdir("train/"):
image = cv2.imread(os.path.join("train/", file))
image = cv2.resize(image, (32, 32))
train_data.append(image.flatten())
if "cat" in file:
train_labels.append(0)
else:
train_labels.append(1)
train_data = np.array(train_data)
train_labels = np.array(train_labels)
# 加载测试数据
test_data = []
test_labels = []
for file in os.listdir("test/"):
image = cv2.imread(os.path.join("test/", file))
image = cv2.resize(image, (32, 32))
test_data.append(image.flatten())
if "cat" in file:
test_labels.append(0)
else:
test_labels.append(1)
test_data = np.array(test_data)
test_labels = np.array(test_labels)
# 训练KNN模型
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(train_data, train_labels)
# 使用模型进行预测
predictions = knn.predict(test_data)
# 计算准确率
accuracy = np.mean(predictions == test_labels)
print("Accuracy:", accuracy)
```
在这个示例中,我们使用了KNN算法来对猫狗图片进行分类。首先,我们将训练数据和测试数据加载到内存中,每张图片都被转换为一个大小为32x32的向量。然后,我们使用sklearn库中的KNeighborsClassifier来训练KNN模型,并使用该模型对测试数据进行预测。最后,我们计算预测准确率并输出结果。
阅读全文