Issue
My goal is to do multi class image classification in Pytorch using the EMNIST dataset. As a loss function, I would like to use Multi-Class Cross-Entropy Loss.
Currently, I define my loss function as follows:
criterion = nn.CrossEntropyLoss()
I train my model as follows:
iter = 0
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# Add a single channel dimension
# From: [batch_size, height, width]
# To: [batch_size, 1, height, width]
images = images.unsqueeze(1)
# Forward pass to get output/logits
outputs = model(images)
# Clear gradients w.r.t. parameters
optimizer.zero_grad()
# Forward pass to get output/logits
outputs = model(images)
# Calculate Loss: softmax --> cross entropy loss
loss = criterion(outputs, labels)
# Getting gradients w.r.t. parameters
loss.backward()
# Updating parameters
optimizer.step()
iter += 1
if iter % 500 == 0:
# Calculate Accuracy
correct = 0
total = 0
# Iterate through test dataset
for images, labels in test_loader:
images = images.unsqueeze(1)
# Forward pass only to get logits/output
outputs = model(images)
# Get predictions from the maximum value
_, predicted = torch.max(outputs.data, 1)
# Total number of labels
total += labels.size(0)
correct += (predicted == labels).sum()
accuracy = 100 * correct / total
# Print Loss
print('Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.data[0], accuracy))
However, the error that I get is:
RuntimeError Traceback (most recent call last)
<ipython-input-15-c26c43bbc32e> in <module>()
21
22 # Calculate Loss: softmax --> cross entropy loss
---> 23 loss = criterion(outputs, labels)
24
25 # Getting gradients w.r.t. parameters
3 frames
/usr/local/lib/python3.6/dist-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)
RuntimeError: 1D target tensor expected, multi-target not supported
My CNN outputs 26 variables and my target variables are also 26D.
How can I change my code so that nn.crossentropyloss() expects a 26D input rather than 1D?
Solution
nn.CrossEntropy()(input, target)
expects input
to be an one-hot vector with size batchsize X num_classes
, and target
to be the id of true class with size batchsize
.
So in short, you can change your target with target = torch.argmax(target, dim=1)
to have it fit nn.CrossEntropy()
.
Answered By - Flicic Suo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.