如何实现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输出的维度还是会不同,无法并行。

相关推荐
iNeuOS工业互联网1 分钟前
多模态知识库,打通文本、图像与视频资源的协同实践与应用
人工智能·python·音视频
一晌小贪欢2 分钟前
python-第20天:关键字参数与不定长参数
java·开发语言·前端·python·数据可视化·函数参数·python办公
Metaphor6925 分钟前
如何在 Python 环境中裁剪 PDF 页面
python·pdf
半亩码田11 分钟前
C#转Python第4.4篇:JSON 处理:json 模块 vs System.Text.Json
python·c#·json
Geek-Chow18 分钟前
MCP 模型上下文协议:四、概念地图 · 八个概念与五个组件
人工智能·大语言模型·mcp
Hotchip_MEMS20 分钟前
MS2202AB-M15E输出驱动能力:直连MCU GPIO无需三极管
人工智能·笔记·物联网·电脑·制造
SelectDB技术团队20 分钟前
统一全文检索与 SQL 分析:Apache Doris 日志分析实践
大数据·数据结构·后端·python·全文检索·doris·日志分析
向哆哆23 分钟前
PCB电子元器件目标检测数据集:23类别 | 目标检测
人工智能·目标检测·计算机视觉
心中有你021429 分钟前
Python爬虫实战:京东商品数据爬取+可视化分析
开发语言·爬虫·python
陈彬深大37 分钟前
《AI 渐进编程》之二十九:从面向对象到 Harness——封装 AI 的不确定性
人工智能·软件工程