【问题标题】:Keras / TensorFlow: concatenating layer of constants to a convolutionKeras / TensorFlow:将常数层连接到卷积
【发布时间】:2018-07-18 05:22:39
【问题描述】:

对于每个卷积激活图,我想连接一层常量——更具体地说,我想连接一个网格。 (这是为了转载 Uber 的一篇论文。)

例如,假设我有一个(?, 256, 256, 32) 的激活图;然后我想连接一个形状为(?, 256, 256, 1)的常量层。

这就是我的做法:

from keras import layers
import tensorflow as tf
import numpy as np

input_layer = layers.Input((256, 256, 3))
conv = layers.Conv2D(32, 3, padding='same')(input_layer)
print('conv:', conv.shape)


xx, yy = np.mgrid[:256, :256]  # [(256, 256), (256, 256)]
xx = tf.constant(xx, np.float32)
yy = tf.constant(yy, np.float32)

xx = tf.reshape(xx, (-1, 256, 256, -1))
yy = tf.reshape(yy, (-1, 256, 256, -1))
print('xx:', xx.shape, 'yy:', yy.shape)

concat = layers.Concatenate()([conv, xx, yy])
print('concat:', concat.shape)

conv2 = layers.Conv2D(32, 3, padding='same')(concat)
print('conv2:', conv2.shape)

但我得到了错误:

conv: (?, 256, 256, 32)
xx: (?, 256, 256, ?) yy: (?, 256, 256, ?)
concat: (?, 256, 256, ?)
Traceback (most recent call last):
File "temp.py", line 21, in <module>
conv2 = layers.Conv2D(32, 3, padding='same')(concat)
[...]
raise ValueError('The channel dimension of the inputs '
ValueError: The channel dimension of the inputs should be defined. Found `None`.

问题是我的常量层是(?, 256, 256, ?),而不是(?, 256, 256, 1),然后下一个卷积层error-out。

我尝试了其他方法但没有成功。

PS:我试图实现的论文已经是implemented here

【问题讨论】:

    标签: tensorflow keras


    【解决方案1】:

    问题在于tf.reshape 无法推断出多于一维的形状(即,对多于一维使用-1 会导致未定义的维度?)。由于您希望 xxyy 的形状为 (?, 256, 256, 1),因此您可以将这些张量整形如下:

    xx = tf.reshape(xx, (-1, 256, 256, 1))
    yy = tf.reshape(yy, (-1, 256, 256, 1))
    

    生成的形状将是(1, 256, 256, 1)。现在,conv(?, 256, 256, 32)keras.layers.Concatenate 要求所有输入的形状都匹配,除了 concat 轴。然后,您可以使用 tf.tile 沿第一个维度重复张量 xxyy 以匹配批量大小:

    xx = tf.tile(xx, [tf.shape(conv)[0], 1, 1, 1])
    yy = tf.tile(yy, [tf.shape(conv)[0], 1, 1, 1])
    

    xxyy 的形状现在是 (?, 256, 256, 1),并且可以连接张量,因为它们的第一个维度与批量大小匹配。

    【讨论】:

    • 我不知道我可以传递尚未定义的形状 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多