能否提供一个用Python实现的猫狗图像分类(二分类任务)的代码示例,用于识别猫和狗的图片?
时间: 2024-10-24 08:10:02 浏览: 27
当然可以,这里是一个简单的Python代码示例,使用了深度学习库Keras和预训练模型ResNet50来进行猫狗图像分类。首先,你需要安装`tensorflow`, `keras`, 和 `numpy` 等库。
```python
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model
# 加载预训练的ResNet50模型,去掉顶层的全连接层
base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# 添加自定义的分类层
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(1, activation='sigmoid')(x)
# 创建新的模型,输入是ResNet50的输入,输出是我们的预测层
model = Model(inputs=base_model.input, outputs=predictions)
# 冻结预训练模型的所有层
for layer in base_model.layers:
layer.trainable = False
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 数据增强
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input,
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
# 训练数据路径,替换为你实际的路径
train_generator = train_datagen.flow_from_directory(
'path_to_train_data',
target_size=(224, 224),
batch_size=32,
class_mode='binary'
)
# 验证数据路径
validation_generator = train_datagen.flow_from_directory(
'path_to_validation_data',
target_size=(224, 224),
batch_size=32,
class_mode='binary',
shuffle=False # 验证集不需要随机化
)
# 训练模型
history = model.fit(train_generator,
steps_per_epoch=len(train_generator),
epochs=10,
validation_data=validation_generator,
validation_steps=len(validation_generator))
#
阅读全文