Multi-Variate Linear Regression

Rishabh Roy
Jun 20, 2020 · 10 min read

This is quite similar to the simple linear regression model or Uni-Variate linear regression model (Click here if you haven't checked my blog on Uni-variate linear regression) , but with multiple independent variables contributing to the dependent variable and hence multiple coefficients to determine and complex computation due to the added variables.

In a simple linear regression model, a dependent variable guided by a single independent variable is a good start but of very less use in real world scenarios. Generally one dependent variable depends on multiple factors. For example, the rent of a house depends on many factors like the neighbourhood it is in, size of it, no.of rooms, attached facilities, distance of nearest station from it, distance of nearest shopping area from it, etc. How do we deal with such scenarios? Let’s jump into multivariate linear regression and figure this out.

The equation of multivariate linear regression is

Image for post
Image for post

Yi is the estimate of i component of dependent variable y, where we have n independent variables and x denotes the i component of the j independent variable/feature.

Lets Start…

We’ll create a model that predicts crop yields for apples and oranges (target variables) by looking at the average temperature, rainfall and humidity (input variables or features) in a region. Here’s the training data:

Image for post
Image for post

Yes, this is a Pokemon reference.

In a linear regression model, each target variable is estimated to be a weighted sum of the input variables, offset by some constant, known as a bias :

yield_apple = w11 * temp + w12 * rainfall + w13 * humidity + b1

yield_orange = w21 * temp + w22 * rainfall + w23 * humidity + b2

Visually, it means that the yield of apples is a linear or planar function of temperature, rainfall and humidity:

Image for post
Image for post

The learning part of linear regression is to figure out a set of weights w11, w12,… w23, b1 & b2 by looking at the training data, to make accurate predictions for new data (i.e. to predict the yields for apples and oranges in a new region using the average temperature, rainfall and humidity). This is done by adjusting the weights slightly many times to make better predictions, using an optimisation technique called gradient descent.

We begin by importing Numpy and PyTorch:

Training data

The training data can be represented using 2 matrices: inputs and targets, each with one row per observation, and one column per variable.

We’ve separated the input and target variables, because we’ll operate on them separately. Also, we’ve created numpy arrays, because this is typically how you would work with training data: read some CSV files as numpy arrays, do some processing, and then convert them to PyTorch tensors as follows:

Linear regression model from scratch

The weights and biases (w11, w12,… w23, b1 & b2) can also be represented as matrices, initialised as random values. The first row of w and the first element of b are used to predict the first target variable i.e. yield of apples, and similarly the second for oranges.

torch.randn creates a tensor with the given shape, with elements picked randomly from a normal distribution with mean 0 and standard deviation 1.

Our model is simply a function that performs a matrix multiplication of the inputs and the weights w (transposed) and adds the bias b (replicated for each observation).

Image for post
Image for post

We can define the model as follows:

@ represents matrix multiplication in PyTorch, and the .t method returns the transpose of a tensor.

The matrix obtained by passing the input data into the model is a set of predictions for the target variables.

Let’s compare the predictions of our model with the actual targets.

You can see that there’s a huge difference between the predictions of our model, and the actual values of the target variables. Obviously, this is because we’ve initialised our model with random weights and biases, and we can’t expect it to just work.

Loss function

Before we improve our model, we need a way to evaluate how well our model is performing. We can compare the model’s predictions with the actual targets, using the following method:

The result is a single number, known as the mean squared error (MSE).

torch.sum returns the sum of all the elements in a tensor, and the .numel method returns the number of elements in a tensor. Let’s compute the mean squared error for the current predictions of our model.

Here’s how we can interpret the result: On average, each element in the prediction differs from the actual target by about 100–120 (square root of the loss 17960…). And that’s pretty bad, considering the numbers we are trying to predict are themselves in the range 50–200. Also, the result is called the loss, because it indicates how bad the model is at predicting the target variables. Lower the loss, better the model.

Compute gradients

With PyTorch, we can automatically compute the gradient or derivative of the loss w.r.t. to the weights and biases, because they have requires_grad set to True.

The gradients are stored in the .grad property of the respective tensors. Note that the derivative of the loss w.r.t. the weights matrix is itself a matrix, with the same dimensions.

The loss is a quadratic function of our weights and biases, and our objective is to find the set of weights where the loss is the lowest. If we plot a graph of the loss w.r.t any individual weight or bias element, it will look like the figure shown below. A key insight from calculus is that the gradient indicates the rate of change of the loss, or the slope of the loss function w.r.t. the weights and biases.

If a gradient element is positive:

Image for post
Image for post

If a gradient element is negative:

Image for post
Image for post

The increase or decrease in loss by changing a weight element is proportional to the value of the gradient of the loss w.r.t. that element. This forms the basis for the optimisation algorithm that we’ll use to improve our model.

Before we proceed, we reset the gradients to zero by calling .zero_() method. We need to do this, because PyTorch accumulates, gradients i.e. the next time we call .backward on the loss, the new gradient values will get added to the existing gradient values, which may lead to unexpected results.

Adjust weights and biases using gradient descent
We’ll reduce the loss and improve our model using the gradient descent optimisation algorithm, which has the following steps:

Generate predictions

Calculate the loss

Compute gradients w.r.t the weights and biases

Adjust the weights by subtracting a small quantity proportional to the gradient

Reset the gradients to zero

Let’s implement the above step by step.

Note that the predictions are same as before, since we haven’t made any changes to our model. The same holds true for the loss and gradients.

Finally, we update the weights and biases using the gradients computed above.

A few things to note above:

We use torch.no_grad to indicate to PyTorch that we shouldn’t track, calculate or modify gradients while updating the weights and biases.

We multiply the gradients with a really small number (10^-5 in this case), to ensure that we don’t modify the weights by a really large amount, since we only want to take a small step in the downhill direction of the gradient. This number is called the learning rate of the algorithm.

After we have updated the weights, we reset the gradients back to zero, to avoid affecting any future computations.

Let’s take a look at the new weights and biases.

With the new weights and biases, the model should have lower loss.

We have already achieved a significant reduction in the loss, simply by adjusting the weights and biases slightly using gradient descent.

Train for multiple epochs

To reduce the loss further, we can repeat the process of adjusting the weights and biases using the gradients multiple times. Each iteration is called an epoch. Let’s train the model for 100 epochs.

Once again, let’s verify that the loss is now lower:

As you can see, the loss is now much lower than what we started out with. Let’s look at the model’s predictions and compare them with the targets.

The prediction are now quite close to the target variables, and we can get even better results by training for a few more epochs.

Linear regression using PyTorch built-ins

The model and training process above were implemented using basic matrix operations. But since this such a common pattern , PyTorch has several built-in functions and classes to make it easy to create and train models.

Let’s begin by importing the torch.nn package from PyTorch, which contains utility classes for building neural networks.

As before, we represent the inputs and targets and matrices.

We are using 15 training examples this time, to illustrate how to work with large datasets in small batches.

Dataset and DataLoader

We’ll create a TensorDataset, which allows access to rows from inputs and targets as tuples, and provides standard APIs for working with many different types of datasets in PyTorch.

The TensorDataset allows us to access a small section of the training data using the array indexing notation ([0:3] in the above code). It returns a tuple (or pair), in which the first element contains the input variables for the selected rows, and the second contains the targets.

We’ll also create a DataLoader, which can split the data into batches of a predefined size while training. It also provides other utilities like shuffling and random sampling of the data.

The data loader is typically used in a for-in loop. Let’s look at an example.

In each iteration, the data loader returns one batch of data, with the given batch size. If shuffle is set to True, it shuffles the training data before creating batches. Shuffling helps randomise the input to the optimisation algorithm, which can lead to faster reduction in the loss.

nn.Linear

Instead of initializing the weights & biases manually, we can define the model using the nn.Linear class from PyTorch, which does it automatically.

PyTorch models also have a helpful .parameters method, which returns a list containing all the weights and bias matrices present in the model. For our linear regression model, we have one weight matrix and one bias matrix.

We can use the model to generate predictions in the exact same way as before:

Loss Function

Instead of defining a loss function manually, we can use the built-in loss function mse_loss.

The nn.functional package contains many useful loss functions and several other utilities.

Let’s compute the loss for the current predictions of our model.

Optimizer

Instead of manually manipulating the model’s weights & biases using gradients, we can use the optimizer optim.SGD. SGD stands for stochastic gradient descent. It is called stochastic because samples are selected in batches (often with random shuffling) instead of as a single group.

Note that model.parameters() is passed as an argument to optim.SGD, so that the optimizer knows which matrices should be modified during the update step. Also, we can specify a learning rate which controls the amount by which the parameters are modified.

Train the model

We are now ready to train the model. We’ll follow the exact same process to implement gradient descent:

Generate predictions

Calculate the loss

Compute gradients w.r.t the weights and biases

Adjust the weights by subtracting a small quantity proportional to the gradient

Reset the gradients to zero

The only change is that we’ll work batches of data, instead of processing the entire training data in every iteration. Let’s define a utility function fit which trains the model for a given number of epochs.

Some things to note above:

We use the data loader defined earlier to get batches of data for every iteration.

Instead of updating parameters (weights and biases) manually, we use opt.step to perform the update, and opt.zero_grad to reset the gradients to zero.

We’ve also added a log statement which prints the loss from the last batch of data for every 10th epoch, to track the progress of training. loss.item returns the actual value stored in the loss tensor.

Let’s train the model for 100 epochs.

Let’s generate predictions using our model and verify that they’re close to our targets.

Indeed, the predictions are quite close to our targets, and now we have a fairly good model to predict crop yields for apples and oranges by looking at the average temperature, rainfall and humidity in a region.

The Startup

Medium's largest active publication, followed by +756K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store