machine-learning - ResNet50:层global_average_pooling2d_2的输入0与层不兼容:预期ndim=4,发现ndim=2
问题描述
尝试使用迁移学习在自定义数据集上实现 ResNet50,但出现此错误:
ValueError: Input 0 of layer global_average_pooling2d_2 is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: [None, 2048]
这是我的代码:
img_height, img_width = (224, 224)
batch_size = 32
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size = (img_height, img_width),
batch_size = batch_size,
class_mode = 'categorical',
subset = 'training')
base_model = ResNet50(include_top = False, weights = 'imagenet', pooling='avg')
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation = 'relu')(x)
predictions = Dense(train_generator.num_classes, activation = 'softmax')(x)
model = Model(inputs = base_model.input, outputs = predictions)
for layer in base_model.layers:
layer.trainable = False
model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
model.fit(train_generator, epochs = 10)
我已按照其他答案中的建议将 include_top 设置为 False。我哪里出错了,我该如何解决?
解决方案
在这种情况下我们不需要GlobalAveragePooling2D
,试试这个代码:
base_model = ResNet50(include_top = False, weights = 'imagenet', pooling='avg')
x = base_model.output
x = Dense(1024, activation = 'relu')(x)
predictions = Dense(train_generator.num_classes, activation = 'softmax')(x)
model = Model(inputs = base_model.input, outputs = predictions)
推荐阅读
- php - 基于多维数组中的子级构建php数组
- sql - 错误:列“owner_name”指定了多次
- java - Java 8 上的 TLS 版本始终默认为 TLSv1
- kubernetes - Prometheus Operator + 新 Kubernetes Minikube = DeadMansSwitch + KubeControllerManagerDown + KubeSchedulerDown + TargetDown
- sql - 与 sum 一起的情况
- header - 改变
在特定的 prestashop 中标记 - sql - MS SQL 根据一个列表执行多个更新
- r - 如何从列表转换为省略号?
- excel - 由于脚本安全性,Excel VBA GetObject 返回 Outlook.Application 的类型不匹配
- ios - 即使没有条件请求,设置缓存控制是否会自动启用缓存?