美文网首页
PaddlePaddle中的Tensor的广播规则

PaddlePaddle中的Tensor的广播规则

作者: LabVIEW_Python | 来源:发表于2021-02-25 06:29 被阅读0次

在两个Tensor上进行操作时,PaddlePaddle逐元素比较其形状。它从尾部(即最右边)的尺寸开始,一直向左移动,能广播的条件是:

  • 要么尺寸相等
  • 要么其中一个为1
  • 要么其中一个不存在
    如果不满足这些条件, 则会引发异常,表明Tensor的形状不兼容:ValueError: (InvalidArgument) Broadcast dimension mismatch

例1:一个256x256x3RGB值Tensor,并且想要按不同的值缩放图像中的每种颜色,则可以将图像乘以一维Tensor,并使用3个值。根据广播规则来排列这些Tensor的尾轴的大小,表明它们是兼容(match)的
Image (3d tensor): 256 x 256 x 3
Scale (1d tensor): __________ 3
Result (3d tensor): 256 x 256 x 3

import paddle

image = paddle.ones((256,256,3))
scale = paddle.to_tensor([0.5,0.5,0.5])
print(image.shape)
print(scale.shape)
result = image * scale
print(result.shape)

[256, 256, 3]
[3]
[256, 256, 3]

例2:两个张量:
x: 2x1x4
y: __3x2
可以看出,尾部对齐后,不符合广播尺寸规则

import paddle

x = paddle.ones((2, 1, 4))
y = paddle.ones((3, 2))
z = x + y

ValueError: (InvalidArgument) Broadcast dimension mismatch. Operands could not be broadcast together with the shape of X = [2, 1,
4] and the shape of Y = [3, 2]. Received [4] in X is not equal to [2] in Y at i:2.
[Hint: Expected x_dims_array[i] == y_dims_array[i] || x_dims_array[i] <= 1 || y_dims_array[i] <= 1 == true, but received x_dims_array[i] == y_dims_array[i] || x_dims_array[i] <= 1 || y_dims_array[i] <= 1:0 != true:1.] (at D:\v2.0.0\paddle\paddle/fluid/operators/elementwise/elementwise_op_function.h:160)
[operator < elementwise_add > error]

相关文章

网友评论

      本文标题:PaddlePaddle中的Tensor的广播规则

      本文链接:https://www.haomeiwen.com/subject/dohyxltx.html