提问人:Samvel Safaryan 提问时间:10/22/2023 最后编辑:Samvel Safaryan 更新时间:10/23/2023 访问量:43
如何沿轴连接张量的内部矩阵?
How to you concat inner matrixes of tensor along axis?
问:
让我们有一个形状为 $n\times d\times h\times w\times p\times p$ 的张量,我们想连接形状为 $p\time p$ 的 innet 矩阵,这样我们就制作了一个形状为 $n\times d\times ph\times pw$ 的矩阵。我该怎么做?
array([[[[[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]],
[[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]],
[[27, 28, 29],
[30, 31, 32],
[33, 34, 35]]]]]])
康卡特之后
array([[[[0, 1, 2, 9, 10, 11],
[3, 4, 5, 12, 13, 14],
[6, 7, 8, 15, 16, 17],
[18, 19, 20, 27, 28, 29],
[21, 22, 23, 30, 31, 32],
[24, 25, 26, 33, 34, 35]]]])
我用reshape做了很多实验,但没有成功。我的一个实验
a.reshape(n, d, p*h, p*w)
我可以使用 for 循环来做到这一点,但我认为如果没有这个,这也是可能的。 请帮帮我。 使用 for 循环的代码
p = 3
arr = np.arange(1*1*2*2*p*p).reshape(1, 1, 2, 2, p, p)
answer = np.zeros(shape=(1, 1, 2*p, 2*p))
for (n, d, h, w) in np.ndindex(*arr.shape[:4]):
answer[n, d, h:h+p, w:w+p] = arr[n, d, h, w]
答:
1赞
hpaulj
10/23/2023
#1
In [15]: arr=np.arange(0,36).reshape(2,2,3,3)
reshape
无法对数组的元素重新排序。我从 [0,1,... 开始35],并保留:reshape
In [18]: arr.reshape(2,3,6)
Out[18]:
array([[[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]],
[[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]]])
我们必须以某种方式对元素进行重新排序,将 [9,10,11] 块与 [0,1,2] 相邻。 就是这样一种工具:transpose
In [19]: arr.transpose(0,2,1,3)
Out[19]:
array([[[[ 0, 1, 2],
[ 9, 10, 11]],
[[ 3, 4, 5],
[12, 13, 14]],
[[ 6, 7, 8],
[15, 16, 17]]],
[[[18, 19, 20],
[27, 28, 29]],
[[21, 22, 23],
[30, 31, 32]],
[[24, 25, 26],
[33, 34, 35]]]])
In [20]: arr.transpose(0,2,1,3).reshape(6,6)
Out[20]:
array([[ 0, 1, 2, 9, 10, 11],
[ 3, 4, 5, 12, 13, 14],
[ 6, 7, 8, 15, 16, 17],
[18, 19, 20, 27, 28, 29],
[21, 22, 23, 30, 31, 32],
[24, 25, 26, 33, 34, 35]])
要通过分配给“空白”来做同样的事情,我们需要类似的东西:
In [32]: res=np.zeros((6,6),int)
In [33]: res[:,:3] = arr[:,::2,:].reshape(6,3)
In [34]: res
Out[34]:
array([[ 0, 1, 2, 0, 0, 0],
[ 3, 4, 5, 0, 0, 0],
[ 6, 7, 8, 0, 0, 0],
[18, 19, 20, 0, 0, 0],
[21, 22, 23, 0, 0, 0],
[24, 25, 26, 0, 0, 0]])
In [35]: res[:,3:] = arr[:,1::2,:].reshape(6,3)
In [36]: res
Out[36]:
array([[ 0, 1, 2, 9, 10, 11],
[ 3, 4, 5, 12, 13, 14],
[ 6, 7, 8, 15, 16, 17],
[18, 19, 20, 27, 28, 29],
[21, 22, 23, 30, 31, 32],
[24, 25, 26, 33, 34, 35]])
同一块连接的串联版本:
In [41]: np.concatenate((arr[:,::2], arr[:,1::2]), axis=3)
Out[41]:
array([[[[ 0, 1, 2, 9, 10, 11],
[ 3, 4, 5, 12, 13, 14],
[ 6, 7, 8, 15, 16, 17]]],
[[[18, 19, 20, 27, 28, 29],
[21, 22, 23, 30, 31, 32],
[24, 25, 26, 33, 34, 35]]]])
上一个:NumPy 重塑不做功能
评论
You can think of reshaping as first raveling the array...
ravel
3x3
5x5
p=3
answer = np.zeros(shape=(1, 1, 2*p, 2*p))