在循环计算或者对张量进行索引时,经常需要创建一段连续的整型或浮点型的序列张量。PyTorch 提供了一些能够创建序列张量的方法。
创建整型序列:
(
为向上取整,返回大于或者等于表达式的最小整数) 的 1D 张量,张量的元素值为在 [start, end) 之间,步长为 step 的整型序列,不包含 end 本身;
(
为向下取整,返回小于或者等于表达式的最大整数) 的 1D 张量,张量的元素值为在 [start, end] 之间,步长为 step 的整型序列,包含 end 本身;
使用 torch.range() 函数会出现 Warning 警告:未来的 Pytorch 版本会将 torch.range() 函数丢弃。因为 torch.range() 函数和 Python 的内建函数 range 行为不一致,Python 中的 range 函数生成的整数序列范围为 [start, end) (包左不包右,Python中习惯使用包左不包右的规范),而 torch.range() 函数生成的整数序列范围为 [start, end] (包左包右)。
torch.arange() 函数和 torch.range() 函数功能相似。「如果想要创建整型序列,推荐使用 torch.arange() 函数。」
>>> import torch
>>> # 创建元素值为范围[0, 10)步长为1的1D整数序列张量
>>> a = torch.arange(0, 10)
>>> print(a)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> # 创建元素值为范围[1, 10)步长为2的1D整数序列张量
>>> b = torch.arange(1, 10, 2)
>>> print(b)
tensor([1, 3, 5, 7, 9])
>>> # 使用torch.range()函数创建元素值为范围[0, 10)步长为1的1D整数序列张量
>>> c = torch.range(0, 10)
>>> print(c)
tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
/home/chenkc/code/create_tensor.py:298: UserWarning: torch.range is deprecated in favor of torch.arange and will be removed in 0.5. Note that arange generates values in [start; end), not [start; end].
c = torch.range(0, 10)
对于张量 b 来说,由于
,因此最终张量 b 为长度为 5 的 1D 张量。
创建浮点型序列:
;
之间均匀间隔的 steps 个点。序列张量的值为
;
>>> import torch
>>> # 创建元素值为范围[0, 10]之间均匀间隔的5个值的1D浮点型序列张量
>>> a = torch.linspace(0., 10., 5)
>>> print(a)
tensor([ 0.0000, 2.5000, 5.0000, 7.5000, 10.0000])
>>> # 创建元素值为范围[10^0, 10^10]之间均匀间隔的5个值的1D浮点型序列张量
>>> b = torch.logspace(0., 10., 5)
>>> print(b)
tensor([1.0000e+00, 3.1623e+02, 1.0000e+05, 3.1623e+07, 1.0000e+10])