Linear Regression

Ordinary Least Squares

Given dataset of datapoints (where ) and corresponding labels , we essentially learn a vector of weights and a scalar bias such that:

where denotes the predicted output of our linear model. Notice that the bias can be included into the weights if the corresponding dimension of the features is , which essentially compresses the expression to:

where is now a matrix with the first column being a vector of ones.

We can consider these as a system of linear equations. As we know a linear system may be consistent or inconsistent. In the former case where , solutions do exist, however the model overfits (memorizes the training data). This is undesirable since the model does not generalize well to new examples. In the latter case however, we don’t have unique solutions. For most practical purposes, leading the system to be inconsistent. So, what can we do?

We can think of a few ways to solve this problem:

  1. We can simply take , however since is not invertible (), this is not possible.
  2. In that case, we can take the Moore-Penrose pseudo-inverse of . Let the Singular Value Decomposition (SVD) of where is the eigen vectors of , is the eigen vectors of , and is the diagonal matrix of singular values which are the square roots of the eigenvalues of . Then,

However, the eigenvalue and eigenvector calculation requires a lot of computations. Can we think of a way to reduce the computations?

Insert Image

We can think of the plane as the column space spanned by the dataset , and we can assume that the ground truth targets lie outside the plane. We can then take the projection of the ground truth labels to the plane, that should correspond to the predicted labels. Recall that the predicted labels were calculated as . Therefore the vector should lie in the column space of . We can estimate the weights in the following 2 ways:

Method 1 (ERM)

Our aim is to minimize the empirical risk, which we can do by minimizing the error. We notice that the error is given by the differences of the actual label and the predicted label . We can take the squared differences (since square is a monotonically increasing function in the range ) and sum them up across all the datapoints in the dataset to get the loss function:

This objective is popularly known as the “mean squared error” (MSE). However, since the loss has to be calculated over the entire dataset, we can always write it in the vectorized form:

where is the norm. Now, in order to minimize the loss, we can take the gradient with respect to :

Taking the Hessian, we get:

which is positive definite (assuming full rank, i.e. rank is ), thus if we equate the gradient of the loss to 0, we should obtain the minima:

Note that the inverse of the matrix is not possible unless it is full rank, and hence our previous assumption was reasonable.

Method 2 (Projection)

Alternatively, we can directly calculate the projection of the ground truth labels to the plane. The error of can be expressed as . Since we know that the vector is perpendicular to the plane , we get the following relation:


Iterative Methods for Linear Regression

We notice that the operation takes computations, which can be costly if D is large. Also itself requires FLOPs to compute, which can be costly since N is often very high. Hence it would be useful if we had a way to optimize the parameters without the requirement of inverting the matrix.

We can use the Gradient Descent or Stochastic Gradient Descent (SGD) to optimize the parameters when N is large. Let be the loss function, then:

Gradient Descent:

  1. Initialize
  2. while :

In Gradient descent, notice that the gradient is calculated for the entire dataset. However, that might also be computationally expensive. Hence, we can use Stochastic Gradient Descent.

Stochastic Gradient Descent:

  1. Initialize
  2. while :

However, this requires us to compute the gradient for each datapoint, which might not be a good estimate of the gradient. Hence, we can use Mini-Batch Gradient Descent which is a tradeoff between the above two methods and the batch size can be chosen depending on the availability of RAM.

Mini-Batch Gradient Descent:

  1. Initialize
  2. while :

In our case, the loss function and the gradient is given by i.e. .


Aside (Data pre-processing):

We saw that in linear regression, the each feature is multiplied with the corresponding weight (). Now in case that the units are very different, the linear regression will not give very useful results. For instance, say the height and weight of a person is used to predict age. So, the height and weight are the features respectively, and the age is the target . Now, suppose that the features are in SI units, which means that the height is in meters and the weight is in kilograms. Say a person weighs 1.5m and weighs 50kg. Therefore: . Notice that the height of the person will be given less weightage since the weight (in SI units) dominates. Ideally this can be resolved by learning a very low that can compensate for the high value of weight, it’s not a good idea (more details in regularization). We can alternatively scale the dataset (feature-wise) to ensure that the units are in the same scale as follows:

  1. Normalization: Let be the minimum value of the datapoints along the feature column, and similarly be the maximum value. Then:
  2. Standardization: Let be the average value of the datapoints along the feature column, and similarly let be the square root of the sample variance. Then:

Note: that the nomenclature might slightly confusing, so rather it’s easier to remember the former as min-max scaling, while the later can be thought of as scaling the features as if they were sampled from isotropic standard Gaussian distributions each.


Probabilistic Perspective of Linear Regression

Assume that the dataset was generated using the following process:

where . For simplicity, we can assume unidimensional , which in turn makes .

insert image

Taking expectation we get:

Which means that: if we model as , then we should be fine because in expectation we will be getting no errors. We can reparameterize by assuming that the is generated from a Gaussian with mean and variance . Thus the likelihood of given is:

