Linear Regression Implementation from Scratch
We are now ready to work through a fully functioning implementation of linear regression. In this section, we will implement the entire method from scratch, including (i) the model; (ii) the loss function; (iii) a minibatch stochastic gradient descent optimizer; and (iv) the training function that stitches all of these pieces together. Finally, we will run our synthetic data generator from :numref:sec_synthetic-regression-data and apply our model on the resulting dataset. While modern deep learning frameworks can automate nearly all of this work, implementing things from scratch is the only way to make sure that you really know what you are doing. Moreover, when it is time to customize models, defining our own layers or loss functions, understanding how things work under the hood will prove handy. In this section, we will rely only on tensors and automatic differentiation. Later, we will introduce a more concise implementation, taking advantage of the bells and whistles of deep learning frameworks while retaining the structure of what follows below.
using Pkg
Pkg.activate("../../d2lai")
using Flux, d2lai, Distributions Activating project at `/workspace/workspace/d2l-julia/d2lai`Defining the Model
Before we can begin optimizing our model's parameters by minibatch SGD, we need to have some parameters in the first place. In the following we initialize weights by drawing random numbers from a normal distribution with mean 0 and a standard deviation of 0.01. The magic number 0.01 often works well in practice, but you can specify a different value through the argument sigma. Moreover we set the bias to 0.
struct LinearRegressionScratch <: d2lai.AbstractModel
w::AbstractArray
b::AbstractArray
args::NamedTuple
end
function LinearRegressionScratch(num_inputs::Int64, lr, sigma = 0.01)
w = rand(Normal(0, sigma), 1, num_inputs)
b = zeros(1)
args = (num_inputs = num_inputs, lr = lr, sigma = sigma)
LinearRegressionScratch(w, b, args)
end
Flux.@layer LinearRegressionScratch trainable=(w, b)Next we must define our model, relating its input and parameters to its output. Using the same notation as :eqref:eq_linreg-y-vec for our linear model we simply take the matrix–vector product of the input features subsec_broadcasting), when we add a vector and a scalar, the scalar is added to each component of the vector.
function d2lai.forward(lr::LinearRegressionScratch, x)
return lr.w*x .+ lr.b
endDefining the Loss Function
Since updating our model requires taking the gradient of our loss function, we ought to (define the loss function first.) Here we use the squared loss function in :eqref:eq_mse. In the implementation, we need to transform the true value y into the predicted value's shape y_hat. The result returned by the following method will also have the same shape as y_hat. We also return the averaged loss value among all examples in the minibatch.
function d2lai.loss(lr::LinearRegressionScratch, y_pred, y)
l = 0.5*(y_pred - y).^2
return mean(l)
endDefining the Optimization Algorithm
As discussed in :numref:sec_linear_regression, linear regression has a closed-form solution. However, our goal here is to illustrate how to train more general neural networks, and that requires that we teach you how to use minibatch SGD. Hence we will take this opportunity to introduce your first working example of SGD. At each step, using a minibatch randomly drawn from our dataset, we estimate the gradient of the loss with respect to the parameters. Next, we update the parameters in the direction that may reduce the loss.
The following code applies the update, given a set of parameters, a learning rate lr. Since our loss is computed as an average over the minibatch, we do not need to adjust the learning rate against the batch size. In later chapters we will investigate how learning rates should be adjusted for very large minibatches as they arise in distributed large-scale learning. For now, we can ignore this dependency.
struct SGD{P, L}
params::P
lr::L
end
function step!(sgd::SGD, model, grads)
model.w .-= sgd.lr.*grads[model.w]
model.b .-= sgd.lr.*grads[model.b]
endstep! (generic function with 1 method)Training
Now that we have all of the parts in place (parameters, loss function, model, and optimizer), we are ready to implement the main training loop. It is crucial that you understand this code fully since you will employ similar training loops for every other deep learning model covered in this book. In each epoch, we iterate through the entire training dataset, passing once through every example (assuming that the number of examples is divisible by the batch size). In each iteration, we grab a minibatch of training examples, and compute its loss through the model's training_step method. Then we compute the gradients with respect to each parameter. Finally, we will call the optimization algorithm to update the model parameters. In summary, we will execute the following loop:
Initialize parameters
Repeat until done
Compute gradient
Update parameters
Recall that the synthetic regression dataset that we generated in :numref:prepare_batch and fit_epoch methods are registered in the d2l.Trainer class (introduced in :numref:oo-design-training).
function d2lai.fit_epoch(model::LinearRegressionScratch, opt; train_dataloader = nothing, val_dataloader = nothing, gradient_clip_val = 0.)
losses = (train_losses = [], val_losses = [], val_acc = [])
for batch in train_dataloader
gs = gradient(Flux.Params([model.w, model.b])) do
training_step(trainer.model, batch)
end
step!(opt, model, gs)
train_loss = training_step(trainer.model, batch)
push!(losses.train_losses, train_loss)
end
for batch in val_dataloader
loss, _ = validation_step(trainer.model, batch)
push!(losses.val_losses , loss)
end
return losses
endWe are almost ready to train the model, but first we need some training data. Here we use the SyntheticRegressionData class and pass in some ground truth parameters. Then we train our model with the learning rate lr=0.03 and set max_epochs=3. Note that in general, both the number of epochs and the learning rate are hyperparameters. In general, setting hyperparameters is tricky and we will usually want to use a three-way split, one set for training, a second for hyperparameter selection, and the third reserved for the final evaluation. We elide these details for now but will revise them later.
model = LinearRegressionScratch(2, 0.03)
sgd = SGD(nothing, 0.03)
data = SyntheticRegressionData([2 -3.4], 4.3)
trainer = Trainer(model, data, sgd; max_epochs = 5)
d2lai.fit(trainer) [ Info: Train Loss: 4.159377763440317, Val Loss: 1.6136084418676728
[ Info: Train Loss: 0.5253720630174942, Val Loss: 0.20050404086196566
[ Info: Train Loss: 0.06684764937174377, Val Loss: 0.024274566118867594
[ Info: Train Loss: 0.008670093066378354, Val Loss: 0.002744558889707349
[ Info: Train Loss: 0.0011937151261237698, Val Loss: 0.0002836587166744213(LinearRegressionScratch([1.992836720414413 -3.37799751615318], [4.2724079808329645], (num_inputs = 2, lr = 0.03, sigma = 0.01)), (val_loss = [0.0008190482770071592, 0.0004729000362407759, 0.0008228406226611303, 0.0009655684573209392, 0.0003667007325329076, 0.000566660471668708, 0.0007715233407286309, 0.0005612130406624064, 0.0005501054302935709, 0.0007714316856376472 … 0.0008044788837960324, 0.0007816813786489018, 0.0005494918163793845, 0.0006066466659859343, 0.0007979676460930835, 0.0007077506486962472, 0.0007604577022060139, 0.0006439598375716324, 0.0005397228479022556, 0.0002836587166744213], val_acc = nothing))Because we synthesized the dataset ourselves, we know precisely what the true parameters are. Thus, we can evaluate our success in training by comparing the true parameters with those that we learned through our training loop. Indeed they turn out to be very close to each other.
@show model.w
@show model.bmodel.w = [1.992836720414413 -3.37799751615318]
model.b = [4.2724079808329645]
1-element Vector{Float64}:
4.2724079808329645We should not take the ability to exactly recover the ground truth parameters for granted. In general, for deep models unique solutions for the parameters do not exist, and even for linear models, exactly recovering the parameters is only possible when no feature is linearly dependent on the others. However, in machine learning, we are often less concerned with recovering true underlying parameters, but rather with parameters that lead to highly accurate prediction [13]. Fortunately, even on difficult optimization problems, stochastic gradient descent can often find remarkably good solutions, owing partly to the fact that, for deep networks, there exist many configurations of the parameters that lead to highly accurate prediction.
Summary
In this section, we took a significant step towards designing deep learning systems by implementing a fully functional neural network model and training loop. In this process, we built a data loader, a model, a loss function, an optimization procedure, and a visualization and monitoring tool. We did this by composing a Python object that contains all relevant components for training a model. While this is not yet a professional-grade implementation it is perfectly functional and code like this could already help you to solve small problems quickly. In the coming sections, we will see how to do this both more concisely (avoiding boilerplate code) and more efficiently (using our GPUs to their full potential).
Exercises
What would happen if we were to initialize the weights to zero. Would the algorithm still work? What if we initialized the parameters with variance
rather than ? Assume that you are Georg Simon Ohm trying to come up with a model for resistance that relates voltage and current. Can you use automatic differentiation to learn the parameters of your model?
Can you use Planck's Law to determine the temperature of an object using spectral energy density? For reference, the spectral density
of radiation emanating from a black body is . Here is the wavelength, is the temperature, is the speed of light, is Planck's constant, and is the Boltzmann constant. You measure the energy for different wavelengths and you now need to fit the spectral density curve to Planck's law. What are the problems you might encounter if you wanted to compute the second derivatives of the loss? How would you fix them?
Why is the
reshapemethod needed in thelossfunction?Experiment using different learning rates to find out how quickly the loss function value drops. Can you reduce the error by increasing the number of epochs of training?
If the number of examples cannot be divided by the batch size, what happens to
data_iterat the end of an epoch?Try implementing a different loss function, such as the absolute value loss
(y_hat - d2l.reshape(y, y_hat.shape)).abs().sum().Check what happens for regular data.
Check whether there is a difference in behavior if you actively perturb some entries, such as
, of . Can you think of a cheap solution for combining the best aspects of squared loss and absolute value loss? Hint: how can you avoid really large gradient values?
Why do we need to reshuffle the dataset? Can you design a case where a maliciously constructed dataset would break the optimization algorithm otherwise?