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

标签 python tensorflow keras deep-learning conv-neural-network

我正在使用带有 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.

关于python - 具有可变输入大小的 tensorflow Conv 网络的 Keras,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56546049/

相关文章:

python - 将标签映射到 tf.unique_with_counts() 之后的计数

python - Keras历史平均自定义损失函数

python - 如何修复 _load_libtiff 函数中的 IOError?

python - 使用Python unicode的特殊字符问题

python - Python 中是否有允许在单个文件中管理虚拟文件系统的库?

python - input() 在 Windows 8 (python 3.3) 中阻止其他 python 进程

python - 如何在keras中将回归输出限制在0到1之间

python - 根据 Pandas Python 中的分组列值执行条件过滤

tensorflow - 如何将 tfjs 的 body-pix 模型转换为 keras h5 或 tensorflow 卡住图

tensorflow - 具有交叉熵的像素级 softmax 用于多类分割