1

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)
DachuanZhao
  • 1,181
  • 3
  • 15
  • 34

2 Answers2

1

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)
David
  • 8,113
  • 2
  • 17
  • 36
0

Already answered: https://stackoverflow.com/a/51323886/9399618

According to the documentation:

Additionally outer product is supported by passing axes=0

Tested as follow:

a = np.array([1,2,3,4,5,6,7,8,9,10.0])
tf.tensordot(a, a, axes=0)
# Got <tf.Tensor: shape=(10, 10), dtype=float64, numpy=xxx>
Meow Cat 2012
  • 928
  • 1
  • 9
  • 21