Home > OS >  Matrix operation to switch last shape of tensor in keras
Matrix operation to switch last shape of tensor in keras

Time:06-05

Is there any method to output like this?

x = (30, 64, 36, 1)
y = (30, 64, 36, 2048)

Is there some operation that can make the output of shape (30, 64, 2048, 1) with x and y

CodePudding user response:

If I Understand Correctly (IIUC) you want this:

enter image description here

You can use einsum in numpy or tensorflow like below:

Numpy Version

import numpy as np
x = np.random.rand(30, 64, 36, 1)
y = np.random.rand(30, 64, 36, 2048)
z = np.einsum('ijkl,ijkm->ijml', x, y)
# output[i,j,m,l] = sum_k x[i,j,k,l] * y[i,j,k,m]
print(z.shape)

Tensorflow Version

import tensorflow as tf
x = tf.random.normal(shape=[30, 64, 36, 1])
y = tf.random.normal(shape=[30, 64, 36, 2048])
z = tf.einsum('ijkl,ijkm->ijml', x, y)
# output[i,j,m,l] = sum_k x[i,j,k,l] * y[i,j,k,m]
print(z.shape)

Output:

(30, 64, 2048, 1)
  • Related