图像分类识别衣服帽子裤子鞋子的代码
时间: 2023-11-20 15:07:18 浏览: 137
这是一个简单的图像分类识别衣服、帽子、裤子和鞋子的代码示例:
```python
import tensorflow as tf
from tensorflow.keras import layers, models
# 定义模型
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(128, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(512, activation='relu'),
layers.Dense(4, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 加载数据集
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'/path/to/train/directory',
target_size=(150, 150),
batch_size=20,
class_mode='categorical')
validation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
validation_generator = validation_datagen.flow_from_directory(
'/path/to/validation/directory',
target_size=(150, 150),
batch_size=20,
class_mode='categorical')
# 训练模型
model.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=10,
validation_data=validation_generator,
validation_steps=50)
# 对新图像进行预测
import numpy as np
from tensorflow.keras.preprocessing import image
img_path = '/path/to/new/image'
img = image.load_img(img_path, target_size=(150, 150))
img_tensor = image.img_to_array(img)
img_tensor = np.expand_dims(img_tensor, axis=0)
img_tensor /= 255.
prediction = model.predict(img_tensor)
print(prediction)
```
这个代码使用了 TensorFlow 和 Keras 库来定义和训练一个卷积神经网络模型。数据集应该按照类别组织在两个不同的文件夹中,每个文件夹的名称应该是类别的名称。在训练期间,模型将使用 ImageDataGenerator 来从数据集中加载和预处理图像。最后,模型将对新图像进行预测并输出一个四维向量,每个元素代表一个类别的概率。
阅读全文