Skip to content

SGDRegressor gets poor fit with sparse matrix #11178

Closed

Description

@jennaliu

If a sparse matrix is passed into the function, it doesn't throw any error but gets a poor fit sometimes. I think it should either throw an error when the parameter is a sparse matrix or convert it into a dense matrix like #535

Below is some code to compare the differences. (It fits well on boston housing price even when the parameter is a sparse matrix but fails on diabetes.)

import numpy
from scipy.sparse import csr_matrix
from sklearn.datasets import load_diabetes
from sklearn.linear_model import SGDRegressor, LinearRegression
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

diabetes = load_diabetes()
X = diabetes.data
# X = csr_matrix(X)  # Uncomment this line to use a sparse matrix
y = numpy.asarray(diabetes.target)

scaler = StandardScaler(with_mean=False)
scaler.fit(X)
X = scaler.transform(X)

estimator = SGDRegressor()
# estimator = LinearRegression()  # LinearRegression works with sparse matrix
estimator.fit(X, y)
predicted = estimator.predict(X)

fig, ax = plt.subplots()
ax.scatter(y, predicted, edgecolors=(0, 0, 0))
ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4)
ax.set_xlabel('Measured')
ax.set_ylabel('Predicted')
plt.show()

Just stating in the documentation that the input should be a dense matrix is not enough, it may cause surprises like this.

NumPy 1.14.2
SciPy 1.1.0
Scikit-Learn 0.19.1

