Skip to main content
 首页 » 编程设计

python之具有可变输入大小的 tensorflow Conv 网络的 Keras

2025年05月04日22jiqing9006

我正在使用带有 anaconda 的 python 3,以及带有 over tensorflow 的 keras,我的目标是创建一个具有可变输入大小的 Conv 层的网络

我找到了 here使用此代码

i = Input((None, None, 1)) 
o = Conv2D(1, 3, 3)(i) 
model = Model(i, o) 
model.compile('sgd', 'mse') 

我已经用它用这段代码创建了我自己的模型(我需要一个展平层)

model = Sequential() 
I = Input((None, None, 1)) 
c = Conv2D(filters=1, kernel_size=(1, 1))(I) 
f = Flatten()(c) 
o = Dense(10, activation="softmax")(f) 
m = Model(I, o) 
m.compile(loss=categorical_crossentropy, optimizer=SGD(), metrics=["accuracy"]) 

我一直收到这个错误

ValueError: The shape of the input to "Flatten" is not fully defined (got (None, None, 1). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.

似乎问题出在 Flatten 层的输入形状上,当我删除它时,一切正常。

我怎样才能让它与可变大小一起很好地发挥作用?

谢谢

请您参考如下方法:

Dense 需要固定大小的输入/输出,因为它的权重变量的数量必须是固定的。

您的情况有两种解决方案。

  1. 使用 GAP(全局平均池化)而不是 Flatten。 GAP 的输出大小是前一层的 channel 数。因此,它的大小在您的案例中是固定的。
  2. 使用没有密集层的全卷积网络。在这种情况下,网络的输出是二维的,而不是一维的。所以 y 的大小应该是那个大小。

下面是应 Allen M 的要求添加的。
这是一个代码示例:

# The original number of Conv filters are one. 
# But I set it 16 to depict how GAP works. 
# And B/H/W means BatchSize/Height/Width. 
 
#1. using GAP 
I = Input((None, None, 1)) # output shape=(B, H(None), W(None), 1) 
c = Conv2D(filters=16, kernel_size=(1, 1))(I)  # output shape=(B, H, W, 16) 
f = GlobalAveragePooling2D()(c) # output shape=(B, 16) <- space data(H/W) are aggregated by average 
o = Dense(10, activation="softmax")(f) # output shape = (B, 10) 
m = Model(I, o) 
 
#2. all conv 
I = Input((None, None, 1)) # output shape=(B, H, W, 1) 
c = Conv2D(filters=16, kernel_size=(1, 1))(I) # output shape=(B, H, W, 16) 
o = Conv2D(filters=10, kernel_size=(1, 1), activation="softmax")(c) 
    # output shape=(B, H, W, 10) 
m = Model(I, o) 
# The output size of all conv is H * W * 10, where 10 is the number of classes. 
# so the shape of y should be (B, H, W, 1) or (B, H, W) or (B, H, W, 10). 
# That is pixel-wise classification or semantic segmentation.