shape函数是Numpy中的函数,它的功能是读取矩阵的长度,比如shape[0]就是读取矩阵第一维度的长度。
直接用.shape可以快速读取矩阵的形状,使用shape[0]读取矩阵第一维度的长度。
.shape的使用方法
1 2 3 | >>> import numpy as np >>> x = np.array([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) >>> print (x.shape) |
1 | (2, 3) |
shape[0]的使用方法
1 2 3 4 | >>> import numpy as np >>> x = np.array([[ 1 , 2 , 3 ],[ 4 , 5 , 6 ]]) >>> print (x.shape[ 0 ]) 2 |
其实,我们可以发现:
1 2 | >>> print ( len (x)) 2 |
shape[0]读取矩阵第一维度的长度,即数组的行数。
shape[1]的使用方法
1 2 | >>> print (x.shape[ 1 ]) 3 |
是我们的数组的列数。
有时我们会遇到一种新的表示方法:shape[-1]
首先需要知道,对于二维张量,shape[0]代表行数,shape[1]代表列数,同理三维张量还有shape[2]
对于图像来说:
image.shape[0]——图片高
image.shape[1]——图片长
image.shape[2]——图片通道数
而对于矩阵来说:
shape[0]:表示矩阵的行数
shape[1]:表示矩阵的列数
一般来说,-1代表最后一个,所以shape[-1]代表最后一个维度,如在二维张量里,shape[-1]表示列数,注意,即使是一维行向量,shape[-1]表示行向量的元素总数,换言之也是列数:
我们还是举上面的例子:
1 2 | >>> print (x.shape[ - 1 ]) 3 |
就是求得的列数。
python中shape[0]与shape[1]
1 2 3 4 5 6 7 | import numpy as np k = np.matrix([[ 1 , 2 , 3 , 4 ], [ 5 , 6 , 7 , 8 ], [ 9 , 10 , 11 , 12 ]]) print (np.shape(k)) # 输出(3,4)表示矩阵为3行4列 print (k.shape[ 0 ]) # shape[0]输出3,为矩阵的行数 print (k.shape[ 1 ]) # 同理shape[1]输出列数 |
到此这篇关于Python中的shape[0]、shape[1]和shape[-1]使用方法的文章就介绍到这了,更多相关Python shape使用内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!