前言
shape函数是Numpy中的函数,它的功能是读取矩阵的长度,比如shape[0]就是读取矩阵第一维度的长度。
直接用.shape可以快速读取矩阵的形状,使用shape[0]读取矩阵第一维度的长度。
.shape的使用方法
>>> import numpy as np
>>> x=np.array([[1,2,3],[4,5,6]])
>>> print(x.shape)
(2, 3)
shape[0]的使用方法
>>> import numpy as np
>>> x=np.array([[1,2,3],[4,5,6]])
>>> print(x.shape[0])
2
其实,我们可以发现:
>>> print(len(x))
2
shape[0]读取矩阵第一维度的长度,即数组的行数。
shape[1]的使用方法
>>> 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]表示行向量的元素总数,换言之也是列数:
我们还是举上面的例子:
>>> print(x.shape[-1])
3
就是求得的列数。
附:需要注意的小细节
然后就是,需要注意turple,list等没有shape属性,需要替换成张量tensor
注意,即使是三维,由于shape[0]表示向量数,所以shape[1]是行数,那么shape[2]还是列数,所以shape[-1]最后一维还是列数
import torch
x = torch.tensor([[2, 3, 4, 3, 6, 8],
[1, 8, 9, 5, 0, 1],
[2, 0, 2, 2, 7, 1]])
print(x.shape[-1])
输出是:6
6
Process finished with exit code 0
来源:https://blog.csdn.net/wzk4869/article/details/126022909
标签:shape[0],shape[1],shape[-1]
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python通配符之glob模块的使用详解
2021-07-16 23:13:18
Python调用adb命令实现对多台设备同时进行reboot的方法
2022-08-06 02:40:45
机器深度学习二分类电影的情感问题
2022-07-17 06:13:28
![](https://img.aspxhome.com/file/2023/1/72851_0s.png)
Python首次安装后运行报错(0xc000007b)的解决方法
2023-12-15 12:33:49
![](https://img.aspxhome.com/file/2023/7/103157_0s.png)
Python中的hypot()方法使用简介
2021-06-02 03:44:37
Selenium+BeautifulSoup+json获取Script标签内的json数据
2023-06-17 09:30:18
重新认识视觉设计
2009-09-08 12:46:00
Python中的字典及其使用方法
2022-03-22 13:31:49
![](https://img.aspxhome.com/file/2023/3/93673_0s.png)
python3中编码获取网页的实例方法
2023-07-17 23:31:47
![](https://img.aspxhome.com/file/2023/1/75931_0s.png)
鼠标驱动图片变化
2009-07-26 10:03:00
Gradio机器学习模型快速部署工具quickstart
2023-06-30 01:09:52
![](https://img.aspxhome.com/file/2023/5/62545_0s.png)
centos6.4下python3.6.1安装教程
2021-11-03 05:44:03
![](https://img.aspxhome.com/file/2023/3/88983_0s.png)
美图秀秀web开放平台--PHP流式上传和表单上传示例分享
2023-11-15 08:34:42
MySQL两种识别是否有中文字符的方法
2011-01-04 20:11:00
Python程序设计入门(5)类的使用简介
2023-01-21 06:27:56
python读写修改Excel之xlrd&xlwt&xlutils
2022-04-03 16:35:43
![](https://img.aspxhome.com/file/2023/9/94149_0s.jpg)
python 边缘扩充方式的实现示例
2021-03-30 23:28:17
![](https://img.aspxhome.com/file/2023/4/115514_0s.jpg)
pycharm最新免费激活码至2099年(21.3.18亲测可用)
2023-10-02 09:53:20
![](https://img.aspxhome.com/file/2023/5/90685_0s.png)
PHP面向接口编程 耦合设计模式 简单范例
2023-10-24 09:18:27
Python光学仿真之对光的干涉理解学习
2021-05-24 04:47:52
![](https://img.aspxhome.com/file/2023/6/110406_0s.png)