A Basic Python Question about Defining Function
I have a basic question regarding Python code.
For example,
import torch
import torch.nn as nn

loss = nn.MSELoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()

Why do I need to define the loss function at the first line? I can't replace loss() at the 4th line with nn.MSELoss().

As a few others have pointed out, nn.MSELoss is a class and not a function. In line 1 you are creating an object of type torch.nn.modules.loss.MSELoss. And because it inherits from nn.Module, you can call this object like you would call a function, like you do in line 4.
If you don't want to use the MSELoss class, you can also import torch.nn.functional as F and then use F.mse_loss(input, target) directly (this is what pytorch normally calls for you).
