如何实现torch.arange的tensor版本

文章目录

背景

python 复制代码
import torch

我们都知道,torch.arange只支持数字,不支持tensor,如下:

python 复制代码
torch.arange(0,5,1)

tensor(0, 1, 2, 3, 4)

但是如果使用tensor,就会报错:

python 复制代码
torch.arange(torch.tensor([0]),torch.tensor([5]),torch.tensor([1]))

可问题是,我们有如下场景怎么办:

python 复制代码
torch.arange(torch.tensor([0,2]),torch.tensor([5,7]),torch.tensor([1,1]))

也就是说,我们希望

python 复制代码
torch.arange(0,5,1)和torch.arange(2,7,1)

并行做,难道就不行吗?

实现方案

上面这种并行是可以做到的,如下:

python 复制代码
x=torch.arange(0,5,1).reshape(1,-1)
a=torch.tensor([0,2])
a=a.reshape(-1,1)
x=a+x
x

tensor(\[0, 1, 2, 3, 4,

2, 3, 4, 5, 6])

不可行的情况

细心的人可以发现,上面是具有特殊性的,

python 复制代码
torch.arange(torch.tensor([0,2]),torch.tensor([5,7]),torch.tensor([1,1]))

python 复制代码
torch.tensor([0,2])+5=torch.tensor([5,7])

且步长是一样的:

python 复制代码
torch.tensor([1,1])#步长都是1

为什么必须这样呢?因为这样才可以保证,输出的结果的维度是一样的。比如你换一个:

python 复制代码
torch.arange(torch.tensor([0,2]),torch.tensor([5,7]),torch.tensor([1,2]))

步长一个是1,一个是2,这样肯定不行,两个arange输出的维度不同,就肯定不可能并行。再比如:

python 复制代码
torch.arange(torch.tensor([0,2]),torch.tensor([5,9]),torch.tensor([1,1]))

步长是一样了,但是5-0=5,9-2=7(end-start),最终arange输出的维度还是会不同,无法并行。

相关推荐
回眸&啤酒鸭2 天前
【回眸】Minicart 电商购物车核心功能落地指南
人工智能
一隅论数智2 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
AI的探索之旅2 天前
97 个 OpenCV 实例(三十):双目立体,从标定到点云
人工智能·opencv·计算机视觉
AlbertZein2 天前
Step-5-Preview 上手实测:3D 游戏、金融分析、网页设计一次跑完
人工智能·aigc
LaughingZhu2 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
美狐美颜SDK开放平台2 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk