gpt4 book ai didi

numpy - PyTorch 中的 reshape 顺序 - 类似 Fortran 的索引排序

转载 作者:行者123 更新时间:2023-12-03 08:35:26 35 4
gpt4 key购买 nike

在numpy中,有一个用于 reshape 数组的排序功能,默认情况下它是C,但您可以指定其他排序,例如F:

a = np.arange(6).reshape((3, 2))
f = np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
c = np.reshape(a, (2, 3))
print('a= \n', a)
print('f= \n', b)
print('c= \n', c)

结果:

a= 
[[0 1]
[2 3]
[4 5]]
f=
[[0 4 3]
[2 1 5]]
c=
[[0 1 2]
[3 4 5]]

torch.reshape或tensor.view中没有用于按F顺序 reshape 的选项。有什么方法可以在 PyTorch 中进行 F 顺序 reshape 吗?我需要 PyTorch 中的所有内容。

最佳答案

我不认为 pytorch 对此有内置支持。也就是说,您可以使用 Tensor.permute 获得所需的结果。 。不幸的是,我怀疑这是否会非常有效,因为 AFAIK 排列内部会生成张量的副本。

def reshape_fortran(x, shape):
if len(x.shape) > 0:
x = x.permute(*reversed(range(len(x.shape))))
return x.reshape(*reversed(shape)).permute(*reversed(range(len(shape))))

使用示例:

a = torch.arange(6).reshape(3, 2)
f = reshape_fortran(a, (2, 3))
c = a.reshape(2, 3)

结果

a = 
tensor([[0, 1],
[2, 3],
[4, 5]])
f =
tensor([[0, 4, 3],
[2, 1, 5]])
c =
tensor([[0, 1, 2],
[3, 4, 5]])

关于numpy - PyTorch 中的 reshape 顺序 - 类似 Fortran 的索引排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63960352/

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