1.1.Linear Models#

The following are a set of methods intended for regression in whichthe target value is expected to be a linear combination of the features.In mathematical notation, if\(\hat{y}\) is the predictedvalue.

\[\hat{y}(w, x) = w_0 + w_1 x_1 + ... + w_p x_p\]

Across the module, we designate the vector\(w = (w_1,..., w_p)\) ascoef_ and\(w_0\) asintercept_.

To perform classification with generalized linear models, seeLogistic regression.

1.1.1.Ordinary Least Squares#

LinearRegression fits a linear model with coefficients\(w = (w_1, ..., w_p)\) to minimize the residual sumof squares between the observed targets in the dataset, and thetargets predicted by the linear approximation. Mathematically itsolves a problem of the form:

\[\min_{w} || X w - y||_2^2\]
../_images/sphx_glr_plot_ols_ridge_001.png

LinearRegression takes in itsfit method argumentsX,y,sample_weight and stores the coefficients\(w\) of the linear model in itscoef_ andintercept_ attributes:

>>>fromsklearnimportlinear_model>>>reg=linear_model.LinearRegression()>>>reg.fit([[0,0],[1,1],[2,2]],[0,1,2])LinearRegression()>>>reg.coef_array([0.5, 0.5])>>>reg.intercept_0.0

The coefficient estimates for Ordinary Least Squares rely on theindependence of the features. When features are correlated and somecolumns of the design matrix\(X\) have an approximately lineardependence, the design matrix becomes close to singularand as a result, the least-squares estimate becomes highly sensitiveto random errors in the observed target, producing a largevariance. This situation ofmulticollinearity can arise, forexample, when data are collected without an experimental design.

Examples

1.1.1.1.Non-Negative Least Squares#

It is possible to constrain all the coefficients to be non-negative, which maybe useful when they represent some physical or naturally non-negativequantities (e.g., frequency counts or prices of goods).LinearRegression accepts a booleanpositiveparameter: when set toTrueNon-Negative Least Squares are then applied.

Examples

1.1.1.2.Ordinary Least Squares Complexity#

The least squares solution is computed using the singular valuedecomposition of\(X\). If\(X\) is a matrix of shape(n_samples,n_features)this method has a cost of\(O(n_{\text{samples}} n_{\text{features}}^2)\), assuming that\(n_{\text{samples}} \geq n_{\text{features}}\).

1.1.2.Ridge regression and classification#

1.1.2.1.Regression#

Ridge regression addresses some of the problems ofOrdinary Least Squares by imposing a penalty on the size of thecoefficients. The ridge coefficients minimize a penalized residual sumof squares:

\[\min_{w} || X w - y||_2^2 + \alpha ||w||_2^2\]

The complexity parameter\(\alpha \geq 0\) controls the amountof shrinkage: the larger the value of\(\alpha\), the greater the amountof shrinkage and thus the coefficients become more robust to collinearity.

../_images/sphx_glr_plot_ridge_path_001.png

As with other linear models,Ridge will take in itsfit methodarraysX,y and will store the coefficients\(w\) of the linear model initscoef_ member:

>>>fromsklearnimportlinear_model>>>reg=linear_model.Ridge(alpha=.5)>>>reg.fit([[0,0],[0,0],[1,1]],[0,.1,1])Ridge(alpha=0.5)>>>reg.coef_array([0.34545455, 0.34545455])>>>reg.intercept_np.float64(0.13636)

Note that the classRidge allows for the user to specify that thesolver be automatically chosen by settingsolver="auto". When this optionis specified,Ridge will choose between the"lbfgs","cholesky",and"sparse_cg" solvers.Ridge will begin checking the conditionsshown in the following table from top to bottom. If the condition is true,the corresponding solver is chosen.

Solver

Condition

‘lbfgs’

Thepositive=True option is specified.

‘cholesky’

The input array X is not sparse.

‘sparse_cg’

None of the above conditions are fulfilled.

Examples

1.1.2.2.Classification#

TheRidge regressor has a classifier variant:RidgeClassifier. This classifier first converts binary targets to{-1,1} and then treats the problem as a regression task, optimizing thesame objective as above. The predicted class corresponds to the sign of theregressor’s prediction. For multiclass classification, the problem istreated as multi-output regression, and the predicted class corresponds tothe output with the highest value.

It might seem questionable to use a (penalized) Least Squares loss to fit aclassification model instead of the more traditional logistic or hingelosses. However, in practice, all those models can lead to similarcross-validation scores in terms of accuracy or precision/recall, while thepenalized least squares loss used by theRidgeClassifier allows fora very different choice of the numerical solvers with distinct computationalperformance profiles.

TheRidgeClassifier can be significantly faster than e.g.LogisticRegression with a high number of classes because it cancompute the projection matrix\((X^T X)^{-1} X^T\) only once.

This classifier is sometimes referred to as aLeast Squares Support VectorMachine witha linear kernel.

Examples

1.1.2.3.Ridge Complexity#

This method has the same order of complexity asOrdinary Least Squares.

1.1.2.4.Setting the regularization parameter: leave-one-out Cross-Validation#

RidgeCV andRidgeClassifierCV implement ridgeregression/classification with built-in cross-validation of the alpha parameter.They work in the same way asGridSearchCV exceptthat it defaults to efficient Leave-One-Outcross-validation.When using the defaultcross-validation, alpha cannot be 0 due to theformulation used to calculate Leave-One-Out error. See[RL2007] for details.

Usage example:

>>>importnumpyasnp>>>fromsklearnimportlinear_model>>>reg=linear_model.RidgeCV(alphas=np.logspace(-6,6,13))>>>reg.fit([[0,0],[0,0],[1,1]],[0,.1,1])RidgeCV(alphas=array([1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01,      1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06]))>>>reg.alpha_np.float64(0.01)

Specifying the value of thecv attribute will trigger the use ofcross-validation withGridSearchCV, forexamplecv=10 for 10-fold cross-validation, rather than Leave-One-OutCross-Validation.

References#
[RL2007]

“Notes on Regularized Least Squares”, Rifkin & Lippert (technical report,course slides).

1.1.3.Lasso#

TheLasso is a linear model that estimates sparse coefficients.It is useful in some contexts due to its tendency to prefer solutionswith fewer non-zero coefficients, effectively reducing the number offeatures upon which the given solution is dependent. For this reason,Lasso and its variants are fundamental to the field of compressed sensing.Under certain conditions, it can recover the exact set of non-zerocoefficients (seeCompressive sensing: tomography reconstruction with L1 prior (Lasso)).

Mathematically, it consists of a linear model with an added regularization term.The objective function to minimize is:

\[\min_{w} { \frac{1}{2n_{\text{samples}}} ||X w - y||_2 ^ 2 + \alpha ||w||_1}\]

The lasso estimate thus solves the minimization of theleast-squares penalty with\(\alpha ||w||_1\) added, where\(\alpha\) is a constant and\(||w||_1\) is the\(\ell_1\)-norm ofthe coefficient vector.

The implementation in the classLasso uses coordinate descent asthe algorithm to fit the coefficients. SeeLeast Angle Regressionfor another implementation:

