keras resnet
时间: 2024-01-22 08:16:11 浏览: 71
以下是使用Keras训练自己的数据的ResNet模型的示例代码:
```python
from keras.applications.resnet50 import ResNet50
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras.preprocessing.image import ImageDataGenerator
# 创建ResNet模型
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(num_classes, activation='softmax')(x)
# 构建完整模型
model = Model(inputs=base_model.input, outputs=predictions)
# 冻结ResNet的权重
for layer in base_model.layers:
layer.trainable = False
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 数据增强
train_datagen = ImageDataGenerator(
rescale=1./255,
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_data_dir,
target_size=(224, 224),
batch_size=batch_size,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(224, 224),
batch_size=batch_size,
class_mode='categorical')
# 训练模型
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size)
# 保存模型
model.save('resnet_model.h5')
```
请注意,上述代码中的一些变量(如`train_data_dir`,`validation_data_dir`,`num_classes`等)需要根据您的数据集进行相应的设置。
阅读全文