1

定义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。)

4

1 回答 1

1

如果添加ragged_rank=0到 Ragged Tensor,问题将得到解决,如下所示:

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)

再更正一次。

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

因此,下面的代码可以正常工作并很好地演示了 Broadcasting 的属性:

%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)

如需更多信息,请参阅此链接

希望这可以帮助。快乐学习!

于 2020-05-26T02:55:27.380 回答