>>>fromsklearnimportlinear_model>>>reg=linear_model.Lasso(alpha=0.1)>>>reg.fit([[0,0],[1,1]],[0,1])Lasso(alpha=0.1)>>>reg.predict([[1,1]])array([0.8])

The functionlasso_path is useful for lower-level tasks, as itcomputes the coefficients along the full path of possible values.

Examples

Note

Feature selection with Lasso

As the Lasso regression yields sparse models, it canthus be used to perform feature selection, as detailed inL1-based feature selection.

References#

The following two references explain the iterationsused in the coordinate descent solver of scikit-learn, as well asthe duality gap computation used for convergence control.

  • “Regularization Path For Generalized linear Models by Coordinate Descent”,Friedman, Hastie & Tibshirani, J Stat Softw, 2010 (Paper).

  • “An Interior-Point Method for Large-Scale L1-Regularized Least Squares,”S. J. Kim, K. Koh, M. Lustig, S. Boyd and D. Gorinevsky,in IEEE Journal of Selected Topics in Signal Processing, 2007(Paper)

1.1.3.1.Setting regularization parameter#

Thealpha parameter controls the degree of sparsity of the estimatedcoefficients.

1.1.3.1.1.Using cross-validation#

scikit-learn exposes objects that set the Lassoalpha parameter bycross-validation:LassoCV andLassoLarsCV.LassoLarsCV is based on theLeast Angle Regression algorithmexplained below.

For high-dimensional datasets with many collinear features,LassoCV is most often preferable. However,LassoLarsCV hasthe advantage of exploring more relevant values ofalpha parameter, andif the number of samples is very small compared to the number offeatures, it is often faster thanLassoCV.

lasso_cv_1lasso_cv_2

1.1.3.1.2.Information-criteria based model selection#

Alternatively, the estimatorLassoLarsIC proposes to use theAkaike information criterion (AIC) and the Bayes Information criterion (BIC).It is a computationally cheaper alternative to find the optimal value of alphaas the regularization path is computed only once instead of k+1 timeswhen using k-fold cross-validation.

Indeed, these criteria are computed on the in-sample training set. In short,they penalize the over-optimistic scores of the different Lasso models bytheir flexibility (cf. to “Mathematical details” section below).

However, such criteria need a proper estimation of the degrees of freedom ofthe solution, are derived for large samples (asymptotic results) and assume thecorrect model is candidates under investigation. They also tend to break whenthe problem is badly conditioned (e.g. more features than samples).

../_images/sphx_glr_plot_lasso_lars_ic_001.png

Examples

1.1.3.1.3.AIC and BIC criteria#

The definition of AIC (and thus BIC) might differ in the literature. In thissection, we give more information regarding the criterion computed inscikit-learn.

Mathematical details#

The AIC criterion is defined as:

\[AIC = -2 \log(\hat{L}) + 2 d\]

where\(\hat{L}\) is the maximum likelihood of the model and\(d\) is the number of parameters (as well referred to as degrees offreedom in the previous section).

The definition of BIC replaces the constant\(2\) by\(\log(N)\):

\[BIC = -2 \log(\hat{L}) + \log(N) d\]

where\(N\) is the number of samples.

For a linear Gaussian model, the maximum log-likelihood is defined as:

\[\log(\hat{L}) = - \frac{n}{2} \log(2 \pi) - \frac{n}{2} \log(\sigma^2) - \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{2\sigma^2}\]

where\(\sigma^2\) is an estimate of the noise variance,\(y_i\) and\(\hat{y}_i\) are respectively the true and predictedtargets, and\(n\) is the number of samples.

Plugging the maximum log-likelihood in the AIC formula yields:

\[AIC = n \log(2 \pi \sigma^2) + \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{\sigma^2} + 2 d\]

The first term of the above expression is sometimes discarded since it is aconstant when\(\sigma^2\) is provided. In addition,it is sometimes stated that the AIC is equivalent to the\(C_p\) statistic[12]. In a strict sense, however, it is equivalent only up to some constantand a multiplicative factor.

At last, we mentioned above that\(\sigma^2\) is an estimate of thenoise variance. InLassoLarsIC when the parameternoise_variance isnot provided (default), the noise variance is estimated via the unbiasedestimator[13] defined as:

\[\sigma^2 = \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{n - p}\]

where\(p\) is the number of features and\(\hat{y}_i\) is thepredicted target using an ordinary least squares regression. Note, that thisformula is valid only whenn_samples>n_features.

References

[12]

Zou, Hui, Trevor Hastie, and Robert Tibshirani.“On the degrees of freedom of the lasso.”The Annals of Statistics 35.5 (2007): 2173-2192.

[13]

Cherkassky, Vladimir, and Yunqian Ma.“Comparison of model selection for regression.”Neural computation 15.7 (2003): 1691-1714.

1.1.3.1.4.Comparison with the regularization parameter of SVM#

The equivalence betweenalpha and the regularization parameter of SVM,C is given byalpha=1/C oralpha=1/(n_samples*C),depending on the estimator and the exact objective function optimized by themodel.

1.1.4.Multi-task Lasso#

TheMultiTaskLasso is a linear model that estimates sparsecoefficients for multiple regression problems jointly:y is a 2D array,of shape(n_samples,n_tasks). The constraint is that the selectedfeatures are the same for all the regression problems, also called tasks.

The following figure compares the location of the non-zero entries in thecoefficient matrix W obtained with a simple Lasso or a MultiTaskLasso.The Lasso estimates yield scattered non-zeros while the non-zeros ofthe MultiTaskLasso are full columns.

multi_task_lasso_1multi_task_lasso_2

Fitting a time-series model, imposing that any active feature be active at all times.

Examples

Mathematical details#

Mathematically, it consists of a linear model trained with a mixed\(\ell_1\)\(\ell_2\)-norm for regularization.The objective function to minimize is:

\[\min_{W} { \frac{1}{2n_{\text{samples}}} ||X W - Y||_{\text{Fro}} ^ 2 + \alpha ||W||_{21}}\]

where\(\text{Fro}\) indicates the Frobenius norm

\[||A||_{\text{Fro}} = \sqrt{\sum_{ij} a_{ij}^2}\]

and\(\ell_1\)\(\ell_2\) reads

\[||A||_{2 1} = \sum_i \sqrt{\sum_j a_{ij}^2}.\]

The implementation in the classMultiTaskLasso usescoordinate descent as the algorithm to fit the coefficients.

1.1.5.Elastic-Net#

ElasticNet is a linear regression model trained with both\(\ell_1\) and\(\ell_2\)-norm regularization of the coefficients.This combination allows for learning a sparse model where few ofthe weights are non-zero likeLasso, while still maintainingthe regularization properties ofRidge. We control the convexcombination of\(\ell_1\) and\(\ell_2\) using thel1_ratioparameter.

Elastic-net is useful when there are multiple features that arecorrelated with one another. Lasso is likely to pick one of theseat random, while elastic-net is likely to pick both.

A practical advantage of trading-off between Lasso and Ridge is that itallows Elastic-Net to inherit some of Ridge’s stability under rotation.

The objective function to minimize is in this case

\[\min_{w} { \frac{1}{2n_{\text{samples}}} ||X w - y||_2 ^ 2 + \alpha \rho ||w||_1 +\frac{\alpha(1-\rho)}{2} ||w||_2 ^ 2}\]
../_images/sphx_glr_plot_lasso_lasso_lars_elasticnet_path_002.png

The classElasticNetCV can be used to set the parametersalpha (\(\alpha\)) andl1_ratio (\(\rho\)) by cross-validation.

Examples

References#

The following two references explain the iterationsused in the coordinate descent solver of scikit-learn, as well asthe duality gap computation used for convergence control.

  • “Regularization Path For Generalized linear Models by Coordinate Descent”,Friedman, Hastie & Tibshirani, J Stat Softw, 2010 (Paper).

  • “An Interior-Point Method for Large-Scale L1-Regularized Least Squares,”S. J. Kim, K. Koh, M. Lustig, S. Boyd and D. Gorinevsky,in IEEE Journal of Selected Topics in Signal Processing, 2007(Paper)

1.1.6.Multi-task Elastic-Net#

TheMultiTaskElasticNet is an elastic-net model that estimates sparsecoefficients for multiple regression problems jointly:Y is a 2D arrayof shape(n_samples,n_tasks). The constraint is that the selectedfeatures are the same for all the regression problems, also called tasks.

Mathematically, it consists of a linear model trained with a mixed\(\ell_1\)\(\ell_2\)-norm and\(\ell_2\)-norm for regularization.The objective function to minimize is:

\[\min_{W} { \frac{1}{2n_{\text{samples}}} ||X W - Y||_{\text{Fro}}^2 + \alpha \rho ||W||_{2 1} +\frac{\alpha(1-\rho)}{2} ||W||_{\text{Fro}}^2}\]

The implementation in the classMultiTaskElasticNet uses coordinate descent asthe algorithm to fit the coefficients.

The classMultiTaskElasticNetCV can be used to set the parametersalpha (\(\alpha\)) andl1_ratio (\(\rho\)) by cross-validation.

1.1.7.Least Angle Regression#

Least-angle regression (LARS) is a regression algorithm forhigh-dimensional data, developed by Bradley Efron, Trevor Hastie, IainJohnstone and Robert Tibshirani. LARS is similar to forward stepwiseregression. At each step, it finds the feature most correlated with thetarget. When there are multiple features having equal correlation, insteadof continuing along the same feature, it proceeds in a direction equiangularbetween the features.

The advantages of LARS are:

  • It is numerically efficient in contexts where the number of featuresis significantly greater than the number of samples.

  • It is computationally just as fast as forward selection and hasthe same order of complexity as ordinary least squares.

  • It produces a full piecewise linear solution path, which isuseful in cross-validation or similar attempts to tune the model.

  • If two features are almost equally correlated with the target,then their coefficients should increase at approximately the samerate. The algorithm thus behaves as intuition would expect, andalso is more stable.

  • It is easily modified to produce solutions for other estimators,like the Lasso.

The disadvantages of the LARS method include:

  • Because LARS is based upon an iterative refitting of theresiduals, it would appear to be especially sensitive to theeffects of noise. This problem is discussed in detail by Weisbergin the discussion section of the Efron et al. (2004) Annals ofStatistics article.

The LARS model can be used via the estimatorLars, or itslow-level implementationlars_path orlars_path_gram.

1.1.8.LARS Lasso#

LassoLars is a lasso model implemented using the LARSalgorithm, and unlike the implementation based on coordinate descent,this yields the exact solution, which is piecewise linear as afunction of the norm of its coefficients.

../_images/sphx_glr_plot_lasso_lasso_lars_elasticnet_path_001.png
>>>fromsklearnimportlinear_model>>>reg=linear_model.LassoLars(alpha=.1)>>>reg.fit([[0,0],[1,1]],[0,1])LassoLars(alpha=0.1)>>>reg.coef_array([0.6, 0.        ])

Examples

The LARS algorithm provides the full path of the coefficients alongthe regularization parameter almost for free, thus a common operationis to retrieve the path with one of the functionslars_pathorlars_path_gram.

Mathematical formulation#

The algorithm is similar to forward stepwise regression, but insteadof including features at each step, the estimated coefficients areincreased in a direction equiangular to each one’s correlations withthe residual.

Instead of giving a vector result, the LARS solution consists of acurve denoting the solution for each value of the\(\ell_1\) norm of theparameter vector. The full coefficients path is stored in the arraycoef_path_ of shape(n_features,max_features+1). The firstcolumn is always zero.

References

1.1.9.Orthogonal Matching Pursuit (OMP)#

OrthogonalMatchingPursuit andorthogonal_mp implement the OMPalgorithm for approximating the fit of a linear model with constraints imposedon the number of non-zero coefficients (i.e. the\(\ell_0\) pseudo-norm).

Being a forward feature selection method likeLeast Angle Regression,orthogonal matching pursuit can approximate the optimum solution vector with afixed number of non-zero elements:

\[\underset{w}{\operatorname{arg\,min\,}} ||y - Xw||_2^2 \text{ subject to } ||w||_0 \leq n_{\text{nonzero_coefs}}\]

Alternatively, orthogonal matching pursuit can target a specific error insteadof a specific number of non-zero coefficients. This can be expressed as:

\[\underset{w}{\operatorname{arg\,min\,}} ||w||_0 \text{ subject to } ||y-Xw||_2^2 \leq \text{tol}\]

OMP is based on a greedy algorithm that includes at each step the atom mosthighly correlated with the current residual. It is similar to the simplermatching pursuit (MP) method, but better in that at each iteration, theresidual is recomputed using an orthogonal projection on the space of thepreviously chosen dictionary elements.

Examples

References#

1.1.10.Bayesian Regression#

Bayesian regression techniques can be used to include regularizationparameters in the estimation procedure: the regularization parameter isnot set in a hard sense but tuned to the data at hand.

This can be done by introducinguninformative priorsover the hyper parameters of the model.The\(\ell_{2}\) regularization used inRidge regression and classification isequivalent to finding a maximum a posteriori estimation under a Gaussian priorover the coefficients\(w\) with precision\(\lambda^{-1}\).Instead of settinglambda manually, it is possible to treat it as a randomvariable to be estimated from the data.

To obtain a fully probabilistic model, the output\(y\) is assumedto be Gaussian distributed around\(X w\):

\[p(y|X,w,\alpha) = \mathcal{N}(y|X w,\alpha^{-1})\]

where\(\alpha\) is again treated as a random variable that is to beestimated from the data.

The advantages of Bayesian Regression are:

  • It adapts to the data at hand.

  • It can be used to include regularization parameters in theestimation procedure.

The disadvantages of Bayesian regression include:

  • Inference of the model can be time consuming.

References#
  • A good introduction to Bayesian methods is given in C. Bishop: PatternRecognition and Machine learning

  • Original Algorithm is detailed in the bookBayesianlearningforneuralnetworks by Radford M. Neal

1.1.10.1.Bayesian Ridge Regression#

BayesianRidge estimates a probabilistic model of theregression problem as described above.The prior for the coefficient\(w\) is given by a spherical Gaussian:

\[p(w|\lambda) =\mathcal{N}(w|0,\lambda^{-1}\mathbf{I}_{p})\]

The priors over\(\alpha\) and\(\lambda\) are chosen to begammadistributions, theconjugate prior for the precision of the Gaussian. The resulting model iscalledBayesian Ridge Regression, and is similar to the classicalRidge.

The parameters\(w\),\(\alpha\) and\(\lambda\) are estimatedjointly during the fit of the model, the regularization parameters\(\alpha\) and\(\lambda\) being estimated by maximizing thelog marginal likelihood. The scikit-learn implementationis based on the algorithm described in Appendix A of (Tipping, 2001)where the update of the parameters\(\alpha\) and\(\lambda\) is doneas suggested in (MacKay, 1992). The initial value of the maximization procedurecan be set with the hyperparametersalpha_init andlambda_init.

There are four more hyperparameters,\(\alpha_1\),\(\alpha_2\),\(\lambda_1\) and\(\lambda_2\) of the gamma prior distributions over\(\alpha\) and\(\lambda\). These are usually chosen to benon-informative. By default\(\alpha_1 = \alpha_2 = \lambda_1 = \lambda_2 = 10^{-6}\).

Bayesian Ridge Regression is used for regression:

>>>fromsklearnimportlinear_model>>>X=[[0.,0.],[1.,1.],[2.,2.],[3.,3.]]>>>Y=[0.,1.,2.,3.]>>>reg=linear_model.BayesianRidge()>>>reg.fit(X,Y)BayesianRidge()

After being fitted, the model can then be used to predict new values:

>>>reg.predict([[1,0.]])array([0.50000013])

The coefficients\(w\) of the model can be accessed:

>>>reg.coef_array([0.49999993, 0.49999993])

Due to the Bayesian framework, the weights found are slightly different from theones found byOrdinary Least Squares. However, Bayesian Ridge Regressionis more robust to ill-posed problems.

Examples

References#

1.1.10.2.Automatic Relevance Determination - ARD#

The Automatic Relevance Determination (as being implemented inARDRegression) is a kind of linear model which is very similar to theBayesian Ridge Regression, but that leads to sparser coefficients\(w\)[1][2].

ARDRegression poses a different prior over\(w\): it dropsthe spherical Gaussian distribution for a centered elliptic Gaussiandistribution. This means each coefficient\(w_{i}\) can itself be drawn froma Gaussian distribution, centered on zero and with a precision\(\lambda_{i}\):

\[p(w|\lambda) = \mathcal{N}(w|0,A^{-1})\]

with\(A\) being a positive definite diagonal matrix and\(\text{diag}(A) = \lambda = \{\lambda_{1},...,\lambda_{p}\}\).

In contrast to theBayesian Ridge Regression, each coordinate of\(w_{i}\) has its own standard deviation\(\frac{1}{\lambda_i}\). Theprior over all\(\lambda_i\) is chosen to be the same gamma distributiongiven by the hyperparameters\(\lambda_1\) and\(\lambda_2\).

ARD is also known in the literature asSparse Bayesian Learning andRelevanceVector Machine[3][4].

SeeComparing Linear Bayesian Regressors for a worked-out comparison between ARD andBayesian Ridge Regression.

SeeL1-based models for Sparse Signals for a comparison between various methods - Lasso, ARD and ElasticNet - on correlated data.

References

[1]

Christopher M. Bishop: Pattern Recognition and Machine Learning, Chapter 7.2.1

[2]

David Wipf and Srikantan Nagarajan:A New View of Automatic Relevance Determination

[3]

Michael E. Tipping:Sparse Bayesian Learning and the Relevance Vector Machine

[4]

Tristan Fletcher:Relevance Vector Machines Explained

1.1.11.Logistic regression#

The logistic regression is implemented inLogisticRegression. Despiteits name, it is implemented as a linear model for classification rather thanregression in terms of the scikit-learn/ML nomenclature. The logisticregression is also known in the literature as logit regression,maximum-entropy classification (MaxEnt) or the log-linear classifier. In thismodel, the probabilities describing the possible outcomes of a single trialare modeled using alogistic function.

This implementation can fit binary, One-vs-Rest, or multinomial logisticregression with optional\(\ell_1\),\(\ell_2\) or Elastic-Netregularization.

Note

Regularization

Regularization is applied by default, which is common in machinelearning but not in statistics. Another advantage of regularization isthat it improves numerical stability. No regularization amounts tosetting C to a very high value.

Note

Logistic Regression as a special case of the Generalized Linear Models (GLM)

Logistic regression is a special case ofGeneralized Linear Models with a Binomial / Bernoulli conditionaldistribution and a Logit link. The numerical output of the logisticregression, which is the predicted probability, can be used as a classifierby applying a threshold (by default 0.5) to it. This is how it isimplemented in scikit-learn, so it expects a categorical target, makingthe Logistic Regression a classifier.

Examples

1.1.11.1.Binary Case#

For notational ease, we assume that the target\(y_i\) takes values in theset\(\{0, 1\}\) for data point\(i\).Once fitted, thepredict_probamethod ofLogisticRegression predictsthe probability of the positive class\(P(y_i=1|X_i)\) as

\[\hat{p}(X_i) = \operatorname{expit}(X_i w + w_0) = \frac{1}{1 + \exp(-X_i w - w_0)}.\]

As an optimization problem, binaryclass logistic regression with regularization term\(r(w)\) minimizes thefollowing cost function:

(1)#\[\min_{w} \frac{1}{S}\sum_{i=1}^n s_i\left(-y_i \log(\hat{p}(X_i)) - (1 - y_i) \log(1 - \hat{p}(X_i))\right)+ \frac{r(w)}{S C}\,,\]

where\({s_i}\) corresponds to the weights assigned by the user to aspecific training sample (the vector\(s\) is formed by element-wisemultiplication of the class weights and sample weights),and the sum\(S = \sum_{i=1}^n s_i\).

We currently provide four choices for the regularization term\(r(w)\) viathepenalty argument:

penalty

\(r(w)\)

None

\(0\)

\(\ell_1\)

\(\|w\|_1\)

\(\ell_2\)

\(\frac{1}{2}\|w\|_2^2 = \frac{1}{2}w^T w\)

ElasticNet

\(\frac{1 - \rho}{2}w^T w + \rho \|w\|_1\)

For ElasticNet,\(\rho\) (which corresponds to thel1_ratio parameter)controls the strength of\(\ell_1\) regularization vs.\(\ell_2\)regularization. Elastic-Net is equivalent to\(\ell_1\) when\(\rho = 1\) and equivalent to\(\ell_2\) when\(\rho=0\).

Note that the scale of the class weights and the sample weights will influencethe optimization problem. For instance, multiplying the sample weights by aconstant\(b>0\) is equivalent to multiplying the (inverse) regularizationstrengthC by\(b\).

1.1.11.2.Multinomial Case#

The binary case can be extended to\(K\) classes leading to the multinomiallogistic regression, see alsolog-linear model.

Note

It is possible to parameterize a\(K\)-class classification modelusing only\(K-1\) weight vectors, leaving one class probability fullydetermined by the other class probabilities by leveraging the fact that allclass probabilities must sum to one. We deliberately choose to overparameterize the modelusing\(K\) weight vectors for ease of implementation and to preserve thesymmetrical inductive bias regarding ordering of classes, see[16]. This effect becomesespecially important when using regularization. The choice of overparameterization can bedetrimental for unpenalized models since then the solution may not be unique, as shown in[16].

Mathematical details#

