如何使用 Tensorflow 将张量的每一列乘以另一个张量的所有列?
How can I multiply each column of a Tensor by all columns of an another using Tensorflow?
设 a
和 b
为张量,定义为:
a = tf.constant([[1, 4],
[2, 5],
[3, 6]], tf.float32)
b = tf.constant([[10, 40],
[20, 50],
[30, 60]], tf.float32)
我正在寻找一种方法将 a
的每一列乘以 b
的所有列,产生如下结果:
[[10, 40, 40, 160],
[40, 100, 100, 250],
[90, 180, 180, 360]]
我需要一个可以在具有任意列数 (> 2) 的张量上执行的操作。
我已经开发了一个可以在循环中使用的解决方案。你可以去看看 here.
感谢您的关注。
你可以试试这个:
import tensorflow as tf
a = tf.constant([[1, 4],
[2, 5],
[3, 6]], tf.float32)
b = tf.constant([[10, 40],
[20, 50],
[30, 60]], tf.float32)
a_t = tf.transpose(a)
b_t = tf.transpose(b)
c = tf.transpose(tf.stack([a_t[0] * b_t[0],
a_t[0] * b_t[1],
a_t[1] * b_t[0],
a_t[1] * b_t[1]]))
with tf.Session() as sess:
print(sess.run(c))
然而,对于更大的矩阵,您必须调整索引。
我错过了什么吗?为什么不只是
import tensorflow as tf
a = tf.constant([[1, 4],
[2, 5],
[3, 6]], tf.float32)
b = tf.constant([[10, 40],
[20, 50],
[30, 60]], tf.float32)
h_b, w_a = a.shape.as_list()[:2]
w_b = a.shape.as_list()[1]
c = tf.einsum('ij,ik->ikj', a, b)
c = tf.reshape(c,[h_b, w_a * w_b])
with tf.Session() as sess:
print(sess.run(c))
编辑:添加foo.shape.as_list()
设 a
和 b
为张量,定义为:
a = tf.constant([[1, 4],
[2, 5],
[3, 6]], tf.float32)
b = tf.constant([[10, 40],
[20, 50],
[30, 60]], tf.float32)
我正在寻找一种方法将 a
的每一列乘以 b
的所有列,产生如下结果:
[[10, 40, 40, 160],
[40, 100, 100, 250],
[90, 180, 180, 360]]
我需要一个可以在具有任意列数 (> 2) 的张量上执行的操作。
我已经开发了一个可以在循环中使用的解决方案。你可以去看看 here.
感谢您的关注。
你可以试试这个:
import tensorflow as tf
a = tf.constant([[1, 4],
[2, 5],
[3, 6]], tf.float32)
b = tf.constant([[10, 40],
[20, 50],
[30, 60]], tf.float32)
a_t = tf.transpose(a)
b_t = tf.transpose(b)
c = tf.transpose(tf.stack([a_t[0] * b_t[0],
a_t[0] * b_t[1],
a_t[1] * b_t[0],
a_t[1] * b_t[1]]))
with tf.Session() as sess:
print(sess.run(c))
然而,对于更大的矩阵,您必须调整索引。
我错过了什么吗?为什么不只是
import tensorflow as tf
a = tf.constant([[1, 4],
[2, 5],
[3, 6]], tf.float32)
b = tf.constant([[10, 40],
[20, 50],
[30, 60]], tf.float32)
h_b, w_a = a.shape.as_list()[:2]
w_b = a.shape.as_list()[1]
c = tf.einsum('ij,ik->ikj', a, b)
c = tf.reshape(c,[h_b, w_a * w_b])
with tf.Session() as sess:
print(sess.run(c))
编辑:添加foo.shape.as_list()