Complete worked example
python
from bootstrap_lab import torch_setup
torch = torch_setup()
from torch import nn
def one_update(initial, learning_rate):
model = nn.Linear(1, 1, bias=False)
with torch.no_grad():
model.weight.fill_(initial)
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
x = torch.tensor([[1.0]])
target = torch.tensor([[2.0]])
optimizer.zero_grad(set_to_none=True)
loss = nn.MSELoss()(model(x), target)
loss.backward()
optimizer.step()
return model.weight.item()- Reasoning
- The helper initializes a one-weight linear model to a known value, predicts one from one input and compares it with target two using mean squared error.