scikit-learn/scikit-learn — Issue #533: LinearRegression does not work with sparse matrix
Author: emmanuelle
Created: 2012-01-05 21:20:19+00:00
State: open

The following code

from scipy import sparse
from sklearn.linear_model import LinearRegression
import numpy as np

np.random.seed(0)
n = 100
diag = np.random.random(n)
X = sparse.dia_matrix((diag, [0]), shape=(n, n))
beta = np.random.random(n)[:, np.newaxis]
y = X * beta

ols = LinearRegression()
# works fine
ols.fit(X.todense(), y.ravel())
# doesn't work
ols.fit(X, y.ravel())

yields the following traceback

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)

/home/emma/travail/2011/signal_processing/tomo/discussions/marc/marc/traceback.py in ()
14 ols.fit(X.todense(), y.ravel())
15 # doesn't work

---> 16 ols.fit(X, y.ravel())
17
18

/usr/local/lib/python2.7/dist-packages/scikit_learn-0.10_git-py2.7-linux-x86_64.egg/sklearn/linear_model/base.pyc in fit(self, X, y)
143
144 X, y, X_mean, y_mean, X_std = self._center_data(X, y,
--> 145 self.fit_intercept, self.normalize, self.copy_X)
146
147 self.coef_, self.residues_, self.rank_, self.singular_ = \

/usr/local/lib/python2.7/dist-packages/scikit_learn-0.10_git-py2.7-linux-x86_64.egg/sklearn/linear_model/base.pyc in _center_data(X, y, fit_intercept, normalize, copy)
61 If copy is False, modifies X in-place.
62 """
---> 63 X = as_float_array(X, copy)
64
65 if fit_intercept:

/usr/local/lib/python2.7/dist-packages/scikit_learn-0.10_git-py2.7-linux-x86_64.egg/sklearn/utils/validation.pyc in as_float_array(X, copy)
60 X = X.astype(np.float32)
61 else:
---> 62 X = X.astype(np.float64)
63 return X
64

TypeError: float() argument must be a string or a number
WARNING: Failure executing file: