有意思的测试:
import numpy as np
a=np.array([1,2,3])
print(a.shape) #(3,) rank 3 array
print(sum(a)) #6
print(sum(a).shape) # ()
print(type(sum(a))) #<class 'numpy.int32'>
print(sum(a).dtype) #int32
b=np.array([[1,2,3]])
print(b.shape) #(1, 3)
print(sum(b)) #[1 2 3]
print(sum(b).shape) # (3,)
print(type(sum(b))) #<class 'numpy.ndarray'>
print(sum(b).dtype) #int32
查资料总结:
numpy.ndarray.shap是返回一个数组维度的元组。 (3,)与(1,3)的区别如下:
ndarray.shape:数组的维度。为一个表示数组在每个维度上大小的整数元组。例如二维数组中,表示数组的“行数”和“列数”。
ndarray.shape返回一个元组,这个元组的长度就是维度的数目,即ndim属性。
一般情况下:
[1,2,3]的shape值(3,),意思是一维数组,数组中有3个元素。
[[1,2,3]]的shape值是(1,3),意思是一个行向量(此处理解为一维数组是错误的),每行有3个元素。
关于 X.shape=(,)的问题解释:
a = np.array([[1]])
print(a)
a = np.squeeze(a) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
print('a:',a)
print(a.shape)
assert(a.shape == ())
b = np.array(1)
print('b:',b)
print(b.shape)
assert(b.shape == ())
看样子应该np.squeeze转化为数,类型仍旧是ndarray,
如果b = 1
print(b.shape),则会出错
AttributeError: 'int' object has no attribute 'shape'