Let\(y_i \in \{1, \ldots, K\}\) be the label (ordinal) encoded target variable for observation\(i\).Instead of a single coefficient vector, we now havea matrix of coefficients\(W\) where each row vector\(W_k\) corresponds to class\(k\). We aim at predicting the class probabilities\(P(y_i=k|X_i)\) viapredict_proba as:

\[\hat{p}_k(X_i) = \frac{\exp(X_i W_k + W_{0, k})}{\sum_{l=0}^{K-1} \exp(X_i W_l + W_{0, l})}.\]

The objective for the optimization becomes

\[\min_W -\frac{1}{S}\sum_{i=1}^n \sum_{k=0}^{K-1} s_{ik} [y_i = k] \log(\hat{p}_k(X_i))+ \frac{r(W)}{S C}\,,\]

where\([P]\) represents the Iverson bracket which evaluates to\(0\)if\(P\) is false, otherwise it evaluates to\(1\).

Again,\(s_{ik}\) are the weights assigned by the user (multiplication of sampleweights and class weights) with their sum\(S = \sum_{i=1}^n \sum_{k=0}^{K-1} s_{ik}\).

We currently provide four choicesfor the regularization term\(r(W)\) via thepenalty argument, where\(m\)is the number of features:

penalty

\(r(W)\)

None

\(0\)

\(\ell_1\)

\(\|W\|_{1,1} = \sum_{i=1}^m\sum_{j=1}^{K}|W_{i,j}|\)

\(\ell_2\)

\(\frac{1}{2}\|W\|_F^2 = \frac{1}{2}\sum_{i=1}^m\sum_{j=1}^{K} W_{i,j}^2\)

ElasticNet

\(\frac{1 - \rho}{2}\|W\|_F^2 + \rho \|W\|_{1,1}\)

1.1.11.3.Solvers#

The solvers implemented in the classLogisticRegressionare “lbfgs”, “liblinear”, “newton-cg”, “newton-cholesky”, “sag” and “saga”:

The following table summarizes the penalties and multinomial multiclass supported by each solver:

Solvers

Penalties

‘lbfgs’

‘liblinear’

‘newton-cg’

‘newton-cholesky’

‘sag’

‘saga’

L2 penalty

yes

yes

yes

yes

yes

yes

L1 penalty

no

yes

no

no

no

yes

Elastic-Net (L1 + L2)

no

no

no

no

no

yes

No penalty (‘none’)

yes

no

yes

yes

yes

yes

Multiclass support

multinomial multiclass

yes

no

yes

yes

yes

yes

Behaviors

Penalize the intercept (bad)

no

yes

no

no

no

no

Faster for large datasets

no

no

no

no

yes

yes

Robust to unscaled datasets

yes

yes

yes

yes

no

no

The “lbfgs” solver is used by default for its robustness. Forn_samples>>n_features, “newton-cholesky” is a good choice and can reach highprecision (tinytol values). For large datasetsthe “saga” solver is usually faster (than “lbfgs”), in particular for low precision(hightol).For large dataset, you may also consider usingSGDClassifierwithloss="log_loss", which might be even faster but requires more tuning.

1.1.11.3.1.Differences between solvers#

There might be a difference in the scores obtained betweenLogisticRegression withsolver=liblinear orLinearSVC and the external liblinear library directly,whenfit_intercept=False and the fitcoef_ (or) the data to be predictedare zeroes. This is because for the sample(s) withdecision_function zero,LogisticRegression andLinearSVC predict thenegative class, while liblinear predicts the positive class. Note that a modelwithfit_intercept=False and having many samples withdecision_functionzero, is likely to be an underfit, bad model and you are advised to setfit_intercept=True and increase theintercept_scaling.

Solvers’ details#
  • The solver “liblinear” uses a coordinate descent (CD) algorithm, and relieson the excellent C++LIBLINEAR library, which is shipped withscikit-learn. However, the CD algorithm implemented in liblinear cannot learna true multinomial (multiclass) model; instead, the optimization problem isdecomposed in a “one-vs-rest” fashion so separate binary classifiers aretrained for all classes. This happens under the hood, soLogisticRegression instances using this solver behave as multiclassclassifiers. For\(\ell_1\) regularizationsklearn.svm.l1_min_c allows tocalculate the lower bound for C in order to get a non “null” (all featureweights to zero) model.

  • The “lbfgs”, “newton-cg” and “sag” solvers only support\(\ell_2\)regularization or no regularization, and are found to converge faster for somehigh-dimensional data. Settingmulti_class to “multinomial” with these solverslearns a true multinomial logistic regression model[5], which means that itsprobability estimates should be better calibrated than the default “one-vs-rest”setting.

  • The “sag” solver uses Stochastic Average Gradient descent[6]. It is fasterthan other solvers for large datasets, when both the number of samples and thenumber of features are large.

  • The “saga” solver[7] is a variant of “sag” that also supports thenon-smoothpenalty="l1". This is therefore the solver of choice for sparsemultinomial logistic regression. It is also the only solver that supportspenalty="elasticnet".

  • The “lbfgs” is an optimization algorithm that approximates theBroyden–Fletcher–Goldfarb–Shanno algorithm[8], which belongs toquasi-Newton methods. As such, it can deal with a wide range of different trainingdata and is therefore the default solver. Its performance, however, suffers on poorlyscaled datasets and on datasets with one-hot encoded categorical features with rarecategories.

  • The “newton-cholesky” solver is an exact Newton solver that calculates the Hessianmatrix and solves the resulting linear system. It is a very good choice forn_samples >>n_features and can reach high precision (tiny values oftol),but has a few shortcomings: Only\(\ell_2\) regularization is supported.Furthermore, because the Hessian matrix is explicitly computed, the memory usagehas a quadratic dependency onn_features as well as onn_classes.

For a comparison of some of these solvers, see[9].

References

[5]

Christopher M. Bishop: Pattern Recognition and Machine Learning, Chapter 4.3.4

[6]

Mark Schmidt, Nicolas Le Roux, and Francis Bach:Minimizing Finite Sums with the Stochastic Average Gradient.

[7]

Aaron Defazio, Francis Bach, Simon Lacoste-Julien:SAGA: A Fast Incremental Gradient Method With Support forNon-Strongly Convex Composite Objectives.

[8]

https://en.wikipedia.org/wiki/Broyden%E2%80%93Fletcher%E2%80%93Goldfarb%E2%80%93Shanno_algorithm

[9]

Thomas P. Minka“A comparison of numerical optimizers for logistic regression”

[16](1,2)

Simon, Noah, J. Friedman and T. Hastie.“A Blockwise Descent Algorithm for Group-penalized Multiresponse andMultinomial Regression.”

Note

Feature selection with sparse logistic regression

A logistic regression with\(\ell_1\) penalty yields sparse models, and canthus be used to perform feature selection, as detailed inL1-based feature selection.

Note

P-value estimation

It is possible to obtain the p-values and confidence intervals forcoefficients in cases of regression without penalization. Thestatsmodelspackage natively supports this.Within sklearn, one could use bootstrapping instead as well.

LogisticRegressionCV implements Logistic Regression with built-incross-validation support, to find the optimalC andl1_ratio parametersaccording to thescoring attribute. The “newton-cg”, “sag”, “saga” and“lbfgs” solvers are found to be faster for high-dimensional dense data, dueto warm-starting (seeGlossary).

