简体   繁体   English

Tensorflow中的广播动态维度

[英]Broadcasting dynamic dimension in Tensorflow

I am using Tensorflow from python.我正在使用来自 python 的 Tensorflow。 I have two tensors I wish to concatenate (it could also be another operation, I don't think the exact operation matters to this question).我有两个想要连接的张量(它也可能是另一个操作,我不认为确切的操作对这个问题很重要)。 These tensors have their shapes defined as (N1:= N2 are positive integers):这些张量的形状定义为(N1:= N2 是正整数):

a: (None, N1)
b: (1   , N2)

Since I will be concatenating along the last axis, it seems like this operation could be performed.由于我将沿最后一个轴连接,因此似乎可以执行此操作。 But tensorflow refues.但是 tensorflow 拒绝了。 The code编码

from tensorflow import keras
from tensorflow.keras import layers

N1 = 2
N2 = 3
D1 = None

a = keras.Input(shape=(D1, N1))
b = keras.Input(shape=(1, N2))

c = layers.Concatenate(axis=-1)([a, b])

fails with失败了

ValueError: A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, None, 2), (None, 1, 3)]

The closest I have come to making this work is by using RepeatVector as below, but unfortunately, this only works with static dimensions, not dynamic ones:我最接近完成这项工作的是使用如下所示的RepeatVector ,但不幸的是,这仅适用于 static 尺寸,不适用于动态尺寸:

N1 = 2
N2 = 3
D1 = 7

a = keras.Input(shape=(D1, N1))
b = keras.Input(shape=(N2))
b_repeated = layers.RepeatVector(D1)(b)

c = layers.Concatenate()([a, b_repeated])

Any suggestions of how to concatenate -- ie do the right broadcasting or repeating -- with such None dimensions would be much appreciated!任何关于如何连接的建议 - 即做正确的广播或重复 - 与这样的None维度将不胜感激!

Here is a way to do that with a lambda layer:这是一种使用 lambda 层的方法:

import keras
from keras import layers
import keras.backend as K

N1 = 2
N2 = 3
D1 = None

a = keras.Input(shape=(D1, N1))
b = keras.Input(shape=(N2,))
c = layers.Lambda(lambda ab: K.concatenate([ab[0], K.repeat(ab[1], K.shape(ab[0])[1])],
                                           axis=-1))([a, b])
print(c)
# Tensor("lambda_1/concat:0", shape=(?, ?, 5), dtype=float32)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM