Tensorflow 2.0 中的 4D 张量乘法
4D Tensor multiplication in Tensorflow 2.0
我有 2 个张量:
- 形状为:[128,24,24,256]
- B 的形状为:[128,24,24,64]
我想将它们相加,但是维度不同所以类比二维矩阵我想将张量 B 与其他张量 C 相乘,这样张量乘积 B * C 的维度为 [128,24,24,256 ].
我如何在 tensorflow 中做到这一点?
哪个维度应该是C张量?
这真的取决于你想做什么。我能想到的有两种方法,
选项 1
除最后两个维度外,您保持所有其他维度与 a
和 b
完全相同。您可以将 n 维矩阵乘法视为在最后两个维度上进行矩阵乘法,并按原样为其余维度添加前缀。
a = tf.random.normal(shape=[128,24,24,256])
b = tf.random.normal(shape=[128,24,24,64])
c = tf.random.normal(shape=[128,24,64,256])
# Essentially performing a [24, 64] . [64, 256]
# This is dot product
bc = tf.matmul(b,c)
# Res would be of size `128,24,24,256`
# This is element-wise
res = a * bc
选项 2
您还可以通过将最后两个维度以外的维度保持为 1 来利用广播的力量。前两个维度中的任何一个(或所有维度)都可以为 1,TensorFlow 将处理其余部分。
a = tf.random.normal(shape=[128,24,24,256])
b = tf.random.normal(shape=[128,24,24,64])
# Note how the beginning dimensions are 1
c = tf.random.normal(shape=[1,1,64,256])
bc = tf.matmul(b,c)
res = a * bc
但正如我之前所说,c
的大小实际上取决于您的用例。没有正确的通用答案。
我有 2 个张量:
- 形状为:[128,24,24,256]
- B 的形状为:[128,24,24,64]
我想将它们相加,但是维度不同所以类比二维矩阵我想将张量 B 与其他张量 C 相乘,这样张量乘积 B * C 的维度为 [128,24,24,256 ].
我如何在 tensorflow 中做到这一点? 哪个维度应该是C张量?
这真的取决于你想做什么。我能想到的有两种方法,
选项 1
除最后两个维度外,您保持所有其他维度与 a
和 b
完全相同。您可以将 n 维矩阵乘法视为在最后两个维度上进行矩阵乘法,并按原样为其余维度添加前缀。
a = tf.random.normal(shape=[128,24,24,256])
b = tf.random.normal(shape=[128,24,24,64])
c = tf.random.normal(shape=[128,24,64,256])
# Essentially performing a [24, 64] . [64, 256]
# This is dot product
bc = tf.matmul(b,c)
# Res would be of size `128,24,24,256`
# This is element-wise
res = a * bc
选项 2
您还可以通过将最后两个维度以外的维度保持为 1 来利用广播的力量。前两个维度中的任何一个(或所有维度)都可以为 1,TensorFlow 将处理其余部分。
a = tf.random.normal(shape=[128,24,24,256])
b = tf.random.normal(shape=[128,24,24,64])
# Note how the beginning dimensions are 1
c = tf.random.normal(shape=[1,1,64,256])
bc = tf.matmul(b,c)
res = a * bc
但正如我之前所说,c
的大小实际上取决于您的用例。没有正确的通用答案。