visit
Linear regression is a common machine learning technique that predicts a real-valued output using a weighted linear combination of one or more input values. For instance, the sale price of a house can often be estimated using a linear combination of features such as area, number of bedrooms, number of floors, date of construction etc. Mathematically, it can be expressed using the following equation: house_price = w1 * area + w2 * n_bedrooms + w3 * n_floors + ... + w_n * age_in_years + b
The “learning” part of linear regression is to figure out a set of weights w1, w2, w3, ... w_n, b
that leads to good predictions. This is done by looking at lots of examples one by one (or in batches) and adjusting the weights slightly each time to make better predictions, using an optimization technique called .
Let’s create some sample data with one feature x
(e.g. floor area) and one dependent variable y
(e.g. house price). We’ll assume that y
is a linear function of x
, with some noise added to account for features we haven’t considered here. Here’s how we generate the data points, or samples:
Now we can define and instantiate a linear regression model in PyTorch:
def forward(self, x):
out = self.linear(x)
return out
As you can see, it’s quite far from the desired result. Now we can define a utility function to run a training epoch:
# Clear the gradients w.r.t. parameters
optimizer.zero\_grad()
# Forward to get the outputs
outputs = model(inputs)
# Calcuate loss
loss = criterion(outputs, labels)
# Getting gradients from parameters
loss.backward()
# Updating parameters
optimizer.step()
return loss
Next, we can train the model and update the state of a animated graph at the end of each epoch:
That’s it! It takes about 200 epochs for the model to come quite close to the best fit line. The complete code for this post can be found in this Jupyter notebook: