In this example, we fit a linear model with positive constraints on the
regression coefficients and compare the estimated coefficients to a classic
linear regression.
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clauseimportmatplotlib.pyplotaspltimportnumpyasnpfromsklearn.metricsimportr2_score
Generate some random data
np.random.seed(42)n_samples,n_features=200,50X=np.random.randn(n_samples,n_features)true_coef=3*np.random.randn(n_features)# Threshold coefficients to render them non-negativetrue_coef[true_coef<0]=0y=np.dot(X,true_coef)# Add some noisey+=5*np.random.normal(size=(n_samples,))
Comparing the regression coefficients between OLS and NNLS, we can observe
they are highly correlated (the dashed line is the identity relation),
but the non-negative constraint shrinks some to 0.
The Non-Negative Least squares inherently yield sparse results.