class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=5, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(2)
)
self.conv2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2)
)
self.fc = nn.Linear(56 * 56 * 32, 2)
def forward(self, x):
out = self.conv1(x)
out = self.conv2(out) # (bs, C, H, W)
out = out.view(out.size(0), -1) # (bs, C * H, W)
out = self.fc(out)
return out
model = SimpleCNN()
if use_gpu:
model = model.cuda()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.002, momentum=0.9)
num_epochs = 10
losses = []
for epoch in range(num_epochs):
for i, (inputs, targets) in enumerate(train_dl):
inputs = to_var(inputs)
targets = to_var(targets)
# forwad pass
optimizer.zero_grad()
outputs = model(inputs)
# loss
loss = criterion(outputs, targets)
losses += [loss.data[0]]
# backward pass
loss.backward()
# update parameters
optimizer.step()
# report
if (i + 1) % 50 == 0:
print('Epoch [%2d/%2d], Step [%3d/%3d], Loss: %.4f'
% (epoch + 1, num_epochs, i + 1, len(train_ds) // [0], loss.data[0]))
IndexError Traceback (most recent call last)
in
11
12 # loss
—> 13 loss = criterion(outputs, targets)
14 losses += [loss.data[0]]
15 # backward pass
~\anaconda3\lib\site-packages\torch\nn\modules\module.py in call(self, *input, **kwargs)
548 result = self._slow_forward(*input, **kwargs)
549 else:
–> 550 result = self.forward(*input, **kwargs)
551 for hook in self._forward_hooks.values():
552 hook_result = hook(self, input, result)
~\anaconda3\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)
930 def forward(self, input, target):
931 return F.cross_entropy(input, target, weight=self.weight,
–> 932 ignore_index=self.ignore_index, reduction=self.reduction)
933
934
~\anaconda3\lib\site-packages\torch\nn\functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
2315 if size_average is not None or reduce is not None:
2316 reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2317 return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
2318
2319
~\anaconda3\lib\site-packages\torch\nn\functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
2113 .format(input.size(0), target.size(0)))
2114 if dim == 2:
-> 2115 ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
2116 elif dim == 4:
2117 ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
IndexError: Target 3 is out of bounds.
thanks