1.1.12.Generalized Linear Models#

Generalized Linear Models (GLM) extend linear models in two ways[10]. First, the predicted values\(\hat{y}\) are linked to a linearcombination of the input variables\(X\) via an inverse link function\(h\) as

\[\hat{y}(w, X) = h(Xw).\]

Secondly, the squared loss function is replaced by the unit deviance\(d\) of a distribution in the exponential family (or more precisely, areproductive exponential dispersion model (EDM)[11]).

The minimization problem becomes:

\[\min_{w} \frac{1}{2 n_{\text{samples}}} \sum_i d(y_i, \hat{y}_i) + \frac{\alpha}{2} ||w||_2^2,\]

where\(\alpha\) is the L2 regularization penalty. When sample weights areprovided, the average becomes a weighted average.

The following table lists some specific EDMs and their unit deviance :

Distribution

Target Domain

Unit Deviance\(d(y, \hat{y})\)

Normal

\(y \in (-\infty, \infty)\)

\((y-\hat{y})^2\)

Bernoulli

\(y \in \{0, 1\}\)

\(2({y}\log\frac{y}{\hat{y}}+({1}-{y})\log\frac{{1}-{y}}{{1}-\hat{y}})\)

Categorical

\(y \in \{0, 1, ..., k\}\)

\(2\sum_{i \in \{0, 1, ..., k\}} I(y = i) y_\text{i}\log\frac{I(y = i)}{\hat{I(y = i)}}\)

Poisson

\(y \in [0, \infty)\)

\(2(y\log\frac{y}{\hat{y}}-y+\hat{y})\)

Gamma

\(y \in (0, \infty)\)

\(2(\log\frac{\hat{y}}{y}+\frac{y}{\hat{y}}-1)\)

Inverse Gaussian

\(y \in (0, \infty)\)

\(\frac{(y-\hat{y})^2}{y\hat{y}^2}\)

The Probability Density Functions (PDF) of these distributions are illustratedin the following figure,

../_images/poisson_gamma_tweedie_distributions.png

PDF of a random variable Y following Poisson, Tweedie (power=1.5) and Gammadistributions with different mean values (\(\mu\)). Observe the pointmass at\(Y=0\) for the Poisson distribution and the Tweedie (power=1.5)distribution, but not for the Gamma distribution which has a strictlypositive target domain.#

The Bernoulli distribution is a discrete probability distribution modelling aBernoulli trial - an event that has only two mutually exclusive outcomes.The Categorical distribution is a generalization of the Bernoulli distributionfor a categorical random variable. While a random variable in a Bernoullidistribution has two possible outcomes, a Categorical random variable can takeon one of K possible categories, with the probability of each categoryspecified separately.

The choice of the distribution depends on the problem at hand:

  • If the target values\(y\) are counts (non-negative integer valued) orrelative frequencies (non-negative), you might use a Poisson distributionwith a log-link.

  • If the target values are positive valued and skewed, you might try a Gammadistribution with a log-link.

  • If the target values seem to be heavier tailed than a Gamma distribution, youmight try an Inverse Gaussian distribution (or even higher variance powers ofthe Tweedie family).

  • If the target values\(y\) are probabilities, you can use the Bernoullidistribution. The Bernoulli distribution with a logit link can be used forbinary classification. The Categorical distribution with a softmax link can beused for multiclass classification.

Examples of use cases#
  • Agriculture / weather modeling: number of rain events per year (Poisson),amount of rainfall per event (Gamma), total rainfall per year (Tweedie /Compound Poisson Gamma).

  • Risk modeling / insurance policy pricing: number of claim events /policyholder per year (Poisson), cost per event (Gamma), total cost perpolicyholder per year (Tweedie / Compound Poisson Gamma).

  • Credit Default: probability that a loan can’t be paid back (Bernoulli).

  • Fraud Detection: probability that a financial transaction like a cash transferis a fraudulent transaction (Bernoulli).

  • Predictive maintenance: number of production interruption events per year(Poisson), duration of interruption (Gamma), total interruption time per year(Tweedie / Compound Poisson Gamma).

  • Medical Drug Testing: probability of curing a patient in a set of trials orprobability that a patient will experience side effects (Bernoulli).

  • News Classification: classification of news articles into three categoriesnamely Business News, Politics and Entertainment news (Categorical).

References

[10]

McCullagh, Peter; Nelder, John (1989). Generalized Linear Models,Second Edition. Boca Raton: Chapman and Hall/CRC. ISBN 0-412-31760-5.

[11]

Jørgensen, B. (1992). The theory of exponential dispersion modelsand analysis of deviance. Monografias de matemática, no. 51. See alsoExponential dispersion model.

1.1.12.1.Usage#

TweedieRegressor implements a generalized linear model for theTweedie distribution, that allows to model any of the above mentioneddistributions using the appropriatepower parameter. In particular:

  • power=0: Normal distribution. Specific estimators such asRidge,ElasticNet are generally more appropriate inthis case.

  • power=1: Poisson distribution.PoissonRegressor is exposedfor convenience. However, it is strictly equivalent toTweedieRegressor(power=1,link='log').

  • power=2: Gamma distribution.GammaRegressor is exposed forconvenience. However, it is strictly equivalent toTweedieRegressor(power=2,link='log').

  • power=3: Inverse Gaussian distribution.

The link function is determined by thelink parameter.

Usage example:

>>>fromsklearn.linear_modelimportTweedieRegressor>>>reg=TweedieRegressor(power=1,alpha=0.5,link='log')>>>reg.fit([[0,0],[0,1],[2,2]],[0,1,2])TweedieRegressor(alpha=0.5, link='log', power=1)>>>reg.coef_array([0.2463, 0.4337])>>>reg.intercept_np.float64(-0.7638)

Examples

Practical considerations#

The feature matrixX should be standardized before fitting. This ensuresthat the penalty treats features equally.

Since the linear predictor\(Xw\) can be negative and Poisson,Gamma and Inverse Gaussian distributions don’t support negative values, itis necessary to apply an inverse link function that guarantees thenon-negativeness. For example withlink='log', the inverse link functionbecomes\(h(Xw)=\exp(Xw)\).

If you want to model a relative frequency, i.e. counts per exposure (time,volume, …) you can do so by using a Poisson distribution and passing\(y=\frac{\mathrm{counts}}{\mathrm{exposure}}\) as target valuestogether with\(\mathrm{exposure}\) as sample weights. For a concreteexample see e.g.Tweedie regression on insurance claims.

When performing cross-validation for thepower parameter ofTweedieRegressor, it is advisable to specify an explicitscoring function,because the default scorerTweedieRegressor.score is a function ofpower itself.

1.1.13.Stochastic Gradient Descent - SGD#

Stochastic gradient descent is a simple yet very efficient approachto fit linear models. It is particularly useful when the number of samples(and the number of features) is very large.Thepartial_fit method allows online/out-of-core learning.

The classesSGDClassifier andSGDRegressor providefunctionality to fit linear models for classification and regressionusing different (convex) loss functions and different penalties.E.g., withloss="log",SGDClassifierfits a logistic regression model,while withloss="hinge" it fits a linear support vector machine (SVM).

