用CNN实现猫狗识别代码
时间: 2023-09-08 11:12:18 浏览: 100
好的,以下是一个简单的猫狗识别的CNN代码实现。
首先,导入必要的库和模块:
```
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.preprocessing.image import ImageDataGenerator
```
接着,定义一些超参数和数据处理的参数:
```
# 图像大小为 128x128 像素
img_width, img_height = 128, 128
# 训练和验证集的目录
train_dir = 'train'
val_dir = 'val'
# 批次大小
batch_size = 32
# 训练数据增强
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
# 验证数据增强
val_datagen = ImageDataGenerator(rescale=1./255)
# 载入训练和验证数据集
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
val_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
```
接着,定义一个简单的CNN模型:
```
# 初始化模型
model = Sequential()
# 添加卷积层和池化层
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(img_width, img_height, 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
# 添加全连接层
model.add(Flatten())
model.add(Dense(128, activation='relu'))
# 添加 Dropout 层,减少过拟合
model.add(Dropout(0.5))
# 输出层
model.add(Dense(1, activation='sigmoid'))
```
然后,编译模型并进行训练:
```
# 编译模型
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# 训练模型
model.fit(train_generator,
steps_per_epoch=len(train_generator),
epochs=50,
validation_data=val_generator,
validation_steps=len(val_generator))
```
最后,评估模型的性能:
```
# 评估模型
test_loss, test_acc = model.evaluate(val_generator, steps=len(val_generator))
print('Test accuracy:', test_acc)
```
这就是一个简单的猫狗识别的CNN代码实现。
阅读全文