Python empty csr_matrix throws ValueError: cannot infer dimensions from zero sized index arrays
<p>Here's the python SSCCE: </p>

<pre><code>import scipy.sparse
data = []
row = []
col = []
csr = scipy.sparse.csr_matrix((data, (row, col)))  #error happens here
print(type(csr))
print(csr)
</code></pre>

<p>I'm running it with python2.7 I get an error:</p>

<pre><code>raise ValueError('cannot infer dimensions from zero sized index arrays')
ValueError: cannot infer dimensions from zero sized index arrays
</code></pre>

<p>It works correctly when I feed them values like this:</p>

<pre><code>csr = scipy.sparse.csr_matrix(([10,20,30], ([0,0,0],[0,1,2])))
</code></pre>

<p>or like this:</p>

<pre><code>csr = scipy.sparse.csr_matrix(([10,20], ([0,0],[0,1])))
csr = scipy.sparse.csr_matrix(([10], ([0],[0])))
</code></pre>

<p>I read the documentation at:
<a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html</a> and </p>

<p><a href="http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information</a> </p>

<p>but that doesn't seem to explain why I can't make a csr matrix with zero items in it.</p>

<p>What's going on with this error?  I guess scipy.sparse.csr.csr_matrix types must have at least one value in them on instantiation?  That seems like a silly restriction. </p>

<p>Scipy sparse matrices have a definite shape, e.g. (m, n) where m is the number of rows and n is the number of columns.  When you write, for example, <code>csr_matrix(([1, 2], ([0, 3], [1, 4])))</code>, <code>csr_matrix</code> infers the shape from the maximum values of the row and column indices.  But when you write <code>csr_matrix(([], ([], [])))</code>, the function has no way of knowing what the shape of the matrix should be (and I guess it won't create a matrix with shape (0, 0) by default).</p>

<p>One way to handle that is to give an explicit <code>shape</code>:</p>

<pre><code>In [241]: csr_matrix(([], ([], [])), shape=(3, 3))
Out[241]: 
&lt;3x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;'
    with 0 stored elements in Compressed Sparse Row format&gt;
</code></pre>

python scipy sparse-matrix