class HouseMLP(d2l.Module):
"""An MLP with one hidden layer, squared loss, and weight decay."""
loss = d2l.LinearRegression.loss
def __init__(self, num_hiddens, wd, lr):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(nn.LazyLinear(num_hiddens), nn.ReLU(),
nn.LazyLinear(1))
def weight_init(self, module):
if isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
nn.init.zeros_(module.bias)
def configure_optimizers(self):
weights = [p for p in self.parameters() if p.dim() > 1]
biases = [p for p in self.parameters() if p.dim() == 1]
return torch.optim.SGD([{'params': weights, 'weight_decay': self.wd},
{'params': biases}], lr=self.lr)
make_mlp = lambda num_inputs, wd: HouseMLP(num_hiddens=64, wd=wd, lr=0.02)