Warm tip: This article is reproduced from serverfault.com, please click

tensorflow : How to outer product when the tensor's first dim is None?

发布于 2020-11-30 05:37:20

I have a tensor whose shape is None,10 . I want to get a outer product result whose shape is None,100 or None,10,10 . Here is my code :

# output'shape is None,10
output = tf.keras.layers.Concatenate()(encoded_feature_list)
# wrong
cross_output = tf.keras.layers.Lambda(lambda x:tf.linalg.matmul(x,x,transpose_a=True))(output)
cross_output = tf.keras.layers.Flatten()(cross_output)
Questioner
DachuanZhao
Viewed
0
David S 2020-11-30 14:56:50

The answer I provided does have the answer, but not the immediate one!

Given the example you gave in your comment to @Meow Cat 2012:

import tensorflow as tf
import numpy as np

a = np.array([[1,2,3.0],[4,5,6.0]]
res = tf.einsum('ki,kj->kij',a,a)
print(res.shape)  # TensorShape([2, 3, 3])

tf.einsum() function will compute the outer product of two tensors.

Another solution using tf.linalg.matmul is (@DachuanZhao pointed it out):

import tensorflow as tf
import numpy as np
    
a = np.array([[1,2,3.0],[4,5,6.0]]
res = tf.linalg.matmul(tf.expand_dims(a, axis=-1),tf.expand_dims(a, axis=1))
print(res.shape)  # (2, 3, 3)