何时使用.shape和何时使用.reshape? [英] When to use .shape and when to use .reshape?

查看:99
本文介绍了何时使用.shape和何时使用.reshape?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在numpy数组上使用.reshape时遇到内存问题,并弄清楚了是否可以以某种方式将数组整形,这会很棒.

I ran into a memory problem when trying to use .reshape on a numpy array and figured if I could somehow reshape the array in place that would be great.

我意识到我可以通过简单地改变.shape值来改变数组的形状. 不幸的是,当我尝试使用.shape时,我再次遇到内存错误,使我认为它不会在原地重塑.

I realised that I could reshape arrays by simply changing the .shape value. Unfortunately when I tried using .shape I again got a memory error which has me thinking that it doesn't reshape in place.

我想知道何时使用另一种?

I was wondering when do I use one when do I use the other?

感谢您的帮助.

如果您需要其他信息,请告诉我.

If you want additional information please let me know.

我添加了代码,并在重要的情况下如何创建要重塑的矩阵.

I added my code and how the matrix I want to reshape is created in case that is important.

根据您的内存更改N值.

Change the N value depending on your memory.

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

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

This is a better representation. Apparently the transpose seems to be important as it changes the arrays from C-contiguous to F-contiguous, and the resulting multiplication in above case is contiguous while in the one below it is not.

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 will copy the data if it can't make a proper view, whereas setting the shape will raise an error instead of copying the data.

并非总是可以在不复制数据的情况下更改数组的形状.如果要在复制数据时引发错误,则应将新形状分配给数组的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.

这篇关于何时使用.shape和何时使用.reshape?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