0
import numpy as np

a = np.zeros((5,2,3,4), dtype=np.int16)
print a.ndim

b = np.zeros((2,3,4), dtype=np.int16)
print b.ndim

以上是我的代码。输出是:

4
3

我已经从[这里](http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-c5f4ceae0ab4b1313de41aba9104d0d7648e35cc)检查了页面

我预计 a.dim = 2 或 3,但它是 4。为什么?

你能给我一些提示吗?谢谢

4

2 回答 2

7

您提供的元组zeros和其他类似函数给出了数组的“形状”(并且可用于任何数组a.shape)。维度数是该形状中的条目数。

如果您改为打印len(a.shape)并且len(b.shape)您会期望得到的结果。Thendim总是等于这个(因为它是这样定义的)。

您提供的链接显示了相同的行为,除了该reshape方法采用任意数量的位置参数而不是元组。但在本教程的示例中:

>>> a = arange(15).reshape(3, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2

提供给 的参数reshape数量以及由 提供的元组中的元素数量a.shape为 2。如果改为:

>>> a = np.arange(30).reshape(3, 5, 2)
>>> a.ndim
3

然后我们看到相同的行为:这ndim是我们给 numpy 的形状条目的数量。

于 2013-06-08T09:10:03.983 回答
1

zero给出一个由您指定的维度的零数组:

>>> b = np.zeros((2,3,4), dtype=np.int16)  
>>> b 
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]]], dtype=int16)

因为b你给了三个维度,但a你给了四个。算上开口[

>>> a = np.zeros((5,2,3,4), dtype=np.int16)
>>> a 
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]]],


...

shape 回显您指定的尺寸:

>>> a.shape
(5, 2, 3, 4)

>>> b.shape
(2, 3, 4)
于 2013-06-08T09:09:37.997 回答