Source: https://medium.com/dsnet/linear-regression-with-pytorch-3dde91d60b50

Original title: Linear Regression and Gradient Descent from scratch in PyTorch

library(rTorch)

Linear Regression Model using PyTorch built-ins

Let’s re-implement the same model using some built-in functions and classes from PyTorch.

# Input (temp, rainfall, humidity)
inputs = np$array(list(
                     list(73, 67, 43),
                     list(91, 88, 64),
                     list(87, 134, 58),
                     list(102, 43, 37),
                     list(69, 96, 70),
                     list(73, 67, 43), 
                     list(91, 88, 64), 
                     list(87, 134, 58), 
                     list(102, 43, 37), 
                     list(69, 96, 70), 
                     list(73, 67, 43), 
                     list(91, 88, 64), 
                     list(87, 134, 58), 
                     list(102, 43, 37), 
                     list(69, 96, 70)
                   ), dtype='float32')

# Targets (apples, oranges)
targets = np$array(list(
                    list(56, 70), 
                    list(81, 101),
                    list(119, 133),
                    list(22, 37), 
                    list(103, 119),
                    list(56, 70), 
                    list(81, 101), 
                    list(119, 133), 
                    list(22, 37), 
                    list(103, 119), 
                    list(56, 70), 
                    list(81, 101), 
                    list(119, 133), 
                    list(22, 37), 
                    list(103, 119)
                    ), dtype='float32')

Optimizer

Instead of manually manipulating the weights & biases using gradients, we can use the optimizer optim.SGD.

Train the model

We are ready to train the model now. We can define a utility function fit which trains the model for a given number of epochs.

The weights and biases can also be represented as matrices, initialized with random values. The first row of \(w\) and the first element of \(b\) are used to predict the first target variable, i.e. yield for apples, and, similarly, the second for oranges.

Build the model

The model is simply a function that performs a matrix multiplication of the input \(x\) and the weights \(w\) (transposed), and adds the bias \(b\) (replicated for each observation).

model <- function(x) {
  wt <- w$t()
  return(torch$add(torch$mm(x, wt), b))
}

Loss Function

We can compare the predictions with the actual targets, using the following method:

  • Calculate the difference between the two matrices (preds and targets).
  • Square all elements of the difference matrix to remove negative values.
  • Calculate the average of the elements in the resulting matrix.

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

# MSE loss
mse = function(t1, t2) {
  diff <- torch$sub(t1, t2)
  mul <- torch$sum(torch$mul(diff, diff))
  return(torch$div(mul, diff$numel()))
}

The resulting number 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.

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:
    • increasing the element’s value slightly will increase the loss.
    • decreasing the element’s value slightly will decrease the loss.
  • If a gradient element is negative,
    • increasing the element’s value slightly will decrease the loss.
    • decreasing the element’s value slightly will increase the loss.

The increase or decrease is proportional to the value of the gradient.

Finally, we’ll reset the gradients to zero before moving forward, because PyTorch accumulates gradients.

Adjust weights and biases using gradient descent

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

  1. Generate predictions
  2. Calculate the loss
  3. Compute gradients w.r.t the weights and biases
  4. Adjust the weights by subtracting a small quantity proportional to the gradient
  5. Reset the gradients to zero

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