用参差不齐的张量广播

Broadcasting with ragged tensor

定义x为:

>>> import tensorflow as tf
>>> x = tf.constant([1, 2, 3])

为什么这个正常的张量乘法可以很好地用于广播:

>>> tf.constant([[1, 2, 3], [4, 5, 6]]) * tf.expand_dims(x, axis=0)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[ 1,  4,  9],
      [ 4, 10, 18]], dtype=int32)>

而这个张量参差不齐的不是?

>>> tf.ragged.constant([[1, 2, 3], [4, 5, 6]]) * tf.expand_dims(x, axis=0)
*** tensorflow.python.framework.errors_impl.InvalidArgumentError: Expected 'tf.Tensor(False, shape=(), dtype=bool)' to be true. Summarized data: b'Unable to broadcast: dimension size mismatch in dimension'
1
b'lengths='
3
b'dim_size='
3, 3

如何让一维张量在二维参差不齐的张量上广播? (我使用的是 TensorFlow 2.1。)

如果在Ragged Tensor中添加ragged_rank=0,问题将得到解决,如下图:

tf.ragged.constant([[1, 2, 3], [4, 5, 6]], ragged_rank=0) * tf.expand_dims(x, axis=0)

完整的工作代码是:

%tensorflow_version 2.x

import tensorflow as tf
x = tf.constant([1, 2, 3])

print(tf.ragged.constant([[1, 2, 3], [4, 5, 6]], ragged_rank=0) * tf.expand_dims(x, axis=0))

以上代码的输出为:

tf.Tensor(
[[ 1  4  9]
 [ 4 10 18]], shape=(2, 3), dtype=int32)

再更正一次。

根据 BroadcastingBroadcasting is the process of **making** tensors with different shapes have compatible shapes for elementwise operations 的定义,无需明确指定 tf.expand_dims,Tensorflow 会处理它。

因此,下面的代码有效并演示了广播的属性:

%tensorflow_version 2.x

import tensorflow as tf
x = tf.constant([1, 2, 3])

print(tf.ragged.constant([[1, 2, 3], [4, 5, 6]], ragged_rank=0) * x)

以上代码的输出为:

tf.Tensor(
[[ 1  4  9]
 [ 4 10 18]], shape=(2, 3), dtype=int32)

更多信息请参考this link

希望这对您有所帮助。快乐学习!