You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
SGDRegressor gets poor fit with sparse matrix #11178
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.)
importnumpyfromscipy.sparseimportcsr_matrixfromsklearn.datasetsimportload_diabetesfromsklearn.linear_modelimportSGDRegressor, LinearRegressionfromsklearn.preprocessingimportStandardScalerimportmatplotlib.pyplotaspltdiabetes=load_diabetes()
X=diabetes.data# X = csr_matrix(X) # Uncomment this line to use a sparse matrixy=numpy.asarray(diabetes.target)
scaler=StandardScaler(with_mean=False)
scaler.fit(X)
X=scaler.transform(X)
estimator=SGDRegressor()
# estimator = LinearRegression() # LinearRegression works with sparse matrixestimator.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.
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.
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.
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.
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.
It looks like there's some difference in the coefficients but mostly in the intercept.
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.
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.
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.
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?
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)
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.
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.
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
@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.
Activity
jennaliu commentedon May 31, 2018
I misunderstood the code I linked to, it is not converting the matrix.
amueller commentedon Jun 1, 2018
So is there an issue? Indeed the data is not converted to dense. You probably want to use
MaxAbsScalerfor sparse data. And you might want to increase the number of iterations for better performance.jennaliu commentedon Jun 1, 2018
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.


amueller commentedon Jun 1, 2018
Is the data preprocessed the same way? Can you provide self-contained code to reproduce the figures?
jennaliu commentedon Jun 1, 2018
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.
amueller commentedon Jun 1, 2018
It would be nicer to have it fully self-contained but alright. I can reproduce. Seems like a bug to me :-/
amueller commentedon Jun 1, 2018
I don't understand the line that you're drawing.
jennaliu commentedon Jun 1, 2018
That's just the diagonal line. The predicted values and target values should be close. http://scikit-learn.org/stable/auto_examples/plot_cv_predict.html#sphx-glr-auto-examples-plot-cv-predict-py
amueller commentedon Jun 1, 2018
ah yeah, I was confused by the way it was written for a second.
amueller commentedon Jun 1, 2018
(not the different scales)
amueller commentedon Jun 1, 2018
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.

It looks like there's some difference in the coefficients but mostly in the intercept.
jennaliu commentedon Jun 1, 2018
http://scikit-learn.org/stable/modules/sgd.html#stochastic-gradient-descent-for-sparse-data
But to me, that difference is huge. In order to get the same fit, I need to run many more iterations.
amueller commentedon Jun 1, 2018
I think that this is not the reason because that would make the intercept larger, not smaller.
amueller commentedon Jun 1, 2018
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.
jennaliu commentedon Jun 1, 2018
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.
amueller commentedon Jun 1, 2018
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
amueller commentedon Jun 1, 2018
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.
jennaliu commentedon Jun 1, 2018
In that case, maybe the learning rate should be adjusted with the sparsity of the data? It seems like it could have worked better.
amueller commentedon Jun 2, 2018
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?
jennaliu commentedon Jun 2, 2018
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)
amueller commentedon Jun 2, 2018
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.
jennaliu commentedon Jun 2, 2018
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.
jennaliu commentedon Jun 5, 2018
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.)
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
SimonBenhamou commentedon Jan 8, 2021
@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
jeremiedbb commentedon Apr 7, 2026
The issue is fixed in main.
The reproducer from #11178 (comment) now gives similar results
and the reproducer from #11178 (comment) now gives similar scales for sparse and dense.

We can close this one