Numpy reshape acts different on copied vs. uncopied arrays
<p>I've come across seemingly inconsistent results when flattening certain numpy arrays with numpy.reshape. Sometimes if I reshape an array it returns a 2D array with one row, whereas if I first copy the array then do the exact same operation, it returns a 1D array. </p>

<p>This seems to happen primarily when combining numpy arrays with scipy arrays, and creates alignment problems when I want to later multiply the flattened array by a matrix.</p>

<p>For example, consider the following code:</p>

<pre><code>import numpy as np
import scipy.sparse as sps

n = 10
A = np.random.randn(n,n)
I = sps.eye(n)
X = I+A

x1 = np.reshape(X, -1)
x2 = np.reshape(np.copy(X), -1)

print 'x1.shape=', x1.shape
print 'x2.shape=', x2.shape
</code></pre>

<p>When run it prints:</p>

<pre><code>x1.shape= (1, 100)
x2.shape= (100,)
</code></pre>

<p>The same thing happens with numpy.flatten(). What is going on here? Is this behavior intentional?</p>

<p>You added together a sparse matrix object and a normal ndarray:</p>

<pre><code>X = I+A
</code></pre>

<p>The result is a dense <em>matrix</em> object, an instance of <code>np.matrix</code>, not a normal ndarray.</p>

<p>This:</p>

<pre><code>np.reshape(X, -1)
</code></pre>

<p>ends up returning a matrix, which can't be less than 2D.</p>

<p>This:</p>

<pre><code>np.reshape(np.copy(X), -1)
</code></pre>

<p>makes a normal ndarray in <code>np.copy(X)</code>, so you get a 1D output from <code>np.reshape</code>.</p>

<p>Be very careful at all times about whether you're dealing with sparse matrices, dense matrices, or standard ndarrays. Avoid <code>np.matrix</code> whenever possible.</p>

python arrays numpy scipy