猫狗识别tensorflow代码
时间: 2023-08-11 11:07:52 浏览: 32
以下是使用 TensorFlow 和 Keras API 进行猫狗识别的示例代码:
```python
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 定义训练和验证数据集路径
train_dir = '/path/to/train_data'
validation_dir = '/path/to/validation_data'
# 数据预处理
train_datagen = ImageDataGenerator(rescale=1./255)
validation_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
# 构建 CNN 模型
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# 编译模型
model.compile(loss='binary_crossentropy',
optimizer=tf.keras.optimizers.RMSprop(lr=1e-4),
metrics=['accuracy'])
# 训练模型
history = model.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=20,
validation_data=validation_generator,
validation_steps=50,
verbose=2)
# 使用模型进行预测
import numpy as np
from tensorflow.keras.preprocessing import image
img_path = '/path/to/test_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('狗')
```
需要注意的是,上述代码中的 `train_dir` 和 `validation_dir` 需要替换成对应的训练和验证数据集的路径。
阅读全文