gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:46:57 25 4
gpt4 key购买 nike

假设我有一个形状为 [1,5] 的 numpy 数组 x。我想沿轴 0 扩展它,使得结果数组 y 的形状为 [10,5] 并且 y[i:i+1,:] 等于 x 每个 i.

如果 x 是一个 pytorch 张量,我可以简单地做

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]])

最佳答案

您可以使用 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]]

关于python - pytorch 中 expand 的 numpy 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65234748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com