gpt4 book ai didi

python - 何时使用 .shape 何时使用 .reshape?

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:53 25 4
gpt4 key购买 nike

我尝试在 numpy 数组上使用 .reshape 时遇到了内存问题,我想如果我能以某种方式就地 reshape 数组,那就太好了。

我意识到我可以通过简单地更改 .shape 值来 reshape 数组。不幸的是,当我尝试使用 .shape 时,我再次遇到内存错误,这让我认为它没有就地 reshape 。

我想知道什么时候使用一个,什么时候使用另一个?

感谢任何帮助。

如果您需要更多信息,请告诉我。

编辑:

我添加了我的代码以及我想要 reshape 的矩阵是如何创建的,以防万一。

根据您的内存更改 N 值。

import numpy as np
N = 100
a = np.random.rand(N, N)
b = np.random.rand(N, N)
c = a[:, np.newaxis, :, np.newaxis] * b[np.newaxis, :, np.newaxis, :]
c = c.reshape([N*N, N*N])
c.shape = ([N, N, N, N])

编辑2:这是一个更好的表示。显然,转置似乎很重要,因为它将数组从 C 连续更改为 F 连续,并且在上述情况下产生的乘法是连续的,而在下面的情况下则不是。

import numpy as np
N = 100
a = np.random.rand(N, N).T
b = np.random.rand(N, N).T
c = a[:, np.newaxis, :, np.newaxis] * b[np.newaxis, :, np.newaxis, :]
c = c.reshape([N*N, N*N])
c.shape = ([N, N, N, N])

最佳答案

numpy.reshape如果无法正确查看,将复制数据,而设置 shape 将引发错误,而不是复制数据。

It is not always possible to change the shape of an array without copying the data. If you want an error to be raise if the data is copied, you should assign the new shape to the shape attribute of the array.

关于python - 何时使用 .shape 何时使用 .reshape?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26856375/

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