如何组合不同形状的矩阵?

huangapple go评论57阅读模式
英文:

How can i combine different shape of matrix

问题

我想知道如何在torch或numpy中将不同形状的多个张量连接成一个张量。

此外,我希望将两个矩阵形状不同的部分填充为零。

我使用以下代码:

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))

但是,我得到了错误:

---------------------------------------------------------------------------
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
英文:

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)
&lt;ipython-input-395-2f74879dd1d6&gt; in &lt;module&gt;
      4 n2 = np.array(np.random.rand(1,512,7,7))
      5 
----&gt; 6 np.concatenate((n1,n2))

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

答案1

得分: 2

使用pad来填充零以匹配最大形状可能没有更直接的方法:

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

输出形状:(2, 512, 112, 112)

英文:

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)

huangapple
  • 本文由 发表于 2023年7月6日 20:15:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定