TypeError: __init__() takes at most 2 arguments (3 given)

Just trying a basic example and it keeps on telling me that I’m giving the loss function 3 values when I’m actually only giving it 2. Not sure what’s wrong.

import torch
import torch.nn as nn
from torch.autograd import Variable

image = Variable(torch.randn(2,2).view(1,4))
label = Variable(torch.randn(1,2))

net = nn.Sequential(nn.Linear(4, 2), nn.Sigmoid(), nn.Dropout(), nn.Linear(2, 2))

optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
optimizer.zero_grad()
loss = nn.MSELoss(net(image), label).backward()
optimizer.step()

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    loss = nn.MSELoss(net(image), label).backward()
TypeError: __init__() takes at most 2 arguments (3 given)

The three arguments are self, net(image), and label. self is implicit since you’re calling a method in Python.

You probably want the functional form of mse_loss instead of the module:

import torch.nn.functional as F
loss = F.mse_loss(net(image), label)
loss.backward()

You could use the module nn.MSELoss like:

loss_fn = nn.MSELoss()
loss = loss_fn(net(image), label)
loss.backward()
1 Like

Ah thanks! I didn’t know the difference. :slight_smile: