# 3.3. Concise Implementation of Linear Regression¶ Open the notebook in Colab Open the notebook in Colab Open the notebook in Colab

Broad and intense interest in deep learning for the past several years has inspired companies, academics, and hobbyists to develop a variety of mature open source frameworks for automating the repetitive work of implementing gradient-based learning algorithms. In Section 3.2, we relied only on (i) tensors for data storage and linear algebra; and (ii) auto differentiation for calculating gradients. In practice, because data iterators, loss functions, optimizers, and neural network layers are so common, modern libraries implement these components for us as well.

In this section, we will show you how to implement the linear regression model from Section 3.2 concisely by using high-level APIs of deep learning frameworks.

## 3.3.1. Generating the Dataset¶

To start, we will generate the same dataset as in Section 3.2.

from d2l import mxnet as d2l
from mxnet import autograd, gluon, np, npx
npx.set_np()

true_w = np.array([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)

from d2l import torch as d2l
import numpy as np
import torch
from torch.utils import data

true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)

from d2l import tensorflow as d2l
import numpy as np
import tensorflow as tf

true_w = tf.constant([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)


Rather than rolling our own iterator, we can call upon the existing API in a framework to read data. We pass in features and labels as arguments and specify batch_size when instantiating a data iterator object. Besides, the boolean value is_train indicates whether or not we want the data iterator object to shuffle the data on each epoch (pass through the dataset).

def load_array(data_arrays, batch_size, is_train=True):  #@save
"""Construct a Gluon data iterator."""
dataset = gluon.data.ArrayDataset(*data_arrays)

batch_size = 10

def load_array(data_arrays, batch_size, is_train=True):  #@save
"""Construct a PyTorch data iterator."""
dataset = data.TensorDataset(*data_arrays)

batch_size = 10

def load_array(data_arrays, batch_size, is_train=True):  #@save
"""Construct a TensorFlow data iterator."""
dataset = tf.data.Dataset.from_tensor_slices(data_arrays)
if is_train:
dataset = dataset.shuffle(buffer_size=1000)
dataset = dataset.batch(batch_size)
return dataset

batch_size = 10


Now we can use data_iter in much the same way as we called the data_iter function in Section 3.2. To verify that it is working, we can read and print the first minibatch of examples. Comparing with Section 3.2, here we use iter to construct a Python iterator and use next to obtain the first item from the iterator.

next(iter(data_iter))

[array([[ 0.57342744,  0.3572845 ],
[ 0.08300753,  0.597792  ],
[ 0.46016487,  0.66304696],
[ 0.85235065, -0.50577956],
[ 2.3943908 , -0.04466231],
[-0.1796914 , -3.0070815 ],
[-0.23578128, -0.4984049 ],
[-0.08394501, -2.7443156 ],
[-0.01811524, -0.2241009 ],
[ 0.59860843, -3.0636313 ]]),
array([[ 4.1441317],
[ 2.3552508],
[ 2.8597534],
[ 7.6321135],
[ 9.127469 ],
[14.076318 ],
[ 5.4180074],
[13.356032 ],
[ 4.915421 ],
[15.81957  ]])]

next(iter(data_iter))

[tensor([[-0.3847, -1.2493],
[-0.7249, -1.4076],
[ 1.0442,  0.4986],
[-0.9345,  0.3557],
[-1.8275,  0.0531],
[-1.7961,  0.0593],
[-0.2279,  0.3546],
[ 0.6216,  0.3461],
[ 0.5193, -1.9658],
[ 2.0351, -0.4884]]),
tensor([[ 7.6936],
[ 7.5154],
[ 4.5838],
[ 1.1134],
[ 0.3828],
[ 0.4027],
[ 2.5403],
[ 4.2697],
[11.9099],
[ 9.9346]])]

next(iter(data_iter))

(<tf.Tensor: shape=(10, 2), dtype=float32, numpy=
array([[ 1.2634245 , -0.8425516 ],
[-1.0690204 , -1.0593866 ],
[-0.04169463,  0.1520228 ],
[-0.5587036 , -0.9996145 ],
[ 0.4979539 ,  0.28351393],
[-0.872869  ,  0.42491114],
[ 0.6884263 , -2.6467347 ],
[ 0.38812405, -0.19833739],
[-1.1007651 , -2.1268115 ],
[ 1.216347  ,  0.51283836]], dtype=float32)>,
<tf.Tensor: shape=(10, 1), dtype=float32, numpy=
array([[ 9.594695 ],
[ 5.65869  ],
[ 3.5917993],
[ 6.493142 ],
[ 4.226376 ],
[ 1.0163617],
[14.562097 ],
[ 5.649417 ],
[ 9.230237 ],
[ 4.888485 ]], dtype=float32)>)


## 3.3.3. Defining the Model¶

When we implemented linear regression from scratch in Section 3.2, we defined our model parameters explicitly and coded up the calculations to produce output using basic linear algebra operations. You should know how to do this. But once your models get more complex, and once you have to do this nearly every day, you will be glad for the assistance. The situation is similar to coding up your own blog from scratch. Doing it once or twice is rewarding and instructive, but you would be a lousy web developer if every time you needed a blog you spent a month reinventing the wheel.

For standard operations, we can use a framework’s predefined layers, which allow us to focus especially on the layers used to construct the model rather than having to focus on the implementation. We will first define a model variable net, which will refer to an instance of the Sequential class. The Sequential class defines a container for several layers that will be chained together. Given input data, a Sequential instance passes it through the first layer, in turn passing the output as the second layer’s input and so forth. In the following example, our model consists of only one layer, so we do not really need Sequential. But since nearly all of our future models will involve multiple layers, we will use it anyway just to familiarize you with the most standard workflow.

Recall the architecture of a single-layer network as shown in Fig. 3.1.2. The layer is said to be fully-connected because each of its inputs is connected to each of its outputs by means of a matrix-vector multiplication.

In Gluon, the fully-connected layer is defined in the Dense class. Since we only want to generate a single scalar output, we set that number to 1.

It is worth noting that, for convenience, Gluon does not require us to specify the input shape for each layer. So here, we do not need to tell Gluon how many inputs go into this linear layer. When we first try to pass data through our model, e.g., when we execute net(X) later, Gluon will automatically infer the number of inputs to each layer. We will describe how this works in more detail later.

# nn is an abbreviation for neural networks
from mxnet.gluon import nn
net = nn.Sequential()


In PyTorch, the fully-connected layer is defined in the Linear class. Note that we passed two arguments into nn.Linear. The first one specifies the input feature dimension, which is 2, and the second one is the output feature dimension, which is a single scalar and therefore 1.

# nn is an abbreviation for neural networks
from torch import nn
net = nn.Sequential(nn.Linear(2, 1))


In Keras, the fully-connected layer is defined in the Dense class. Since we only want to generate a single scalar output, we set that number to 1.

It is worth noting that, for convenience, Keras does not require us to specify the input shape for each layer. So here, we do not need to tell Keras how many inputs go into this linear layer. When we first try to pass data through our model, e.g., when we execute net(X) later, Keras will automatically infer the number of inputs to each layer. We will describe how this works in more detail later.

# keras is the high-level API for TensorFlow
net = tf.keras.Sequential()


## 3.3.4. Initializing Model Parameters¶

Before using net, we need to initialize the model parameters, such as the weights and bias in the linear regression model. Deep learning frameworks often have a predefined way to initialize the parameters. Here we specify that each weight parameter should be randomly sampled from a normal distribution with mean 0 and standard deviation 0.01. The bias parameter will be initialized to zero.

We will import the initializer module from MXNet. This module provides various methods for model parameter initialization. Gluon makes init available as a shortcut (abbreviation) to access the initializer package. We only specify how to initialize the weight by calling init.Normal(sigma=0.01). Bias parameters are initialized to zero by default.

from mxnet import init
net.initialize(init.Normal(sigma=0.01))


The code above may look straightforward but you should note that something strange is happening here. We are initializing parameters for a network even though Gluon does not yet know how many dimensions the input will have! It might be 2 as in our example or it might be 2000. Gluon lets us get away with this because behind the scene, the initialization is actually deferred. The real initialization will take place only when we for the first time attempt to pass data through the network. Just be careful to remember that since the parameters have not been initialized yet, we cannot access or manipulate them.

As we have specified the input and output dimensions when constructing nn.Linear. Now we access the parameters directly to specify there initial values. We first locate the layer by net, which is the first layer in the network, and then use the weight.data and bias.data methods to access the parameters. Next we use the replace methods normal_ and fill_ to overwrite parameter values.

net.weight.data.normal_(0, 0.01)
net.bias.data.fill_(0)

tensor([0.])


The initializers module in TensorFlow provides various methods for model parameter initialization. The easiest way to specify the initialization method in Keras is when creating the layer by specifying kernel_initializer. Here we recreate net again.

initializer = tf.initializers.RandomNormal(stddev=0.01)
net = tf.keras.Sequential()


The code above may look straightforward but you should note that something strange is happening here. We are initializing parameters for a network even though Keras does not yet know how many dimensions the input will have! It might be 2 as in our example or it might be 2000. Keras lets us get away with this because behind the scenes, the initialization is actually deferred. The real initialization will take place only when we for the first time attempt to pass data through the network. Just be careful to remember that since the parameters have not been initialized yet, we cannot access or manipulate them.

## 3.3.5. Defining the Loss Function¶

In Gluon, the loss module defines various loss functions. In this example, we will use the Gluon implementation of squared loss (L2Loss).

loss = gluon.loss.L2Loss()


The MSELoss class computes the mean squared error, also known as squared $$L_2$$ norm. By default it returns the average loss over examples.

loss = nn.MSELoss()


The MeanSquaredError class computes the mean squared error, also known as squared $$L_2$$ norm. By default it returns the average loss over examples.

loss = tf.keras.losses.MeanSquaredError()


## 3.3.6. Defining the Optimization Algorithm¶

Minibatch stochastic gradient descent is a standard tool for optimizing neural networks and thus Gluon supports it alongside a number of variations on this algorithm through its Trainer class. When we instantiate Trainer, we will specify the parameters to optimize over (obtainable from our model net via net.collect_params()), the optimization algorithm we wish to use (sgd), and a dictionary of hyperparameters required by our optimization algorithm. Minibatch stochastic gradient descent just requires that we set the value learning_rate, which is set to 0.03 here.

from mxnet import gluon
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.03})


Minibatch stochastic gradient descent is a standard tool for optimizing neural networks and thus PyTorch supports it alongside a number of variations on this algorithm in the optim module. When we instantiate an SGD instance, we will specify the parameters to optimize over (obtainable from our net via net.parameters()), with a dictionary of hyperparameters required by our optimization algorithm. Minibatch stochastic gradient descent just requires that we set the value lr, which is set to 0.03 here.

trainer = torch.optim.SGD(net.parameters(), lr=0.03)


Minibatch stochastic gradient descent is a standard tool for optimizing neural networks and thus Keras supports it alongside a number of variations on this algorithm in the optimizers module. Minibatch stochastic gradient descent just requires that we set the value learning_rate, which is set to 0.03 here.

trainer = tf.keras.optimizers.SGD(learning_rate=0.03)


## 3.3.7. Training¶

You might have noticed that expressing our model through high-level APIs of a deep learning framework requires comparatively few lines of code. We did not have to individually allocate parameters, define our loss function, or implement minibatch stochastic gradient descent. Once we start working with much more complex models, advantages of high-level APIs will grow considerably. However, once we have all the basic pieces in place, the training loop itself is strikingly similar to what we did when implementing everything from scratch.

To refresh your memory: for some number of epochs, we will make a complete pass over the dataset (train_data), iteratively grabbing one minibatch of inputs and the corresponding ground-truth labels. For each minibatch, we go through the following ritual:

• Generate predictions by calling net(X) and calculate the loss l (the forward propagation).

• Calculate gradients by running the backpropagation.

• Update the model parameters by invoking our optimizer.

For good measure, we compute the loss after each epoch and print it to monitor progress.

num_epochs = 3
for epoch in range(num_epochs):
for X, y in data_iter:
l = loss(net(X), y)
l.backward()
trainer.step(batch_size)
l = loss(net(features), labels)
print(f'epoch {epoch + 1}, loss {l.mean().asnumpy():f}')

epoch 1, loss 0.025177
epoch 2, loss 0.000093
epoch 3, loss 0.000051

num_epochs = 3
for epoch in range(num_epochs):
for X, y in data_iter:
l = loss(net(X) ,y)
l.backward()
trainer.step()
l = loss(net(features), labels)
print(f'epoch {epoch + 1}, loss {l:f}')

epoch 1, loss 0.000242
epoch 2, loss 0.000101
epoch 3, loss 0.000103

num_epochs = 3
for epoch in range(num_epochs):
for X, y in data_iter:
l = loss(net(X, training=True), y)
l = loss(net(features), labels)
print(f'epoch {epoch + 1}, loss {l:f}')

epoch 1, loss 0.000186
epoch 2, loss 0.000104
epoch 3, loss 0.000103


Below, we compare the model parameters learned by training on finite data and the actual parameters that generated our dataset. To access parameters, we first access the layer that we need from net and then access that layer’s weights and bias. As in our from-scratch implementation, note that our estimated parameters are close to their ground-truth counterparts.

w = net.weight.data()
print(f'error in estimating w: {true_w - w.reshape(true_w.shape)}')
b = net.bias.data()
print(f'error in estimating b: {true_b - b}')

error in estimating w: [5.5766106e-04 3.4332275e-05]
error in estimating b: [0.00034761]

w = net.weight.data
print('error in estimating w:', true_w - w.reshape(true_w.shape))
b = net.bias.data
print('error in estimating b:', true_b - b)

error in estimating w: tensor([ 0.0008, -0.0007])
error in estimating b: tensor([0.0014])

w = net.get_weights()
print('error in estimating w', true_w - tf.reshape(w, true_w.shape))
b = net.get_weights()
print('error in estimating b', true_b - b)

error in estimating w tf.Tensor([-0.00059032 -0.00121951], shape=(2,), dtype=float32)
error in estimating b [-0.0003891]


## 3.3.8. Summary¶

• Using Gluon, we can implement models much more concisely.

• In Gluon, the data module provides tools for data processing, the nn module defines a large number of neural network layers, and the loss module defines many common loss functions.

• MXNet’s module initializer provides various methods for model parameter initialization.

• Dimensionality and storage are automatically inferred, but be careful not to attempt to access parameters before they have been initialized.

• Using PyTorch’s high-level APIs, we can implement models much more concisely.

• In PyTorch, the data module provides tools for data processing, the nn module defines a large number of neural network layers and common loss functions.

• We can initialize the parameters by replacing their values with methods ending with _.

• Using TensorFlow’s high-level APIs, we can implement models much more concisely.

• In TensorFlow, the data module provides tools for data processing, the keras module defines a large number of neural network layers and common loss functions.

• TensorFlow’s module initializers provides various methods for model parameter initialization.

• Dimensionality and storage are automatically inferred (but be careful not to attempt to access parameters before they have been initialized).

## 3.3.9. Exercises¶

1. If we replace l = loss(output, y) with l = loss(output, y).mean(), we need to change trainer.step(batch_size) to trainer.step(1) for the code to behave identically. Why?

2. Review the MXNet documentation to see what loss functions and initialization methods are provided in the modules gluon.loss and init. Replace the loss by Huber’s loss.

3. How do you access the gradient of dense.weight?

Discussions

1. If we replace nn.MSELoss(reduction='sum') with nn.MSELoss(), how can we change the learning rate for the code to behave identically. Why?

2. Review the PyTorch documentation to see what loss functions and initialization methods are provided. Replace the loss by Huber’s loss.

3. How do you access the gradient of net.weight?

Discussions

1. Review the TensorFlow documentation to see what loss functions and initialization methods are provided. Replace the loss by Huber’s loss.

Discussions