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)
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)
Yes , I have found anther solution :
tf.linalg.matmul(tf.expand_dims(a, axis=-1),tf.expand_dims(a, axis=1))
@DachuanZhao Cool, happy you managed. I will add this solution to my answer for future users