shape函数是numpy.core.fromnumeric中的函数,它的功能是读取矩阵的维度。
例:
shape(matrixA) 返回matrixA的(行数,列数)元组
shape(matrixA) [0] ==》 行数
shape(matrixA) [1] ==》 列数
shape的输入参数可以使一个实数,一个一维列表(数组),二维数组,也可以是一个矩阵。
实例:
>>> np.shape(1) #实数
()
>>> np.shape([1,2,3]) #一维数组(列表)
(3,)
>>> alist2 = [[1,2],[3,4],[5,6]]
>>> np.shape(alist2) #二维列表
(3, 2)
>>> arr2 = np.array(alist2)
>>> np.shape(arr2)#二维数组
(3, 2)
>>> ma2 = np.mat(alist2)
>>> ma2
matrix([[1, 2],
[3, 4],
[5, 6]])
>>> np.shape(ma2)#二维矩阵
(3, 2)
>>> ml = np.shape(ma2)[0]#获取一维参数(行数)
>>> ml
3
>>> ml2 = np.shape(ma2)[1]
>>> ml2
2
>>> em = np.eye(ml)#构造对角矩阵(实际上是二维数组)
>>> em
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> em.shape()
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
em.shape()
TypeError: 'tuple' object is not callable
>>> em.shape
(3, 3)
>>> em.shape[0] #获取一维参数
3