做一个卷积神经网络猫狗识别Python的代码
时间: 2023-09-14 15:09:27 浏览: 104
基于卷积神经网络的猫狗识别
5星 · 资源好评率100%
好的,下面是一个简单的卷积神经网络猫狗识别Python代码,使用Keras框架:
```python
import os
import numpy as np
from keras.preprocessing.image import load_img, img_to_array
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
# 设置训练和验证数据集的路径
train_dir = 'train/'
validation_dir = 'validation/'
# 定义模型的架构
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 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(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(512, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# 编译模型
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
# 定义生成器
from keras.preprocessing.image import ImageDataGenerator
# 对训练和验证图像进行增强处理
train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(150, 150), batch_size=32, class_mode='binary')
validation_generator = test_datagen.flow_from_directory(validation_dir, target_size=(150, 150), batch_size=32, class_mode='binary')
# 训练模型
history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=100, validation_data=validation_generator, validation_steps=50)
# 保存模型
model.save('cats_dogs_cnn.h5')
```
注意:这个代码只是一个简单的示例,你需要根据自己的数据集和需求进行适当修改。同时,要提醒你注意数据集的准备和预处理,这对于模型的性能和准确性至关重要。
阅读全文