import numpy as np def fit(epochs, [model](https://docs.pytorch.org/docs/stable/generated/torch.nn.Sequential.html#torch.nn.Sequential "torch.nn.Sequential"), loss_func, [opt](https://docs.pytorch.org/docs/stable/generated/torch.optim.SGD.html#torch.optim.SGD "torch.optim.SGD"), train_dl, valid_dl): for epoch in range(epochs): [model.train](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.train "torch.nn.Module.train")() for [xb](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), [yb](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") in train_dl: loss_batch([model](https://docs.pytorch.org/docs/stable/generated/torch.nn.Sequential.html#torch.nn.Sequential "torch.nn.Sequential"), loss_func, [xb](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), [yb](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), [opt](https://docs.pytorch.org/docs/stable/generated/torch.optim.SGD.html#torch.optim.SGD "torch.optim.SGD")) [model.eval](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.eval "torch.nn.Module.eval")() with [torch.no_grad](https://docs.pytorch.org/docs/stable/generated/torch.no_grad.html#torch.no_grad "torch.no_grad")(): losses, nums = zip( *[loss_batch([model](https://docs.pytorch.org/docs/stable/generated/torch.nn.Sequential.html#torch.nn.Sequential "torch.nn.Sequential"), loss_func, [xb](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), [yb](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor")) for [xb](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), [yb](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") in valid_dl] ) val_loss = np.sum(np.multiply(losses, nums)) / np.sum(nums) print(epoch, val_loss)