Often, when numpy has seemingly duplicate functions, there often ends up being some sort of unique purpose for one or the other.
I am trying to figure out if there are any situations where flatten() should be used instead of reshape(-1)
Often, when numpy has seemingly duplicate functions, there often ends up being some sort of unique purpose for one or the other.
I am trying to figure out if there are any situations where flatten() should be used instead of reshape(-1)
flatten returns a copy of the array. reshape will return a view if possible.
So, for example, if y = x.reshape(-1) is a view, then modifying y also modifies x:
In [149]: x = np.arange(3)
In [150]: y = x.reshape(-1)
In [151]: y[0] = 99
In [152]: x
Out[152]: array([99, 1, 2])
But since y = x.flatten() is a copy, modifying y will never modify x:
In [153]: x = np.arange(3)
In [154]: y = x.flatten()
In [155]: y[0] = 99
In [156]: x
Out[156]: array([0, 1, 2])
Here is an example of when reshape returns a copy instead of a view:
In [161]: x = np.arange(24).reshape(4,6)[::2, :]
In [163]: y = x.reshape(-1)
In [164]: y[0] = 99
In [165]: x
Out[165]:
array([[ 0, 1, 2, 3, 4, 5],
[12, 13, 14, 15, 16, 17]])
Since x is unaffected by an assignment made to y, we know y is a copy of
x, not a view.