And consequently, the log likelihood is:

Therefore, the log likelihood of the dataset is:

which is same as the loss function in the previous section (equation ). This is easily extendable to the multi-variate case.


Regularized Linear Regression

We can Impose a prior on the weights, and get the aposteriori estimates. Let’s assume .

where . In the multivariate case, we have:

This is known as -regularized regression or Ridge regression and the can be considered as a hyper-parameter controlling the degree of regularization.

Taking the gradient of the loss w.r.t. and equating it to zero, we get:

Notice that unlike , the matrix is positive definite and therefore invertible without any additional assumptions.

Why regularize?

The objective of regularization is to constrain the parameters in a certain way. Regularization is often used to deal with the problem of overfitting in high capacity (over-parameterized) models.

  1. L Regularization: We constrain the norm of the parameters, which results in parameters bering “small” dimension wise. In the ridge regression (assuming appropriate scaling has been performed on the dataset), notice that the regularization can be interpreted as roughly giving equal importance to each feature. We can rewrite the loss as Total loss = Reconstruction loss + Regularization, where: Reconstruction loss: , and Regularization: Consequently, if any feature (say ) gets more weightage, i.e. the corresponding is high, then it must justify itself by reducing the loss function by the corresponding increase. For instance, let be the original value and be the new value such that , then let . The penalty for change from to is . If the change is small, we can say that the penalty . Similarly, the corresponding reduction in the reconstruction loss where is the column of the dataset . Increasing by will only happen if this reconstruction term compensates for the corresponding penalty.
  2. L Regularization: An alternate approach is to select a subset of features which can explain the data. In many datasets, there are lots of features. Since inference takes time (due to the inner product computation), reducing the number of features that is used for the linear regression model reduces the inference time. For instance, gene expression datasets have a very high number of features, and both training and inference time can benefit from the modeling using a subset of features. However, subset selection is np-hard and hence L-regularization is computationally intractable.
  3. L Regularization: We can relax the L Regularization to L Regularization which gives us an approximate solution to the subset selection problem.

Implementation details: Upon convergence, often has some dimensions where the values are extremely low . We can remove those features from the dataset as they are not very important and removing them reduces the size of the model, thus speeding up inference time when deployed.


Logistic Regression

insert image

The logit function/transform:

The logistic regression is used for classification. Say we have two classes, and each items belong to these classes . We can transform the output of the linear model into a conditional probability mass corresponding to each class by applying the logit transform.

and

Therefore, Likelihood of given : Likelihood of dataset: Log Likelihood of dataset: Notice that in the log likelihood, when the first term is non-zero and the second term is zero (due to the multiplication in the front), and similarly when , the second term is non-zero and the first term is zero.

Maximizing the log likelihood is equivalent to minimizing the negative of the log likelihood. Therefore: Negative log likelihood loss (NLL Loss)

This formulation of NLL Loss is also known as the Binary Cross Entropy Loss. Replacing , we get:

Regularization:

Similar to linear regression, we can regularize logistic regression by constraining the weights as follows:

Generalize to multi-class classification:

Let there be number of classes in which a datapoint can belong. One way to extend a binary classifier to multiple classes is to simply train different parallel models each modeling the probability of the datapoints belonging to one of the classes. We can relabel the such that if else , and then train a binary logistic regression classifier using the new as the ground truth. During inference, we have different models. Notice that each model is a vector. So, we can indicate the linear models as a matrix . Therefore upon performing , we will get a matrix as output. For each sample (row), we can simply predict the index corresponding to the maximum value as the class label. This method is known as One vs All (OVA) or One vs Rest (OVR) classifier.

Additionally, for each row, we can compute the softmax of the outputs to obtain a probability distribution of the sample belonging to a given class. Let the output for by the OVA model be which is a dimensional vector. Then the probability is:


Additional Topics

Weighted Linear Regression

Let’s consider a dataset , where are the features, are the labels, and are the weighing factor, i.e. some datapoints are given more weights than others (similar to policy gradient algorithms in reinforcement learning). Then the ERM objective is:

where is a diagonal matrix with on the diagonal.

Upon taking the gradient of the loss, we get:

Equating to zero, we get:

Comments on NLL Loss

Let the label for a given datapoint be a one hot vector with the index being if the label of is . So, for the given datapoint , (cross entropy) loss is:

where represents the column of the matrix , i.e. the linear model. Note that entropy is defined as

Minimizing negative log likelihood is same as minimizing the KL divergence between the data distribution and the distribution predicted by the model.

Learned distribution: Data distribution:

KL Divergence:

The former term is the entropy which is independent of and the latter term is the cross-entropy which is dependent on .

Which is essentially the NLL Loss. It is for this reason that the NLL Loss for categorical variables is also known as the Categorical Cross Entropy Loss. can be written as the indicator since in the dataset we have no uncertainty, i.e. we know the ground truth for every .