英文:
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)
<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
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论