Search code examples
numpytorch

How can i combine different shape of matrix


I am wondering how should i concatenate multiple tensors with different shapes into one tensor in torch or numpy.

Also, I want to fill the part where the shape of the two matrices is different with zero

i use this code

import numpy as np

n1 = np.array(np.random.rand(1,64,112,112))
n2 = np.array(np.random.rand(1,512,7,7))

np.concatenate((n1,n2))

but, i got error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-395-2f74879dd1d6> in <module>
      4 n2 = np.array(np.random.rand(1,512,7,7))
      5 
----> 6 np.concatenate((n1,n2))

ValueError: all the input array dimensions except for the concatenation axis must match exactly

Solution

  • Not sure if there is a more straightforward way, but using pad to fill with zeros to match the maximum shape:

    import numpy as np
    from itertools import zip_longest
    
    n1 = np.array(np.random.rand(1,64,112,112))
    n2 = np.array(np.random.rand(1,512,7,7))
    
    arrays = [n1, n2]
    
    shapes = [n.shape for n in arrays] 
    
    final = np.vstack(shapes).max(axis=0)
    
    out = np.concatenate([np.pad(a, list(zip_longest([0], final-a.shape,
                                                     fillvalue=0)))
                          for a in arrays])
    
    out.shape
    

    Output shape: (2, 512, 112, 112)