ValueError:检查目标时出错:预期avg_pool具有4维,但数组的形状为(100,2)

时间:2019-10-09 15:41:39

标签: python keras classification resnet pooling

我尝试运行此代码(二进制分类),但仍停留在此错误:ValueError:检查目标时出错:预期avg_pool具有4维,但数组的形状为(100,2)

GGally

2 个答案:

答案 0 :(得分:0)

删除这些行,它将起作用,

model.layers.pop() 
model = Model(input=model.input,output=model.layers[-1].output)

前者将删除最后一个(Dense)层,并且字母表示没有最后一个(Flatten的模型,因为Dense已经弹出)。

这没有意义,因为您的目标数据是(100,2)。为什么把它们放在第一位呢?

我也认为这行

predictions = Dense(1, activation='sigmoid')(x)

会出错,因为您的目标数据是2通道,如果确实出错,则将其更改为

predictions = Dense(2, activation='sigmoid')(x)

更新

avg_pool的输出为4维(batch_size,height,width,channel)。您需要先执行Flatten或使用GlobalAveragePooling2D代替AveragePooling2D

喜欢

x = model.get_layer('avg_pool').output
x = keras.layers.Flatten()(x)
predictions = Dense(1, activation='sigmoid')(x)

model = ResNet50(include_top=False, pooling='avg', weights='imagenet')  # `pooling='avg'` makes the `ResNet50` include a `GlobalAveragePoiling` layer and `include_top=False` means that you don't include the imagenet's output layer
x = model.output  # as I use `include_top=False`, you don't need to care the layer name, just use the model's output right away
predictions = Dense(1, activation='sigmoid')(x)

也正如@ bit01所说,将class_mode='categorical'更改为class_mode ='binary'。

答案 1 :(得分:0)

class_mode='categorical'class_mode='binary'中将train_generator更改为validation_generator

另外,删除已创建模型的以下行。

model.layers.pop() 
model = Model(input=model.input,output=model.layers[-1].output)

因此,您的模型将是:

model = ResNet50(include_top=True, weights='imagenet')
x = model.get_layer('avg_pool').output
x = Flatten()(x)
predictions = Dense(1, activation='sigmoid')(x)
model = Model(input = model.input, output = predictions)