有效地堆叠阵列/火炬张量的副本?

编程入门 行业动态 更新时间:2024-10-11 23:26:37
本文介绍了有效地堆叠阵列/火炬张量的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是Python/Pytorch用户.首先,在numpy中,假设我有一个大小为LxL的数组M,我想要以下内容 数组:A =(M,...,M)的大小,例如NxLxL,是否有比:/p>更优雅/更有效的内存存储方式?

I'm a Python/Pytorch user. First, in numpy, let's say I have an array M of size LxL, and i want to have the following array: A=(M,...,M) of size, say, NxLxL, is there a more elegant/memory efficient way of doing it than :

A=np.array([M]*N) ?

与火炬张量相同的问题! 原因,现在,如果M是一个变量(torch.tensor),我必须这样做:

Same question with torch tensor ! Cause, Now, if M is a Variable(torch.tensor), i have to do:

A=torch.autograd.Variable(torch.tensor(np.array([M]*N)))

太丑了!

推荐答案

请注意,您需要确定是否要为扩展数组分配新的内存,还是只需要对内存的现有内存进行新的查看.原始数组.

Note, that you need to decide whether you would like to allocate new memory for your expanded array or whether you simply require a new view of the existing memory of the original array.

在PyTorch中,这种区别产生了两种方法expand()和repeat().前者仅在现有张量上创建一个新视图,其中通过将步幅设置为0将大小为1的维扩展为更大的大小.大小为1的任何维都可以扩展为任意值,而无需分配新的内存.相反,后者复制原始数据并分配新的内存.

In PyTorch, this distinction gives rise to the two methods expand() and repeat(). The former only creates a new view on the existing tensor where a dimension of size one is expanded to a larger size by setting the stride to 0. Any dimension of size 1 can be expanded to an arbitrary value without allocating new memory. In contrast, the latter copies the original data and allocates new memory.

在PyTorch中,您可以按如下方式使用expand()和repeat():

In PyTorch, you can use expand() and repeat() as follows for your purposes:

import torch L = 10 N = 20 A = torch.randn(L,L) A.expand(N, L, L) # specifies new size A.repeat(N,1,1) # specifies number of copies

在Numpy中,有多种方法可以更优雅,更有效地实现您的上述目的.对于您的特定目的,我建议在np.repeat()之前推荐np.tile(),因为np.repeat()被设计为对数组的特定元素进行操作,而np.tile()被设计为对整个数组进行操作.因此,

In Numpy, there are a multitude of ways to achieve what you did above in a more elegant and efficient manner. For your particular purpose, I would recommend np.tile() over np.repeat(), since np.repeat() is designed to operate on the particular elements of an array, while np.tile() is designed to operate on the entire array. Hence,

import numpy as np L = 10 N = 20 A = np.random.rand(L,L) np.tile(A,(N, 1, 1))

更多推荐

有效地堆叠阵列/火炬张量的副本?

本文发布于:2023-11-30 00:03:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:张量   有效地   阵列   副本

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!