You can refer to the dedicatedStochastic Gradient Descent documentation section for more details.

1.1.14.Perceptron#

ThePerceptron is another simple classification algorithm suitable forlarge scale learning. By default:

  • It does not require a learning rate.

  • It is not regularized (penalized).

  • It updates its model only on mistakes.

The last characteristic implies that the Perceptron is slightly faster totrain than SGD with the hinge loss and that the resulting models aresparser.

In fact, thePerceptron is a wrapper around theSGDClassifierclass using a perceptron loss and a constant learning rate. Refer tomathematical section of the SGD procedurefor more details.

1.1.15.Passive Aggressive Algorithms#

The passive-aggressive algorithms are a family of algorithms for large-scalelearning. They are similar to the Perceptron in that they do not require alearning rate. However, contrary to the Perceptron, they include aregularization parameterC.

For classification,PassiveAggressiveClassifier can be used withloss='hinge' (PA-I) orloss='squared_hinge' (PA-II). For regression,PassiveAggressiveRegressor can be used withloss='epsilon_insensitive' (PA-I) orloss='squared_epsilon_insensitive' (PA-II).

References#

1.1.16.Robustness regression: outliers and modeling errors#

Robust regression aims to fit a regression model in thepresence of corrupt data: either outliers, or error in the model.

../_images/sphx_glr_plot_theilsen_001.png

1.1.16.1.Different scenario and useful concepts#

There are different things to keep in mind when dealing with datacorrupted by outliers:

  • Outliers in X or in y?

    Outliers in the y direction

    Outliers in the X direction

    y_outliers

    X_outliers

  • Fraction of outliers versus amplitude of error

    The number of outlying points matters, but also how much they areoutliers.

    Small outliers

    Large outliers

    y_outliers

    large_y_outliers

An important notion of robust fitting is that of breakdown point: thefraction of data that can be outlying for the fit to start missing theinlying data.

Note that in general, robust fitting in high-dimensional setting (largen_features) is very hard. The robust models here will probably not workin these settings.

Trade-offs: which estimator ?

Scikit-learn provides 3 robust regression estimators:RANSAC,Theil Sen andHuberRegressor.

  • HuberRegressor should be faster thanRANSAC andTheil Senunless the number of samples is very large, i.e.n_samples >>n_features.This is becauseRANSAC andTheil Senfit on smaller subsets of the data. However, bothTheil SenandRANSAC are unlikely to be as robust asHuberRegressor for the default parameters.

  • RANSAC is faster thanTheil Senand scales much better with the number of samples.

  • RANSAC will deal better with largeoutliers in the y direction (most common situation).

  • Theil Sen will cope better withmedium-size outliers in the X direction, but this property willdisappear in high-dimensional settings.

When in doubt, useRANSAC.

1.1.16.2.RANSAC: RANdom SAmple Consensus#

RANSAC (RANdom SAmple Consensus) fits a model from random subsets ofinliers from the complete data set.

RANSAC is a non-deterministic algorithm producing only a reasonable result witha certain probability, which is dependent on the number of iterations (seemax_trials parameter). It is typically used for linear and non-linearregression problems and is especially popular in the field of photogrammetriccomputer vision.

The algorithm splits the complete input sample data into a set of inliers,which may be subject to noise, and outliers, which are e.g. caused by erroneousmeasurements or invalid hypotheses about the data. The resulting model is thenestimated only from the determined inliers.

../_images/sphx_glr_plot_ransac_001.png

Examples

Details of the algorithm#

Each iteration performs the following steps:

  1. Selectmin_samples random samples from the original data and checkwhether the set of data is valid (seeis_data_valid).

  2. Fit a model to the random subset (estimator.fit) and checkwhether the estimated model is valid (seeis_model_valid).

  3. Classify all data as inliers or outliers by calculating the residualsto the estimated model (estimator.predict(X)-y) - all datasamples with absolute residuals smaller than or equal to theresidual_threshold are considered as inliers.

  4. Save fitted model as best model if number of inlier samples ismaximal. In case the current estimated model has the same number ofinliers, it is only considered as the best model if it has better score.

These steps are performed either a maximum number of times (max_trials) oruntil one of the special stop criteria are met (seestop_n_inliers andstop_score). The final model is estimated using all inlier samples (consensusset) of the previously determined best model.

Theis_data_valid andis_model_valid functions allow to identify and rejectdegenerate combinations of random sub-samples. If the estimated model is notneeded for identifying degenerate cases,is_data_valid should be used as itis called prior to fitting the model and thus leading to better computationalperformance.

References#

1.1.16.3.Theil-Sen estimator: generalized-median-based estimator#

TheTheilSenRegressor estimator uses a generalization of the median inmultiple dimensions. It is thus robust to multivariate outliers. Note howeverthat the robustness of the estimator decreases quickly with the dimensionalityof the problem. It loses its robustness properties and becomes nobetter than an ordinary least squares in high dimension.

Examples

Theoretical considerations#

TheilSenRegressor is comparable to theOrdinary Least Squares(OLS) in terms of asymptotic efficiency and as anunbiased estimator. In contrast to OLS, Theil-Sen is a non-parametricmethod which means it makes no assumption about the underlyingdistribution of the data. Since Theil-Sen is a median-based estimator, itis more robust against corrupted data aka outliers. In univariatesetting, Theil-Sen has a breakdown point of about 29.3% in case of asimple linear regression which means that it can tolerate arbitrarycorrupted data of up to 29.3%.

../_images/sphx_glr_plot_theilsen_001.png

The implementation ofTheilSenRegressor in scikit-learn follows ageneralization to a multivariate linear regression model[14] using thespatial median which is a generalization of the median to multipledimensions[15].

In terms of time and space complexity, Theil-Sen scales according to

\[\binom{n_{\text{samples}}}{n_{\text{subsamples}}}\]

which makes it infeasible to be applied exhaustively to problems with alarge number of samples and features. Therefore, the magnitude of asubpopulation can be chosen to limit the time and space complexity byconsidering only a random subset of all possible combinations.

References

[14]

Xin Dang, Hanxiang Peng, Xueqin Wang and Heping Zhang:Theil-Sen Estimators in a Multiple Linear Regression Model.

[15]
  1. Kärkkäinen and S. Äyrämö:On Computation of Spatial Median for Robust Data Mining.

Also see theWikipedia page

1.1.16.4.Huber Regression#

TheHuberRegressor is different fromRidge because it applies alinear loss to samples that are defined as outliers by theepsilon parameter.A sample is classified as an inlier if the absolute error of that sample isless than the thresholdepsilon. It differs fromTheilSenRegressorandRANSACRegressor because it does not ignore the effect of the outliersbut gives a lesser weight to them.

../_images/sphx_glr_plot_huber_vs_ridge_001.png

Examples

Mathematical details#

HuberRegressor minimizes

\[\min_{w, \sigma} {\sum_{i=1}^n\left(\sigma + H_{\epsilon}\left(\frac{X_{i}w - y_{i}}{\sigma}\right)\sigma\right) + \alpha {||w||_2}^2}\]

where the loss function is given by

\[\begin{split}H_{\epsilon}(z) = \begin{cases} z^2, & \text {if } |z| < \epsilon, \\ 2\epsilon|z| - \epsilon^2, & \text{otherwise}\end{cases}\end{split}\]

