假设我有以下数组A-
import numpy as np
batch_size, seq_len = 3, 5
A = np.zeros((batch_size, seq_len))
A[0,0:] = 1
A[1,0:] = 2
A[2,0:] = 3
A具有以下值-
array([[1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2.],
[3., 3., 3., 3., 3.]])
现在,如果我以以下方式重塑它-
A4 = A.reshape(seq_len, -1)
array([[1., 1., 1.],
[1., 1., 2.],
[2., 2., 2.],
[2., 3., 3.],
[3., 3., 3.]])
然而,我原以为是
array([[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.]])
这篇很棒的博客文章引起了我对这个问题的关注https://discuss.pytorch.org/t/for-beginners-do-not-use-view-or-reshape-to-swap-dimensions-of-tensors/75524
来自np.reshape
文档
您可以将整形视为首先遍历数组(使用给定的索引顺序(,然后使用与遍历相同的索引顺序将已遍历数组中的元素插入到新数组中。
a4
是(5,3(,元素的顺序与[1,1,1,1,1,2,2,...]
相同