为什么 3D numpy 数组按原样打印(它们是如何排序的)?
Why are 3D numpy arrays printed the way they are (How are they ordered)?
我正在努力思考 3D 数组(或一般的多维数组),但这让我有点头疼。特别是打印 3D numpy 数组的方式对我来说是违反直觉的。这个问题是 similar 但更多的是关于编程语言之间的差异,我仍然没有完全理解。让我试着解释一下。
假设我想创建一个 3 行(长度)、5 列(宽度)和 2 深度的 3D 数组。所以一个 3x5x2 矩阵。
我执行以下操作:
import numpy as np
a = np.zeros(30).reshape(3, 5, 2)
对我来说,一种合乎逻辑的打印方式是这样的:
[[[0. 0. 0. 0. 0.] #We can still see three rows from top to bottom
[0. 0. 0. 0. 0.]] #We can still see five columns from left to right
[[0. 0. 0. 0. 0.] #Depth values are shown underneath each other
[0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]]
然而,当我打印这个数组时,它打印如下:
[[[0. 0.] #We can still see three rows from top to bottom,
[0. 0.] #However columns now also appear from top to bottom instead of from left to right
[0. 0.] #Depth values are now shown from left to right
[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]]]
我不明白为什么要这样打印数组。也许这只是我(也许我的空间推理在这里缺乏),或者 NumPy 数组打印成这样有什么具体原因吗?
正在将评论综合为正确答案:
首先,看一下np.zeros(10).reshape(5, 2)
。那是 5 行 2 列,而不是 2 行 5 列。前面加3就是3个5行2列的平面。您缺少的是您的新维度位于 前面 ,而不是结尾。在数学中,通常在末尾添加额外的维度(就像用 z 扩展 (x,y) 变成 (x,y,z)。但是,在计算机科学中,数组维度通常以这种方式完成。它反映了数组的方式通常以行优先顺序存储在内存中。
我正在努力思考 3D 数组(或一般的多维数组),但这让我有点头疼。特别是打印 3D numpy 数组的方式对我来说是违反直觉的。这个问题是 similar 但更多的是关于编程语言之间的差异,我仍然没有完全理解。让我试着解释一下。
假设我想创建一个 3 行(长度)、5 列(宽度)和 2 深度的 3D 数组。所以一个 3x5x2 矩阵。
我执行以下操作:
import numpy as np
a = np.zeros(30).reshape(3, 5, 2)
对我来说,一种合乎逻辑的打印方式是这样的:
[[[0. 0. 0. 0. 0.] #We can still see three rows from top to bottom
[0. 0. 0. 0. 0.]] #We can still see five columns from left to right
[[0. 0. 0. 0. 0.] #Depth values are shown underneath each other
[0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]]
然而,当我打印这个数组时,它打印如下:
[[[0. 0.] #We can still see three rows from top to bottom,
[0. 0.] #However columns now also appear from top to bottom instead of from left to right
[0. 0.] #Depth values are now shown from left to right
[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]]]
我不明白为什么要这样打印数组。也许这只是我(也许我的空间推理在这里缺乏),或者 NumPy 数组打印成这样有什么具体原因吗?
正在将评论综合为正确答案:
首先,看一下np.zeros(10).reshape(5, 2)
。那是 5 行 2 列,而不是 2 行 5 列。前面加3就是3个5行2列的平面。您缺少的是您的新维度位于 前面 ,而不是结尾。在数学中,通常在末尾添加额外的维度(就像用 z 扩展 (x,y) 变成 (x,y,z)。但是,在计算机科学中,数组维度通常以这种方式完成。它反映了数组的方式通常以行优先顺序存储在内存中。