
张量的属性
描述Pytorch张量有3个属性:
- 形状 (即维度)
- 数据类型
- 执行设备 (GPU或CPU)
代码 | 作用 |
---|---|
torch.Tensor.shape | 返回张量的形状 (即维度) |
torch.Tensor.dtype | 返回张量的数据类型 |
torch.Tensor.device | 返回张量运行所在的设备 (GPU或CPU) |
举个栗子:
import torch
tensor = torch.rand(2, 3) # 创建张量
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device of tensor: {tensor.device}")
输出:
Shape of tensor: torch.Size([2, 3])
Datatype of tensor: torch.float32
Device of tensor: cpu