python代码实现resnet猫狗二分类源码
时间: 2024-11-20 13:56:03 浏览: 14
python课程设计基于resnet18迁移学习的猫狗分类问题源码.zip
5星 · 资源好评率100%
ResNet(残差网络)是一种深度卷积神经网络模型,在图像识别任务中非常成功,特别是在ImageNet数据集上。以下是使用Python和Keras库实现ResNet基本结构的一个简化的二分类猫狗分类的示例:
```python
from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.layers import Dense, GlobalAveragePooling2D
from keras.models import Model
from keras.preprocessing.image import ImageDataGenerator
# 加载预训练的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)
# 创建新模型
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, rotation_range=20, width_shift_range=0.1, height_shift_range=0.1)
val_datagen = ImageDataGenerator(preprocess_input)
# 训练数据生成器
train_generator = train_datagen.flow_from_directory(
'path_to_train_data',
target_size=(224, 224),
batch_size=32,
class_mode='binary'
)
# 验证数据生成器
validation_generator = val_datagen.flow_from_directory(
'path_to_val_data',
target_size=(224, 224),
batch_size=32,
class_mode='binary'
)
# 训练模型
history = model.fit(
train_generator,
steps_per_epoch=len(train_generator),
epochs=10,
validation_data=validation_generator,
validation_steps=len(validation_generator)
)
阅读全文