pytorch中expand的numpy等价物是什么?

wi3ka0sx  于 2022-12-13  发布在  其他
关注(0)|答案(3)|浏览(165)

假设我有一个numpy数组x,形状为[1,5],我想沿着0轴展开它,使得到的数组y的形状为[10,5],并且对于每个i,y[i:i+1,:]等于x
如果x是pytorchTensor,我可以简单地做

y = x.expand(10,-1)

但是numpy中没有expand,看起来像它的那些(expand_dimsrepeat)看起来也不像它。
示例:

>>> import torch
>>> x = torch.randn(1,5)
>>> print(x)
tensor([[ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724]])
>>> print(x.expand(10,-1))
tensor([[ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724],
        [ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724]])
mqkwyuun

mqkwyuun1#

你可以用np.broadcast_to来实现,但不能用负数:

>>> import numpy as np
>>> x = np.array([[ 1.3306,  0.0627,  0.5585, -1.3128, -1.4724]])
>>> print(np.broadcast_to(x,(10,5)))
[[ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
 [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
 [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
 [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
 [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
 [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
 [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
 [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
 [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]
 [ 1.3306  0.0627  0.5585 -1.3128 -1.4724]]
gorkyyrv

gorkyyrv2#

您可以使用np.tile,它会重复指定轴的元素,如下所示:

>>> x = np.range(5)
>>> x = np.expand_dims(x, 0)
>>> x.shape
(1, 5)
>>> y = np.tile(x, (10, 1))  # repeat axis=0 10 times and axis=1 1 time
>>> y.shape
(10, 5)
scyqe7ek

scyqe7ek3#

numpy拥有numpy.newaxis

y = x[:, np.newaxis]

相关问题