It is advised to set the parameterepsilon to 1.35 to achieve 95%statistical efficiency.

References

  • Peter J. Huber, Elvezio M. Ronchetti: Robust Statistics, Concomitant scaleestimates, p. 172.

TheHuberRegressor differs from usingSGDRegressor with loss set tohuberin the following ways.

  • HuberRegressor is scaling invariant. Onceepsilon is set, scalingX andydown or up by different values would produce the same robustness to outliers as before.as compared toSGDRegressor whereepsilon has to be set again whenX andy arescaled.

  • HuberRegressor should be more efficient to use on data with small number ofsamples whileSGDRegressor needs a number of passes on the training data toproduce the same robustness.

Note that this estimator is different from theR implementation of RobustRegression because the Rimplementation does a weighted least squares implementation with weights given to eachsample on the basis of how much the residual is greater than a certain threshold.

1.1.17.Quantile Regression#

Quantile regression estimates the median or other quantiles of\(y\)conditional on\(X\), while ordinary least squares (OLS) estimates theconditional mean.

Quantile regression may be useful if one is interested in predicting aninterval instead of point prediction. Sometimes, prediction intervals arecalculated based on the assumption that prediction error is distributednormally with zero mean and constant variance. Quantile regression providessensible prediction intervals even for errors with non-constant (butpredictable) variance or non-normal distribution.

../_images/sphx_glr_plot_quantile_regression_002.png

Based on minimizing the pinball loss, conditional quantiles can also beestimated by models other than linear models. For example,GradientBoostingRegressor can predict conditionalquantiles if its parameterloss is set to"quantile" and parameteralpha is set to the quantile that should be predicted. See the example inPrediction Intervals for Gradient Boosting Regression.

Most implementations of quantile regression are based on linear programmingproblem. The current implementation is based onscipy.optimize.linprog.

Examples

Mathematical details#

As a linear model, theQuantileRegressor gives linear predictions\(\hat{y}(w, X) = Xw\) for the\(q\)-th quantile,\(q \in (0, 1)\).The weights or coefficients\(w\) are then found by the followingminimization problem:

\[\min_{w} {\frac{1}{n_{\text{samples}}}\sum_i PB_q(y_i - X_i w) + \alpha ||w||_1}.\]

This consists of the pinball loss (also known as linear loss),see alsomean_pinball_loss,

\[\begin{split}PB_q(t) = q \max(t, 0) + (1 - q) \max(-t, 0) =\begin{cases} q t, & t > 0, \\ 0, & t = 0, \\ (q-1) t, & t < 0\end{cases}\end{split}\]

and the L1 penalty controlled by parameteralpha, similar toLasso.

As the pinball loss is only linear in the residuals, quantile regression ismuch more robust to outliers than squared error based estimation of the mean.Somewhat in between is theHuberRegressor.

References#

1.1.18.Polynomial regression: extending linear models with basis functions#

One common pattern within machine learning is to use linear models trainedon nonlinear functions of the data. This approach maintains the generallyfast performance of linear methods, while allowing them to fit a much widerrange of data.

Mathematical details#

For example, a simple linear regression can be extended by constructingpolynomial features from the coefficients. In the standard linearregression case, you might have a model that looks like this fortwo-dimensional data:

\[\hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2\]

If we want to fit a paraboloid to the data instead of a plane, we can combinethe features in second-order polynomials, so that the model looks like this:

\[\hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2 + w_3 x_1 x_2 + w_4 x_1^2 + w_5 x_2^2\]

The (sometimes surprising) observation is that this isstill a linear model:to see this, imagine creating a new set of features

\[z = [x_1, x_2, x_1 x_2, x_1^2, x_2^2]\]

With this re-labeling of the data, our problem can be written

\[\hat{y}(w, z) = w_0 + w_1 z_1 + w_2 z_2 + w_3 z_3 + w_4 z_4 + w_5 z_5\]

We see that the resultingpolynomial regression is in the same class oflinear models we considered above (i.e. the model is linear in\(w\))and can be solved by the same techniques. By considering linear fits withina higher-dimensional space built with these basis functions, the model has theflexibility to fit a much broader range of data.

Here is an example of applying this idea to one-dimensional data, usingpolynomial features of varying degrees:

../_images/sphx_glr_plot_polynomial_interpolation_001.png

This figure is created using thePolynomialFeatures transformer, whichtransforms an input data matrix into a new data matrix of a given degree.It can be used as follows:

>>>fromsklearn.preprocessingimportPolynomialFeatures>>>importnumpyasnp>>>X=np.arange(6).reshape(3,2)>>>Xarray([[0, 1],       [2, 3],       [4, 5]])>>>poly=PolynomialFeatures(degree=2)>>>poly.fit_transform(X)array([[ 1.,  0.,  1.,  0.,  0.,  1.],       [ 1.,  2.,  3.,  4.,  6.,  9.],       [ 1.,  4.,  5., 16., 20., 25.]])

The features ofX have been transformed from\([x_1, x_2]\) to\([1, x_1, x_2, x_1^2, x_1 x_2, x_2^2]\), and can now be used withinany linear model.

This sort of preprocessing can be streamlined with thePipeline tools. A single object representing a simplepolynomial regression can be created and used as follows:

>>>fromsklearn.preprocessingimportPolynomialFeatures>>>fromsklearn.linear_modelimportLinearRegression>>>fromsklearn.pipelineimportPipeline>>>importnumpyasnp>>>model=Pipeline([('poly',PolynomialFeatures(degree=3)),...('linear',LinearRegression(fit_intercept=False))])>>># fit to an order-3 polynomial data>>>x=np.arange(5)>>>y=3-2*x+x**2-x**3>>>model=model.fit(x[:,np.newaxis],y)>>>model.named_steps['linear'].coef_array([ 3., -2.,  1., -1.])

The linear model trained on polynomial features is able to exactly recoverthe input polynomial coefficients.

In some cases it’s not necessary to include higher powers of any single feature,but only the so-calledinteraction featuresthat multiply together at most\(d\) distinct features.These can be gotten fromPolynomialFeatures with the settinginteraction_only=True.

For example, when dealing with boolean features,\(x_i^n = x_i\) for all\(n\) and is therefore useless;but\(x_i x_j\) represents the conjunction of two booleans.This way, we can solve the XOR problem with a linear classifier:

>>>fromsklearn.linear_modelimportPerceptron>>>fromsklearn.preprocessingimportPolynomialFeatures>>>importnumpyasnp>>>X=np.array([[0,0],[0,1],[1,0],[1,1]])>>>y=X[:,0]^X[:,1]>>>yarray([0, 1, 1, 0])>>>X=PolynomialFeatures(interaction_only=True).fit_transform(X).astype(int)>>>Xarray([[1, 0, 0, 0],       [1, 0, 1, 0],       [1, 1, 0, 0],       [1, 1, 1, 1]])>>>clf=Perceptron(fit_intercept=False,max_iter=10,tol=None,...shuffle=False).fit(X,y)

And the classifier “predictions” are perfect:

>>>clf.predict(X)array([0, 1, 1, 0])>>>clf.score(X,y)1.0
On this page

This Page