numpy:尺寸与形状

numpy: dimensions vs. shape

我有一个关于属性 shape 和 ndim 的简短问题。一个数组的维度怎么可能超过两个,而矩阵却被限制为 n x m 的形状?三维阵列是否不需要具有类似 m x n x o 形状的形状?

此致

我认为你在这里混淆了东西,np.array 可以有任意数量的维度而 np.matrix 只有两个,np.matrix 是 ndim=2 的特殊情况并且有特殊矩阵运营商。来自 np.matrix 的 NumPy 文档:

Note:
It is no longer recommended to use this class, even for linear algebra. 
Instead, use regular arrays. The class may be removed in the future.

Returns a matrix from an array-like object, or from a string of data. 
A matrix is a specialized 2-D array that retains its 2-D nature through operations.
It has certain special operators, such as * (matrix multiplication) and ** (matrix power).

另外,请注意这个例子,这样您就可以看到不同之处:

a = np.matrix([[2,2],[2,2]])
print(a**2)

这会 return:

matrix([[8, 8],
        [8, 8]])

因为 matrix "a" 平方就是这样,但是如果你对数组做同样的事情:

a = np.array([[2,2],[2,2]])
print(a**2)

会return:

array([[4, 4],
       [4, 4]])

因为它在所有元素中应用了正方形,如果您想要 np.matrix 的行为,您将不得不使用 np.dot

我认为他们可能会在未来的版本中删除 np.matrix,因为除了打扰开发人员的思想外,它没有添加任何真正有用的东西。