PyTorch中Torch.arange()函数详解

函数原型

arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor

用法

返回大小为的一维张量 ,其值介于区间 为步长等间隔取值

参数说明

参数 类型 说明
start Number 起始值,默认值:0
end Number 结束值
step Number 步长,默认值:1

关键字参数

关键字参数 类型 说明
out Tensor 输出张量
dtype torch.dtype 期望的返回张量的数据类型。默认值:如果是None,则使用全局默认值。如果未给出 dtype,则从其他输入参数推断数据类型。如果 start、end 或 stop 中的任何一个是浮点数,则 dtype被推断为默认值,参见 get_default_dtype()。否则,dtype 被推断为 torch.int64
layout torch.layout 返回张量的期望 layout。默认值:torch.strided
device torch.device 返回张量的期望设备。默认值:如果是None,则使用当前设备作为默认张量类型,参见torch.set_default_tensor_type()。对于 CPU 类型的张量,则 device 是 CPU ,若是 CUDA 类型的张量,则 device 是当前的 CUDA 设备
requires_grad bool autograd 是否记录返回张量上所作的操作。默认值:False

代码示例

python 复制代码
>>> torch.arange(5)  # 默认以 0 为起点
tensor([ 0,  1,  2,  3,  4])
>>> torch.arange(1, 4)  # 默认间隔为 1
tensor([ 1,  2,  3])
>>> torch.arange(1, 2.5, 0.5)  # 指定间隔 0.5
tensor([ 1.0000,  1.5000,  2.0000])

pyTorch中torch.range()和torch.arange()的区别

python 复制代码
x = torch.range(-8, 8)
y = torch.arange(-8, 8)
print(x, x.dtype)
print(y, y.dtype)

输出

tensor(-8., -7., -6., -5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.,6., 7., 8.) torch.float32

   tensor(-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7) torch.int64

可以看到,torch.range()的范围是-8, 8,类型为torch.float32

torch.arange()的范围是[-8, 8),类型为torch.int64

在梯度设置时会出现错误:

python 复制代码
x = torch.range(-8, 8, 1, requires_grad=True)
y = torch.arange(-8, 8, 1, requires_grad=True)
print(x, x.dtype)
print(y, y.dtype)

即只有当类型为float时才可设置requires_grad=True,故可将

y ``= torch.arange(``-``8``, ``8``, ``1``, requires_grad``=``True``)

改为以下,即手动改变数据类型即可。

y ``= torch.arange(``-``8.0``, ``8.0``, ``1.0``, requires_grad``=``True``)

输出

tensor(-8., -7., -6., -5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.,6., 7., 8., requires_grad=True)

   torch.float32

   tensor(-8., -7., -6., -5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.,6., 7., requires_grad=True)

   torch.float32

相关推荐
郝学胜-神的一滴14 分钟前
Effective Python 条款45:巧用属性注解平滑升级类属性
运维·开发语言·数据库·python·网络协议·numpy
小和尚同志30 分钟前
我也来试试已经 202k star 的 Ponytail 马尾辫
人工智能·aigc·ai编程
AAA修煤气灶刘哥31 分钟前
11 月编程 Agent 排名:Arena 第一是 Claude,而另一张榜第一是 Gemini
人工智能·llm·agent
不得了zz34 分钟前
11-Agent 可观测与评估:Spring AI Alibaba Admin Studio 到底解决了什么
java·人工智能·后端·spring·ai编程·springaialibaba
掘金安东尼35 分钟前
智能体运行框架图解:Pi、OpenCode、Hermes 和 OpenClaw
人工智能·开源·agent
iiiiii111 小时前
从最大熵到 SAC:Soft Q-Learning 与 Soft Actor-Critic 公式推导笔记
人工智能·笔记·算法·机器学习·强化学习
JonaHu1 小时前
GPT Image 2.6 商品换台面不悬浮:倒影、接触阴影与材质验收
图像处理·人工智能·aigc
神一样的老师2 小时前
WS63 BLE 配网实战:用 Python 在 PC 上替代手机完成 WiFi 配网
开发语言·python·智能手机
AI创界者2 小时前
2026 全平台 AI 视频换脸工作流实战:一套方案打通 N 卡、A 卡、I 卡与 Win / Mac
人工智能·python·aigc·音视频
always20222 小时前
AI运行时 · 附录3 - GPU 设备插件与 MIG:K8s 上的 AI 加速器编排
人工智能·容器·kubernetes