Skip to content

Commit

Permalink
Prevent svdlibc from seeing a zero-entry sparse matrix.
Browse files Browse the repository at this point in the history
The fact that svdlibc's state can be permanently corrupted by a matrix with no
entries indicates to me that its memory handling is unsafe. We should see if
it's feasible to switch to SciPy sometime.
  • Loading branch information
Rob Speer committed Feb 28, 2012
1 parent d3a9a34 commit fb63231
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions divisi2/algorithms/svd.py
Expand Up @@ -3,6 +3,7 @@
from divisi2.reconstructed import ReconstructedMatrix
from divisi2._svdlib import svd_llmat, svd_ndarray
from divisi2 import operators
import numpy as np

def svd(matrix, k=50):
"""
Expand All @@ -22,6 +23,13 @@ def svd(matrix, k=50):
if isinstance(matrix, DenseMatrix):
Ut, S, Vt = svd_ndarray(matrix, k)
elif isinstance(matrix, SparseMatrix):
if matrix.nnz == 0:
# don't let svdlib touch a matrix of all zeros. It explodes and
# corrupts its state. Just return a zero result instead.
U = DenseMatrix((matrix.shape[0], k))
S = np.zeros((k,))
V = DenseMatrix((matrix.shape[1], k))
return U, S, V
if matrix.shape[1] >= matrix.shape[0] * 1.2:
# transpose the matrix for speed
V, S, U = matrix.T.svd(k)
Expand Down

0 comments on commit fb63231

Please sign in to comment.