以下函数我尝试在 tf.keras.layers.Lambda()
中调用,遵循 TF 2.0 的标准。 inputs
和 outputs
张量将是两个具有相同尺寸和3个颜色通道的图像。我的目标是从 outputs
张量中提取一个掩码,将其应用到 inputs
张量,然后返回结果张量。将张量展平的动机是由于 tf.tensor_scatter_nd_update()
函数的限制。当我构建模型时,由于 indices.shape[0]
是一个 None
值,无法初始化 updates
。如果我在模型外使用两个 tf.constant()
张量来初始化 x
,在急切执行模式下(因为 x
张量有定义的值),它运行得非常好。不幸的是,当我用 tf.keras.layers.Lambda()
调用这个函数时,我收到了以下错误:
TypeError: can't multiply sequence by non-int of type 'NoneType'
@tf.functiondef applyMask(x): # 提取张量 inputs = x[0] outputs = x[1] # 展平输出张量并提取掩码索引 outputs = tf.reshape(outputs,(tf.size(outputs),)) indices = tf.where(outputs==1.) indices = tf.cast(indices, tf.int32) # 从掩码索引构建更新张量 updates = tf.constant([1.]*indices.shape[0]) # 展平输入张量并应用掩码 out_dim = inputs.shape inputs = tf.reshape(inputs,(tf.size(inputs),)) tensor = tf.tensor_scatter_nd_update(inputs, indices, updates) # 重构输入为张量 tensor = tf.reshape(tensor, out_dim) return tensor
回答:
不需要这么复杂。只需这样做,
inp1 = Input(shape=(None, None, 3)) # 输入inp2 = Input(shape=(None, None, 3)) # 输出out = Lambda(lambda x: tf.where(tf.equal(x[1], 1), x[1], x[0]))([inp1, inp2])
甚至可以让 height
和 width
为 None
,只要传递给 inp1
和 inp2
的并行样本在形状上完全相同,tf.where
就能正常工作。