问题描述
我是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 followingarray: 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))
这篇关于有效地堆叠阵列/火炬张量的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!