How can I multiply each column of a Tensor by all

2019-07-08 10:07发布

Let a and b be tensors defined as:

a = tf.constant([[1, 4],
                 [2, 5],
                 [3, 6]], tf.float32)

b = tf.constant([[10, 40],
                 [20, 50],
                 [30, 60]], tf.float32)

I am looking for a way to multiply each column of a by all columns of b, producing a result as below:

[[10,  40,  40, 160],
 [40, 100, 100, 250],
 [90, 180, 180, 360]]

I need an operation that can be performed over a tensor with an arbitrary number of columns (> 2).

I already developed a solution that can be used within a loop. You can checkout it here.

Thank you for you attention.

2条回答
SAY GOODBYE
2楼-- · 2019-07-08 10:42

Do I miss something? Why not just

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))

edit: add foo.shape.as_list()

查看更多
forever°为你锁心
3楼-- · 2019-07-08 10:52

You can try this:

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))

For bigger matrices, however, you have to adjust the indexing.

查看更多
登录 后发表回答