[英]Numpy ndarray shape with 3 parameters
I am confused about what is the shape of ndarray when 3 parameters are provided: 当提供3个参数时,我对ndarray的形状感到困惑:
For example, what is the difference between: 例如,有什么区别:
np.zeros((2, 1, 3))
array([[[ 0., 0., 0.]],
[[ 0., 0., 0.]]])
and: 和:
np.zeros((1, 2, 3))
array([[[ 0., 0., 0.],
[ 0., 0., 0.]]])
It seems to me that both of them represent 2*3 matrices. 在我看来,它们都代表2 * 3矩阵。
No, the shapes are different, you have to pay attention to the square brackets : 不,形状不同,你必须注意方括号 :
>>> np.zeros((2, 1, 3))
array([
[[ 0., 0., 0.]
],
[[ 0., 0., 0.]
]])
versus: 与:
>>> np.zeros((1, 2, 3))
array([
[[ 0., 0., 0.],
[ 0., 0., 0.]
]])
as you can see, in the first call, we have two times a pair of square brackets for the second dimension, whereas in the latter, we only have one such pair. 正如你所看到的,在第一次调用中,我们有两次方括号用于第二个维度,而在后者中,我们只有一个这样的对。
The shape is also different: 形状也不同:
>>> np.zeros((2, 1, 3)).shape
(2, 1, 3)
>>> np.zeros((1, 2, 3)).shape
(1, 2, 3)
So in the former we have a list that contains two sublists. 所以在前者中我们有一个包含两个子列表的列表。 Each of these sublists contains one element: a list of three elements.
这些子列表中的每一个都包含一个元素:三个元素的列表。 In the latter we have a list with one element: a sublist with two elements, and these two elements are lists with three elements.
在后者中,我们有一个包含一个元素的列表:一个包含两个元素的子列表,这两个元素是包含三个元素的列表。
So a vanilla Python list equivalent would be: 所以一个类似于vanilla的Python列表将是:
[ [ [0, 0, 0] ], [ [0, 0, 0] ] ]
versus: 与:
[ [ [0, 0, 0], [0, 0, 0] ] ]
dim=1 is just a dumb dimension, you can alway regard a matrix of 2x3
as a tensor of 1x2x3
. dim = 1只是一个愚蠢的维度,你总是可以将
2x3
矩阵视为1x2x3
的张量。
However, they are technically not the same thing. 但是,它们在技术上并不是一回事。 So you can see the bracket
[]
in your 2 output is not exactly the same, the place of []
for the dumb dimension is not at the same position. 因此,您可以看到2输出中的括号
[]
不完全相同,哑维度的[]
位置不在同一位置。
For removing dumb dimension, use 要删除哑尺寸,请使用
arr = np.squeeze(arr)
As per numpy.zeros
documentation , the first argument is a sequence or int representing the shape of the array. 根据
numpy.zeros
文档 ,第一个参数是表示数组形状的序列或int。
If you look closely the nested square brackets differ in line with the shapes you've built. 如果仔细观察,嵌套的方括号与您构建的形状不一致。
This example might make it clearer: 这个例子可能会更清楚:
np.zeros((2, 3, 4))
array([[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]],
[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.