import numpy as npimport torchimport matplotlib.pyplot as plttorch.manual_seed(7)net = torch.nn.Sequential( torch.nn.Linear(3, 30), torch.nn.ReLU(), torch.nn.Linear(30, 2),)n_params =sum(p.numel() for p in net.parameters())print(net)print("parameters:", n_params)
1
From 3 inputs to 30 hidden neurons. This layer has \(30 \times 4 = 120\) parameters.
2
From 30 hidden neurons to 2 outputs, so \(2 \times 31 = 62\) parameters.
A relu network with one hidden layer is a piecewise linear function. Each neuron contributes a kink.
A network with one hidden layer of relu neurons, fitted to the same 60 points. Switch to the hidden units to see the individual pieces that are summed to make the fit. Each neuron contributes one kink.
Fitting a regression
We fit the weather data. Note the two things we do before training. We standardize the input, and we standardize the output as well, which makes the default learning rate work.
Figure 36.1: The learning curve. It is flat at the end, so more epochs would not help much.
To get predictions in the original units we invert the output scaler.
with torch.no_grad(): pred = ys.inverse_transform(model(Xt).numpy())rmse =float(np.sqrt(np.mean((pred[:, 0] - ydf) **2)))print("training RMSE in km/h:", round(rmse, 3))
training RMSE in km/h: 6.462
Compare this to the linear regression from week 2. The network fits the training data better. Whether it predicts better is a different question, and we would answer it with cross-validation.
The same thing with scikit-learn
For small problems MLPRegressor is quicker to write. It has fewer options than torch, which is often an advantage.
from sklearn.neural_network import MLPRegressorm = MLPRegressor(hidden_layer_sizes=(128, 64), max_iter=200)m.fit(Xn, ydf)