卷积神经网络实现猫狗识别的代码
时间: 2023-09-14 19:10:03 浏览: 79
以下是使用Keras框架实现猫狗识别的卷积神经网络代码示例:
```python
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
# 构建卷积神经网络模型
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(Dense(512, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# 编译模型
model.compile(loss='binary_crossentropy',
optimizer=tf.keras.optimizers.RMSprop(lr=1e-4),
metrics=['accuracy'])
# 训练模型
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'/path/to/train',
target_size=(150, 150),
batch_size=20,
class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
'/path/to/validation',
target_size=(150, 150),
batch_size=20,
class_mode='binary')
model.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=30,
validation_data=validation_generator,
validation_steps=50)
# 预测新数据
import numpy as np
from tensorflow.keras.preprocessing import image
img_path = '/path/to/new_image.jpg'
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)
if prediction < 0.5:
print("这是一只猫")
else:
print("这是一只狗")
```
以上代码演示了使用Keras框架实现猫狗识别的卷积神经网络模型构建、训练和预测的过程。其中,需要注意的是,训练集和测试集需要按照猫和狗进行分类,并分别存放在不同的文件夹中。
阅读全文