本文深入解析了PyTorch中Tensor的维度处理方式,涵盖了Tensor创建时size参数的用法,以及torch.Tensor.sum()和torch.Tensor.softmax()等方法中axis参数的行为。通过详细的示例和解释,帮助读者理解PyTorch Tensor在维度上的操作逻辑,从而更有效地利用PyTorch进行深度学习模型的开发和训练。
在 PyTorch 中创建 Tensor 时,size 参数用于指定 Tensor 的形状。size 参数接受一个元组,元组中的每个元素代表一个维度的大小。需要注意的是,size 参数指定维度时,是从最后一个元素到第一个元素,即最后一个元素代表列数,倒数第二个元素代表行数,以此类推。
import torch # 可以简写: tensor1 = torch.ones((2, 3)) tensor2 = torch.ones(2, 3) # 不能简写: tensor3 = torch.randint(10, (2, 3)) print(tensor1.shape) # 输出: torch.Size([2, 3]) print(tensor2.shape) # 输出: torch.Size([2, 3]) print(tensor3.shape) # 输出: torch.Size([2, 3])
以下是一些 size 参数的示例及其对应的 Tensor 描述:
pytorch.Tensor 类中的许多方法需要一个 axis 参数(通常为 int 或 list of int)。该参数指定了操作沿哪个轴进行。对于由 1 组成的 Tensor(使用 torch.ones(size) 创建),torch.sum(axis=axis) 操作的行为如下:
size | axis | output shape | output |
---|---|---|---|
(2,) | -1 或 0 | [] | tensor(2.) |
(2,1) | -1 或 1 | [2] | tensor([1., 1.]) |
(1,2) | -1 或 1 | [1] | tensor([2.]) |
(3,2) | -1 或 1 | [3] | tensor([2., 2., 2.]) |
(4,3,2) | -1 或 2 | [4,3] | tensor([[2., 2., 2.],[2., 2., 2.],[2., 2., 2.],[2., 2., 2.]]) |
从上表可以看出,torch.sum(axis=-1) 总是执行以下两项操作:
对于 axis 参数的其他指定,行为类似。
在 Tensor 变换中,原始 Tensor 的形状被保留,但其值被更改。以 torch.softmax() 为例:softmax 变换这些值,使其总和等于 1。softmax transforms the values so that their sum equals one。dim 参数允许你选择沿哪个轴的元素总和等于 1:
import torch # 对于 dim=-1,沿列的总和等于 1: tensor4 = torch.randn((2, 2, 2)).softmax(dim=-1) print(tensor4) # 对于 dim=-2,沿行的总和等于 1: tensor5 = torch.randn((2, 2, 2)).softmax(dim=-2) print(tensor5)
注意事项:
总结:
本文详细介绍了 PyTorch 中 Tensor 的维度处理方式,包括 Tensor 的创建、聚合和变换。通过学习本文,你应该能够更好地理解 PyTorch Tensor 在维度上的操作逻辑,从而更有效地利用 PyTorch 进行深度学习模型的开发和训练。
以上就是PyTorch Tensor维度处理详解:创建、聚合与变换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号