dim,shape,size,numel
1. torch.Tensor.dim
dim的作用是返回张量的维数
import torch
a = torch.rand((3,4)) #生成随机数
a.dim()
2.torch.Tensor.shape
shape的作用是返回张量的形状
import torch
a = torch.rand((3,4))
a.shape
3.torch.Tensor.size
shape的作用是返回张量的形状,可指定dim返回某一维度的大小
import torch
a = torch.rand((2,3,4))
print(a.size())
print(a.size(dim=0)) #维度的指标是从0开始
print(a.size(dim=2))
4.torch.Tensor.numel
numel的作用是返回张量中元素的数量
import torch
a = torch.rand((2,3,4))
print(a.numel()) #2×3×4=24
#除此之外还可以使用torch.numel()
print(torch.numel(a))
总结
上述几种方法在实践中会经常使用,查看张量的维度等
*Note,带括号和不带括号的区别在于,不带括号说明它是一个属性,而带括号说明它是一个方法。