Activity

  1. jennaliu commented on May 31, 2018

    @jennaliu
    Author

    I misunderstood the code I linked to, it is not converting the matrix.

  2. amueller commented on Jun 1, 2018

    @amueller
    Member

    So is there an issue? Indeed the data is not converted to dense. You probably want to use MaxAbsScaler for sparse data. And you might want to increase the number of iterations for better performance.

  3. jennaliu commented on Jun 1, 2018

    @jennaliu
    Author

    I probably didn't describe the issue clearly. I attached the fit below. The first figure is for dense matrix and the second one is for sparse matrix. The two fits use the exact same data. The only difference is how it is passed into the function. To me that is very confusing. And other models like LinearRegression don't have this problem. I think there maybe some issue with how SGDRegressor fits on a sparse matrix.
    image 1
    image 2

  4. amueller commented on Jun 1, 2018

    @amueller
    Member

    Is the data preprocessed the same way? Can you provide self-contained code to reproduce the figures?

  5. jennaliu commented on Jun 1, 2018

    @jennaliu
    Author

    I attached the code in my first post. If you run it directly you get the first figure. If you uncommend the line that convert it to a sparse matrix, you would get the second figure.

  6. amueller commented on Jun 1, 2018

    @amueller
    Member

    It would be nicer to have it fully self-contained but alright. I can reproduce. Seems like a bug to me :-/

  7. amueller commented on Jun 1, 2018

    @amueller
    Member

    I don't understand the line that you're drawing.

  8. amueller commented on Jun 1, 2018

    @amueller
    Member

    ah yeah, I was confused by the way it was written for a second.

  9. amueller commented on Jun 1, 2018

    @amueller
    Member
    import numpy
    %matplotlib inline
    from scipy.sparse import csr_matrix
    from sklearn.datasets import load_diabetes
    from sklearn.linear_model import SGDRegressor, LinearRegression
    from sklearn.preprocessing import StandardScaler, MaxAbsScaler
    import matplotlib.pyplot as plt
    
    diabetes = load_diabetes()
    X = diabetes.data
    
    y = numpy.asarray(diabetes.target)
    
    scaler = MaxAbsScaler()
    scaler.fit(X)
    X_scaled = scaler.transform(X)
    X_sparse = csr_matrix(X_scaled)
    
    estimator = SGDRegressor()
    estimator.fit(X_scaled, y)
    predicted_dense = estimator.predict(X_scaled)
    estimator = SGDRegressor()
    estimator.fit(X_sparse, y)
    predicted_sparse = estimator.predict(X_sparse)
    
    fig, ax = plt.subplots()
    ax.scatter(predicted_sparse, predicted_dense, edgecolors=(0, 0, 0))
    #ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4)
    ax.set_xlabel('sparse fit')
    ax.set_ylabel('dense fit')
    ax.set_aspect("equal")
    plt.show()

    image
    (not the different scales)

  10. amueller commented on Jun 1, 2018

    @amueller
    Member

    increasing the number of iterations fixes the mismatch, but it looks like something different is happening in sparse and dense cases and that's surprising to me.
    image
    It looks like there's some difference in the coefficients but mostly in the intercept.

  11. jennaliu commented on Jun 1, 2018

    @jennaliu
    Author

    http://scikit-learn.org/stable/modules/sgd.html#stochastic-gradient-descent-for-sparse-data

    Note The sparse implementation produces slightly different results than the dense implementation due to a shrunk learning rate for the intercept.

    But to me, that difference is huge. In order to get the same fit, I need to run many more iterations.

  12. amueller commented on Jun 1, 2018

    @amueller
    Member

    I think that this is not the reason because that would make the intercept larger, not smaller.

  13. amueller commented on Jun 1, 2018

    @amueller
    Member

    Oh actually that is what's happening. Smaller intercept decay means the intercept decays more. A bit of a misnomer imho. It's a heuristic but it seems to make sense for sparse data. This dataset is very small and you shouldn't use SGD in the first place, and it's also not sparse.

  14. jennaliu commented on Jun 1, 2018

    @jennaliu
    Author

    Is there an example of this intercept decay helping other than obstructing the learning process? Can you point me to some source for this heuristic? It seems to be a bit arbitrary. The reason I passed a csr_matrix is that I wanted to have a unified format for all the data, and the data was sparse in previous use cases.

  15. amueller commented on Jun 1, 2018

    @amueller
    Member

    Always using sparse data is a bad idea, and always using SGDClassifier is also a bad idea.
    I think the reference is probably http://leon.bottou.org/projects/sgd

  16. amueller commented on Jun 1, 2018

    @amueller
    Member

    The point of the heuristic is that for sparse models, coefficients are updated rarely, but the intercept is updated always, so the intercept basically has a learning rate that is higher than the learning rate of the coefficients by a factor of the sparsity of the data.

  17. jennaliu commented on Jun 1, 2018

    @jennaliu
    Author

    In that case, maybe the learning rate should be adjusted with the sparsity of the data? It seems like it could have worked better.

  18. amueller commented on Jun 2, 2018

    @amueller
    Member

    Sorry I don't follow. The point is that the learning rate for the bias and the weights needs to be different in the sparse case. But your case is not sparse. You just converted your data to sparse, but it's not sparse, so the assumptions of the sparse algorithm are not met.
    Why do you want to run the sparse algorithm on dense data?

  19. jennaliu commented on Jun 2, 2018

    @jennaliu
    Author

    I was thinking something like this. jennaliu@981452a
    Just because the data is in a sparse format doesn't mean it is sparse and I don't think SGD is a sparse algorithm (that it only works on sparse data)

  20. amueller commented on Jun 2, 2018

    @amueller
    Member

    yeah something like that might make sense. Do you want to do some benchmarks?
    SGD certainly doesn't only work on sparse data and adapting to the sparsity in the data might make sense for the heuristic. Usually if it's in sparse format, that means the data is sparse, though. If you store dense data in a sparse format you will be much slower than storing it in dense format, and it will be much more memory intensive.

  21. jennaliu commented on Jun 2, 2018

    @jennaliu
    Author

    I agree that usually dense data should not be stored in sparse format. But I don’t think it is user’s responsibility to make sure the data is indeed sparse before calling the function. And it is very counterintuitive when it fails on simple case like this.

  22. jennaliu commented on Jun 5, 2018

    @jennaliu
    Author

    I did some benchmarks. I haven't found a test case where the intercept decay helped. (The benchmark result below is without my changes and my changes don't help either.)

    input data density: 0.100000
    r^2 on train data (SGDRegressor numpy array) : 0.909006
    r^2 on test data (SGDRegressor numpy array) : 0.885369
    r^2 on train data (SGDRegressor csr_matrix) : 0.550368
    r^2 on test data (SGDRegressor csr_matrix) : 0.422082
    r^2 on train data (Ridge numpy array) : 0.908839
    r^2 on test data (Ridge numpy array) : 0.885587
    r^2 on train data (Ridge csr_matrix) : 0.908838
    r^2 on test data (Ridge csr_matrix) : 0.885607
    
    input data density: 0.010000
    r^2 on train data (SGDRegressor numpy array) : 0.572806
    r^2 on test data (SGDRegressor numpy array) : 0.463636
    r^2 on train data (SGDRegressor csr_matrix) : 0.427730
    r^2 on test data (SGDRegressor csr_matrix) : 0.247187
    r^2 on train data (Ridge numpy array) : 0.567457
    r^2 on test data (Ridge numpy array) : 0.466686
    r^2 on train data (Ridge csr_matrix) : 0.567460
    r^2 on test data (Ridge csr_matrix) : 0.466670
    
    input data density: 0.001000
    r^2 on train data (SGDRegressor numpy array) : 0.124133
    r^2 on test data (SGDRegressor numpy array) : 0.020902
    r^2 on train data (SGDRegressor csr_matrix) : 0.096810
    r^2 on test data (SGDRegressor csr_matrix) : 0.001976
    r^2 on train data (Ridge numpy array) : 0.139551
    r^2 on test data (Ridge numpy array) : 0.018710
    r^2 on train data (Ridge csr_matrix) : 0.139549
    r^2 on test data (Ridge csr_matrix) : 0.018711
    

    Can you take a look at my script? Maybe I was doing something wrong.
    https://github.com/jennaliu/scikit-learn/blob/e9a98d7a3730c92e6e0ddfe7ffe99d43b6b35b9a/benchmarks/bench_sgd_sparse.py

  23. SimonBenhamou commented on Jan 8, 2021

    @SimonBenhamou

    @jennaliu Thanks for pointing that out. After weeks spent debugging, I now understand that I experience the same issue you described, for a classification problem with sparse CSR matrices. My intercept is way too low, which causes all kinds of issues. It must come from the intercept decay, which, like you, I don't understand the purpose.

    Is anyone still looking into this ?

    Thanks,
    Simon

  24. jeremiedbb commented on Apr 7, 2026

    @jeremiedbb
    Member

    The issue is fixed in main.
    The reproducer from #11178 (comment) now gives similar results

    Image Image

    and the reproducer from #11178 (comment) now gives similar scales for sparse and dense.
    Image

    We can close this one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions