IndexError: Target 23 is out of bounds

username: Cici1
cooked: <p>I’m training a CNN model and got this error:<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/f/5/f53e63ab0d822b504c578662de45b485b5140f23.png" data-download-href="https://discuss.pytorch.org/uploads/default/f53e63ab0d822b504c578662de45b485b5140f23" title="Screen Shot 2020-05-10 at 10.20.48 AM"><img src="https://discuss.pytorch.org/uploads/default/original/3X/f/5/f53e63ab0d822b504c578662de45b485b5140f23.png" alt="Screen Shot 2020-05-10 at 10.20.48 AM" data-base62-sha1="yZwEdUyU6NFPAm9NGcFouUK1RwT" width="690" height="154" data-dominant-color="363339"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">Screen Shot 2020-05-10 at 10.20.48 AM</span><span class="informations">973×218 35.9 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div><br>
This is my code for training the model:</p>
<pre><code class="lang-auto">
def train_cnn(log_interval, model, device, train_loader, optimizer, epoch):
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        # zero the parameter gradients
        optimizer.zero_grad()
        # forward + backward + optimize
        output = model(data)
        loss = F.cross_entropy(output, target)
        # losses = []
        # losses.append(loss)
        loss.backward()
        optimizer.step()
        if batch_idx % log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))
</code></pre>
<p>This is my model</p>
<pre><code class="lang-auto">class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # Define 2D convolution layers
        # 3: input channels, 32: output channels, 5: kernel size, 1: stride
        self.conv1 = nn.Conv2d(3, 32, 5, 1)   # The size of input channel is 3 because all images are coloured
        self.conv2 = nn.Conv2d(32, 64, 5, 1)
        self.conv3 = nn.Conv2d(64, 128, 3, 1)
        self.conv4 = nn.Conv2d(128, 256, 3, 1)
        # It will 'filter' out some of the input by the probability(assign zero)
        self.dropout1 = nn.Dropout2d(0.25)
        self.dropout2 = nn.Dropout2d(0.5)
        # Fully connected layer: input size, output size
        self.fc1 = nn.Linear(692224, 128)
        self.fc2 = nn.Linear(128, 10)

    # forward() link all layers together,
    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = self.conv3(x)
        x = F.relu(x)
        x = self.conv4(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        output = F.log_softmax(x, dim=1)
        return output
</code></pre>
<p>Any advice would be appreciated. Thanks in advance!</p>

username: KFrank
cooked: <p>Hi Cici!</p>
<aside class="quote no-group" data-username="Cici1" data-post="1" data-topic="80503" data-full="true">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/cici1/48/12567_2.png" class="avatar"> Cici1:</div>
<blockquote>
<p>I’m training a CNN model and got this error:</p>
</blockquote>
</aside>
<p>The short answer is that your <code>target</code> contains a value of <code>23</code>, but<br>
you are training a 10-class classifier for which your class labels<br>
must run from <code>0</code> to <code>9</code>.</p>
<p>(As an aside, please don’t post screen-shots of textual information.<br>
They can’t be searched or copy-pasted.)</p>
<aside class="quote no-group">
<blockquote>
<p>This is my code for training the model:</p>
<pre><code class="lang-auto">...
        loss = F.cross_entropy(output, target)
...
</code></pre>
<p>This is my model</p>
<pre><code class="lang-auto">...
        self.fc2 = nn.Linear(128, 10)
...
        x = self.fc2(x)
        output = F.log_softmax(x, dim=1)
        return output
</code></pre>
</blockquote>
</aside>
<p>Your output has shape <code>[nBatch, 10]</code> so you are predicting <code>10</code><br>
classes.  But you have passed your loss function a target containing<br>
a value of <code>23</code>, hence this particular error message.</p>
<p>(Also, you are using <code>cross_entropy()</code>, which has <code>log_softmax()</code><br>
built in.  You should either get rid of <code>log_softmax()</code> or use <code>nll_loss()</code>,<br>
which expects its <code>input</code> to have been passed through <code>log_softmax()</code><br>
already.)</p>
<p>Good luck.</p>
<p>K. Frank</p>