请帮我写出用ImageDataGenerator导入图像并且基于keras实现ResNet实现图像二分类的代码
时间: 2024-03-04 15:50:52 浏览: 64
好的,以下是代码实现:
```python
# 导入必要的库
import numpy as np
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Conv2D, BatchNormalization, Activation, Add, AveragePooling2D, Flatten
from tensorflow.keras.optimizers import Adam
# 定义ResNet的残差块
def residual_block(x, filters, strides=(1, 1)):
shortcut = x
x = Conv2D(filters=filters, kernel_size=(3, 3), strides=strides, padding='same')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters=filters, kernel_size=(3, 3), strides=(1, 1), padding='same')(x)
x = BatchNormalization()(x)
if strides != (1, 1) or shortcut.shape[-1] != filters:
shortcut = Conv2D(filters=filters, kernel_size=(1, 1), strides=strides, padding='valid')(shortcut)
shortcut = BatchNormalization()(shortcut)
x = Add()([shortcut, x])
x = Activation('relu')(x)
return x
# 定义ResNet模型
def resnet(input_shape, num_classes):
inputs = Input(input_shape)
x = Conv2D(filters=64, kernel_size=(7, 7), strides=(2, 2), padding='same')(inputs)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = AveragePooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
x = residual_block(x, filters=64, strides=(1, 1))
x = residual_block(x, filters=64, strides=(1, 1))
x = residual_block(x, filters=128, strides=(2, 2))
x = residual_block(x, filters=128, strides=(1, 1))
x = residual_block(x, filters=256, strides=(2, 2))
x = residual_block(x, filters=256, strides=(1, 1))
x = residual_block(x, filters=512, strides=(2, 2))
x = residual_block(x, filters=512, strides=(1, 1))
x = AveragePooling2D(pool_size=(7, 7), strides=(1, 1))(x)
x = Flatten()(x)
outputs = Dense(units=num_classes, activation='softmax')(x)
model = Model(inputs=inputs, outputs=outputs)
return model
# 加载数据并进行数据增强
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(directory='/path/to/train/dataset', target_size=(224, 224), batch_size=32, class_mode='binary')
test_generator = test_datagen.flow_from_directory(directory='/path/to/test/dataset', target_size=(224, 224), batch_size=32, class_mode='binary')
# 构建ResNet模型
model = resnet(input_shape=(224, 224, 3), num_classes=2)
# 编译模型并开始训练
model.compile(optimizer=Adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])
model.fit_generator(generator=train_generator, steps_per_epoch=len(train_generator), epochs=10, validation_data=test_generator, validation_steps=len(test_generator))
```
需要注意的是,这里的`/path/to/train/dataset`和`/path/to/test/dataset`需要替换成实际的训练集和测试集所在的路径。另外,如果是多分类问题,需要将`class_mode`设置为`'categorical'`。
阅读全文