[英]InvalidArgumentError: Incompatible shapes: [32,128] vs. [128,128] [Op:BroadcastTo]
I want to broadcast my tensor of size (32, 128)
to (128, 128)
but it generates this error.我想将我的
(32, 128)
大小的张量广播到(128, 128)
但它会产生此错误。 InvalidArgumentError: Incompatible shapes: [32,128] vs. [128,128] [Op:BroadcastTo]. InvalidArgumentError:不兼容的形状:[32,128] 与 [128,128] [Op:BroadcastTo]。
I want to know whether it's possible to broadcast it or not.我想知道是否可以广播。 what are the possible reasons to perform this.
执行此操作的可能原因是什么。 I use the following code
我使用以下代码
loss = tf.broadcast_to(kl_loss, [128, 128])
You need to some how upsample your tensor.你需要一些如何对你的张量进行上采样。 Maybe try
tf.tile
or tf.repeat
or tf.concat
:也许尝试
tf.tile
或tf.repeat
或tf.concat
:
import tensorflow as tf
kl_loss = tf.random.normal((32, 128))
print(tf.repeat(kl_loss, repeats = int(128 / tf.shape(kl_loss)[0]), axis=0).shape)
print(tf.tile(kl_loss, multiples=[int(128 / tf.shape(kl_loss)[0]), 1]).shape)
print(tf.concat([kl_loss, kl_loss, kl_loss, kl_loss], axis=0).shape)
(128, 128)
(128, 128)
(128, 128)
We can use tf.broadcast_to
, But we need to consider that first we need to convert 2D tensor to 3D tensor and then reshape it to 2D like below.我们可以使用
tf.broadcast_to
,但我们需要考虑首先我们需要将 2D 张量转换为 3D 张量,然后将其重新整形为 2D,如下所示。
import tensorflow as tf
kl_loss = tf.random.uniform((32, 128))
print(kl_loss.shape)
# (32, 128)
result = tf.reshape(tf.broadcast_to(kl_loss, [4 , 32, 128]), [128, 128])
# ------------------------------------------ ^4 : 128//32
print(result.shape)
# (128, 128)
What will the output look like? output 会是什么样子? (Example for broadcasting from (2, 3) to (4, 3))
(从 (2, 3) 到 (4, 3) 的广播示例)
tf.random.set_seed(123)
x = tf.random.uniform((2, 3))
print(x)
y = tf.broadcast_to(x, [2, 2, 3])
print(y)
z = tf.reshape(y, [4, 3])
print(z)
# x =>
tf.Tensor(
[[0.12615311 0.5727513 0.2993133 ]
[0.5461836 0.7205157 0.7889533 ]], shape=(2, 3), dtype=float32)
# y =>
tf.Tensor(
[[[0.12615311 0.5727513 0.2993133 ]
[0.5461836 0.7205157 0.7889533 ]]
[[0.12615311 0.5727513 0.2993133 ]
[0.5461836 0.7205157 0.7889533 ]]], shape=(2, 2, 3), dtype=float32)
# z =>
tf.Tensor(
[[0.12615311 0.5727513 0.2993133 ]
[0.5461836 0.7205157 0.7889533 ]
[0.12615311 0.5727513 0.2993133 ]
[0.5461836 0.7205157 0.7889533 ]], shape=(4, 3), dtype=float32)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.