将 4 维张量与 1 维张量相乘

Multiply 4-d tensor with 1-d tensor

我有一个维度为 [batch_size, num_rows, num_cols, num_values] 的 4 阶张量和一个维度为 [num_values] 的 1 阶张量。我想计算第四列中的值和我的 1 阶张量的点积,得到一个维度为 [batch_size, num_rows, num_cols, 1] 的 4 阶张量,然后我可以 tf.squeeze 到一个维度为 [batch_size, num_rows, num_cols]。有谁知道我如何完成这个?

您可以使用 tensordot or reduce_sum:

a = tf.constant(np.random.rand(2, 3, 5, 7))
b = tf.constant(np.random.rand(7))

tf.tensordot(a, b, [-1, -1])  # <tf.Tensor 'Tensordot_1:0' shape=(2, 3, 5) dtype=float64>

tf.reduce_sum(a * b, axis=-1)  # <tf.Tensor 'Tensordot_1:0' shape=(2, 3, 5) dtype=float64>