IndexError: Target 103 is out of bounds

After epoch 1 it is throwing this error. Batch_size is 50.
Epoch 1, Batch 1 loss: 5.308178
‘’’

Building Model

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
def init(self):
super(Net, self).init()

    self.conv1 = nn.Conv2d(in_channels = 1, out_channels = 32, kernel_size = 3, padding=1, stride=1)
    self.relu = nn.ReLU()
    self.maxpool = nn.MaxPool2d(kernel_size = 2)
    
    
    self.conv2 = nn.Conv2d(in_channels = 32, out_channels = 64, kernel_size = 3, padding=1, stride=1)
    
    self.conv3 = nn.Conv2d(in_channels = 64, out_channels = 128, kernel_size = 3, padding=1, stride=1)
    
    self.conv4 = nn.Conv2d(in_channels = 128, out_channels = 256, kernel_size = 3, padding=1, stride=1)
    
    #nn.Flatten()
    
    self.fc1 = nn.Linear(in_features = 16384, out_features = 8192)
    
    self.fc2 = nn.Linear(in_features = 8192, out_features = 256) 
    
    self.linear1 = nn.Linear(in_features = 256, out_features = 100) # For age class output
    self.linear2 = nn.Linear(in_features = 256, out_features = 2)   # For gender class output
 
def forward(self, x):
    out = self.conv1(x)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv2(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv3(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv4(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = out.view(x.size(0),-1)
    out = F.sigmoid(self.fc1(out))
    out = F.sigmoid(self.fc2(out))
    label1 = torch.sigmoid(self.linear1(out))                 # Age output
    label2 = torch.sigmoid(self.linear2(out))  # Gender output
    
    return {'label1': label1, 'label2': label2} 

‘’’
‘’’
import torch.optim as optim

For multilabel output:Age

criterion_multioutput = nn.CrossEntropyLoss()

For binary output:Gender

criterion_binary = nn.CrossEntropyLoss()

optimizer = optim.SGD(net.parameters(), lr=0.001)
‘’’
‘’’
def train_model(model, criterion1, criterion2, optimizer, n_epochs=25):
“”“returns trained model”“”
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
for epoch in range(1, n_epochs):
train_loss = 0.0
valid_loss = 0.0

    # train the model #
    model.train()
   
    for batch_idx, sample_batched in enumerate(train_dataloader):
        
        image, label1, label2 = sample_batched
        # importing data and moving to CPU

image, label1, label2 = sample_batched[X_train].to(device),\

sample_batched[y_age_train].to(device),\

sample_batched[y_gender_train].to(device)

print(type(sample_batched))

        # zero the parameter gradients
        optimizer.zero_grad()
        output = model(image.float())
        output = model(image.float())
        print(output)
        label1_hat = output['label1']
        label2_hat = output['label2']
        #label3_hat=output['label3']         
        # calculate loss
        print(label1.shape)
        loss1 = criterion1(label1_hat, label1.squeeze().type(torch.LongTensor))
        loss2 = criterion2(label2_hat, label2.squeeze().type(torch.LongTensor))
        #loss3=criterion1(label3_hat, label3.squeeze().type(torch.LongTensor))     
        loss = loss1+loss2
        # back prop
        loss.backward()
        # grad
        optimizer.step()
        train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
        if batch_idx % 50 == 0:
            print('Epoch %d, Batch %d loss: %.6f' %
              (epoch, batch_idx + 1, train_loss))
            
    # validate the model #
    model.eval()

    for batch_idx, sample_batched in enumerate(test_dataloader):
        image, label1, label2 = sample_batched

image, label1, label2 = sample_batched[X_test].to(device),\

sample_batched[y_age_test].to(device),\

sample_batched[y_gender_test].to(device),\

#sample_batched[‘label_race’].to(device)

print(type(image))

        output = model(image.float())
        output = model(image.float())
        label1_hat = output['label1']
        label2_hat = output['label2']
        #label3_hat=output['label3']               
        # calculate loss
        loss1=criterion1(label1_hat, label1.squeeze().type(torch.LongTensor))
        loss2=criterion2(label2_hat, label2.squeeze().type(torch.LongTensor))
        #loss3=criterion1(label3_hat, label3.squeeze().type(torch.LongTensor))  
        loss = loss1+loss2
        valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))
    
    # print training/validation statistics 
    print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
        epoch, train_loss, valid_loss))
    
    ## TODO: save the model if validation loss has decreased
    if valid_loss < valid_loss_min:
        torch.save(model, 'model.pt')
        print('Validation loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(
        valid_loss_min,
        valid_loss))
        valid_loss_min = valid_loss
# return trained model
return model

‘’’
‘’’
model_conv = train_model(net, criterion_multioutput, criterion_binary, optimizer)
‘’’
IndexError Traceback (most recent call last)
Input In [56], in <cell line: 1>()
----> 1 model_conv = train_model(net, criterion_multioutput, criterion_binary, optimizer)

Input In [55], in train_model(model, criterion1, criterion2, optimizer, n_epochs)
29 #label3_hat=output[‘label3’]
30 # calculate loss
31 print(label1.shape)
—> 32 loss1 = criterion1(label1_hat, label1.squeeze().type(torch.LongTensor))
33 loss2 = criterion2(label2_hat, label2.squeeze().type(torch.LongTensor))
34 #loss3=criterion1(label3_hat, label3.squeeze().type(torch.LongTensor))

File ~\anaconda3\lib\site-packages\torch\nn\modules\module.py:1130, in Module._call_impl(self, *input, **kwargs)
1126 # If we don’t have any hooks, we want to skip the rest of the logic in
1127 # this function, and just call forward.
1128 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1129 or _global_forward_hooks or _global_forward_pre_hooks):
→ 1130 return forward_call(*input, **kwargs)
1131 # Do not call functions when jit is used
1132 full_backward_hooks, non_full_backward_hooks = [], []

File ~\anaconda3\lib\site-packages\torch\nn\modules\loss.py:1164, in CrossEntropyLoss.forward(self, input, target)
1163 def forward(self, input: Tensor, target: Tensor) → Tensor:
→ 1164 return F.cross_entropy(input, target, weight=self.weight,
1165 ignore_index=self.ignore_index, reduction=self.reduction,
1166 label_smoothing=self.label_smoothing)

File ~\anaconda3\lib\site-packages\torch\nn\functional.py:3014, in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing)
3012 if size_average is not None or reduce is not None:
3013 reduction = _Reduction.legacy_get_string(size_average, reduce)
→ 3014 return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)

IndexError: Target 103 is out of bounds.

I tried to solve this error but it could not. Thank you in advance.

Hi,
I can see you are using nn.CrossEntropyLoss. Please refer to the docs and make sure the labels / targets are in the range [0, N-1] where N=no. of classes.

It is difficult to follow your code as it is not properly formatted but as I can see your output layer has 100 and 2 nodes for two different tasks maybe. In that case, for the layer with 100 nodes the target tensor should contain values in the range [0, 99], and in the range [0,1] for the layer with 2 nodes.

Yes. this code has two different tasks for age and gender detection. Label1 is for Age output has 100 nodes in output and Label2 is for Gender output has 2 nodes in output. and batch size is 50. I am using UTKFace dataset for this.
When I print Label1 it shows tensor([28, 30, 3, 41, 38, 35, 35, 2, 37, 89, 24, 70, 24, 28, 65, 39, 8, 25,
4, 40, 29, 89, 17, 75, 26, 2, 21, 39, 32, 43, 2, 23, 27, 40, 9, 28,
90, 36, 70, 59, 26, 26, 15, 19, 12, 26, 26, 34, 25, 24]) this type of output.
When I print Label2 it shows tensor([1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0,
1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0,
0, 1]) this type of output.
When I print output it shows {‘label1’: tensor([[0.4544, 0.4799, 0.3660, …, 0.5097, 0.4451, 0.5353],
[0.4544, 0.4799, 0.3659, …, 0.5097, 0.4451, 0.5353],
[0.4544, 0.4799, 0.3660, …, 0.5098, 0.4451, 0.5353],
…,
[0.4544, 0.4799, 0.3660, …, 0.5098, 0.4451, 0.5353],
[0.4544, 0.4799, 0.3660, …, 0.5098, 0.4451, 0.5353],
[0.4544, 0.4799, 0.3660, …, 0.5097, 0.4451, 0.5353]],
grad_fn=), ‘label2’: tensor([[0.5183, 0.4864],
[0.5182, 0.4864],
[0.5183, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5183, 0.4865],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4865],
[0.5183, 0.4865],
[0.5182, 0.4864],
[0.5182, 0.4865],
[0.5182, 0.4864],
[0.5182, 0.4865],
[0.5182, 0.4864],
[0.5182, 0.4865],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4865],
[0.5182, 0.4864],
[0.5183, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4865],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4865],
[0.5182, 0.4864],
[0.5183, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4865],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4864],
[0.5182, 0.4865],
[0.5182, 0.4865],
[0.5182, 0.4865],
[0.5182, 0.4864],
[0.5182, 0.4865]], grad_fn=)}

As I am new in this area. I have read so many errors like this but I can’t figure out how correct my model and how to solve this. Will you please guide and assist me?

Hi, sure.

For age, since you have formulated it as a classification task using cross entropy, the correct answer is one and only one of the 100 “categories”.

Now as can be seen your target tensor (the true labels) contains the correct class’ index corresponding to each point in the batch with dim torch.Size([50]) and the output tensor contains class probabilities corresponding to each class for all points in a batch with dimension torch.Size([50, 100]).

Cross entropy loss can be simply used as -

target = torch.empty(50, dtype=torch.long).random_(100)
print(target.shape) # torch.Size([50])
output = torch.randn(50, 100, requires_grad=True)
print(output.shape) # torch.Size([50, 100])
loss_fn = torch.nn.CrossEntropyLoss()
loss = loss_fn(output, target)
print(loss) # tensor(4.9516, grad_fn=<NllLossBackward0>)

Similar is the case with gender.
Feel free to post further questions.
Hope this helps,
S

1 Like

Thank you. It works.

Hi,
My one more question is means i have to convert my target tensor (the true labels) which has dim torch.Size([50]) to torch.Size([50, 100]) which is output tensor.

Since your target tensor the contains the correct class’ index corresponding to each point in the batch, you do not need to do that.
Please see the code in my last post where target has the shape torch.Size([50]).

I got the code you gave me. But I don’t know where to change in my program according to that code which will give the answer. I can’t figure out how correct my model and how to solve this. Will you please guide and assist me?

Sure.
Please try to post a minimum executable snippet that reproduces the error you are facing.

Also, please make sure to properly format the code. Enclose it within three backticks ```.

okay.
This is my data
image

Convert it to dataframe
‘’’
df = pd.DataFrame()
df[‘image’], df[‘age’], df[‘gender’] = image_paths, age_labels, gender_labels
X = extract_features(df[‘image’])
X.shape >>(10497, 1, 128, 128)
X = X/255.0

‘’’
‘’’
X_train, X_test, y_age_train, y_age_test, y_gender_train, y_gender_test = train_test_split(X, label_age, label_gender, test_size=0.2)
train = torch.utils.data.TensorDataset(X_train_tensor, y_age_train_tensor, y_gender_train_tensor)
test = torch.utils.data.TensorDataset(X_test_tensor, y_age_test_tensor, y_gender_test_tensor)
batch_size = 50
train_dataloader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=4)
test_dataloader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=True, num_workers=4)
‘’’
‘’’
Building Model

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
def init(self):
super(Net, self).init()

    self.conv1 = nn.Conv2d(in_channels = 1, out_channels = 32, kernel_size = 3, padding=1, stride=1)
    self.relu = nn.ReLU()
    self.maxpool = nn.MaxPool2d(kernel_size = 2)
    
    
    self.conv2 = nn.Conv2d(in_channels = 32, out_channels = 64, kernel_size = 3, padding=1, stride=1)
    
    self.conv3 = nn.Conv2d(in_channels = 64, out_channels = 128, kernel_size = 3, padding=1, stride=1)
    
    self.conv4 = nn.Conv2d(in_channels = 128, out_channels = 256, kernel_size = 3, padding=1, stride=1)
    
    #nn.Flatten()
    
    self.fc1 = nn.Linear(in_features = 16384, out_features = 8192)
    
    self.fc2 = nn.Linear(in_features = 8192, out_features = 512) 
    
    self.linear1 = nn.Linear(in_features = 512, out_features = 100) # For age class output
    self.linear2 = nn.Linear(in_features = 512, out_features = 2)   # For gender class output
 
def forward(self, x):
    out = self.conv1(x)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv2(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv3(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv4(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = out.view(x.size(0),-1)
    out = F.sigmoid(self.fc1(out))
    out = F.sigmoid(self.fc2(out))
    label1 = self.linear1(out)                 # Age output
    label2 = torch.sigmoid(self.linear2(out))  # Gender output
    
    return {'label1': label1, 'label2': label2}      

criterion_multioutput = nn.CrossEntropyLoss()
criterion_binary = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001)
‘’’
‘’’

def train_model(model, criterion1, criterion2, optimizer, n_epochs=25):

# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
for epoch in range(1, n_epochs):
    train_loss = 0.0
    valid_loss = 0.0
    
    # train the model 
    model.train()
   
    for batch_idx, sample_batched in enumerate(train_dataloader):
        
        image, label1, label2 = sample_batched

                                             
        # zero the parameter gradients
        optimizer.zero_grad()
        output = model(image.float())
        
        print("output label1 shape: ",output['label1'].ndim)
        #print("output label2 shape: ",output['label2'].shape)
        #print(type(output['label1']))
        label1_hat = output['label1']
        label2_hat = output['label2']
        
        
        #print("label1 shape: ",label1.shape)
        #print("label2 shape: ",label2.shape)
        #print("Label1: ", label1)
        age_label1 = label1
        print(label1.ndim)
        gender_label2 = label2
        print(gender_label2)
        
        # calculate loss
        loss1 = criterion1(label1_hat, label1.squeeze().type(torch.LongTensor))
        loss2 = criterion2(label2_hat, label2.squeeze().type(torch.LongTensor))
           
        loss = loss1+loss2
        # back prop
        loss.backward()
        # grad
        optimizer.step()
        train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
        if batch_idx % 50 == 0:
            print('Epoch %d, Batch %d loss: %.6f' %
              (epoch, batch_idx + 1, train_loss))
            
            
    # validate the model #
    model.eval()

    for batch_idx, sample_batched in enumerate(test_dataloader):
        image, label1, label2 = sample_batched

        output = model(image.float())
        
        label1_hat = output['label1']
        label2_hat = output['label2']
                 
        # calculate loss
        loss1=criterion1(label1_hat, label1.squeeze().type(torch.LongTensor))
        loss2=criterion2(label2_hat, label2.squeeze().type(torch.LongTensor))
        
          
        loss = loss1+loss2
        valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))
    
    # print training/validation statistics 
    print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
        epoch, train_loss, valid_loss))
    
    ## TODO: save the model if validation loss has decreased
    if valid_loss < valid_loss_min:
        torch.save(model, 'model.pt')
        print('Validation loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(
        valid_loss_min,
        valid_loss))
        valid_loss_min = valid_loss
# return trained model
return model

model_conv = train_model(net, criterion_multioutput, criterion_binary, optimizer)
‘’’

Hi,
I make some changes in training the model
‘’’
def train_model(model, criterion1, criterion2, optimizer, n_epochs=25):

# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
for epoch in range(1, n_epochs):
    train_loss = 0.0
    valid_loss = 0.0
    
    # train the model #
    model.train()
    
    
   

    for batch_idx, sample_batched in enumerate(train_dataloader):
        
        image, label1, label2 = sample_batched
        
        target = torch.empty(50, dtype=torch.long).random_(100) # as per code you given
        label1 = torch.randn(50, 100, requires_grad=True)           # as per code you given
    
        target = torch.empty(50, dtype=torch.long).random_(2)   # as per code you given
        label2 = torch.randn(50, 2, requires_grad=True)              # as per code you given

                                             
        # zero the parameter gradients
        optimizer.zero_grad()
        output = model(image.float())
        
        #print("output label1 shape: ",output['label1'].shape)    #####
        #print("output label2 shape: ",output['label2'].shape)   ######
        #print(type(output['label1']))                            ########
        #print(output['label2'])                                  ########
        
        label1_hat = output['label1']
        label2_hat = output['label2']
        
        
        
        #print("label1 shape: ",label1.shape)                   ##########
        #print("label2 shape: ",label2.shape)                   ###########
        #print("Label1: ", label1)                              #############
        #age_label1 = label1                                     ##########
        #print(label1.shape)                                     ########
        #print("label2: ", label2)                               ############
        #gender_label2 = label2                                  ############
        #print(gender_label2)                                   ###############
        
        # calculate loss
        loss1 = criterion1(label1_hat, label1.squeeze().type(torch.FloatTensor))
        loss2 = criterion2(label2_hat, label2.squeeze().type(torch.FloatTensor))
           
        loss = loss1+loss2
        # back prop
        loss.backward()
        # grad
        optimizer.step()
        train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
        if batch_idx % 50 == 0:
            print('Epoch %d, Batch %d loss: %.6f' %
              (epoch, batch_idx + 1, train_loss))
            
    # validate the model #
    model.eval()

    for batch_idx, sample_batched in enumerate(test_dataloader):
        image, label1, label2 = sample_batched

        output = model(image.float())
        
        label1_hat = output['label1']
        label2_hat = output['label2']
                 
        # calculate loss
        loss1=criterion1(label1_hat, label1.squeeze().type(torch.FloatTensor))
        loss2=criterion2(label2_hat, label2.squeeze().type(torch.FloatTensor))
        
          
        loss = loss1+loss2
        valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))
    
    # print training/validation statistics 
    print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
        epoch, train_loss, valid_loss))
    
    ## TODO: save the model if validation loss has decreased
    if valid_loss < valid_loss_min:
        torch.save(model, 'model.pt')
        print('Validation loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(
        valid_loss_min,
        valid_loss))
        valid_loss_min = valid_loss
# return trained model
return model

‘’’
Is this correct.

Thanks for the code. Could you please specify the exact error you are now facing with this code?
As for the changes you’ve made in your last post, those do not make sense as you’ll be using labels from your own data and not some random labels.

My code was an example to explain the API.

If we consider last to last post. Then it shows IndexError: Target 110 is out of bounds. And this error shows after 1st epoch. .
But how to make changes as per example of your code.

Hello mam,
After the 1st epoch, it throws this error: “IndexError: Target 110 is out of bounds.”
I am using multitask output - 100 classes are for age prediction output i.e. label1 and 2 classes are for gender prediction output i.e. label2. My batch size is 50.
I trying my best to solve this error. But, I still did not get what changes needs to be made.
Can you please explain how to fix the issue?
‘’’
train = torch.utils.data.TensorDataset(X_train_tensor, y_age_train_tensor, y_gender_train_tensor)
test = torch.utils.data.TensorDataset(X_test_tensor, y_age_test_tensor, y_gender_test_tensor)
batch_size = 50
train_dataloader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True, num_workers=4)
test_dataloader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=True, num_workers=4)
import torch.optim as optim
criterion_multioutput = nn.CrossEntropyLoss() # For multilabel output:Age
criterion_binary = nn.CrossEntropyLoss() # For binary output:Gender
optimizer = optim.Adam(net.parameters(), lr=0.001)
‘’’
‘’’

Building Model

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
def init(self):
super(Net, self).init()

    self.conv1 = nn.Conv2d(in_channels = 1, out_channels = 32, kernel_size = 3, padding=1, stride=1)
    self.relu = nn.ReLU()
    self.maxpool = nn.MaxPool2d(kernel_size = 2)
    
    
    self.conv2 = nn.Conv2d(in_channels = 32, out_channels = 64, kernel_size = 3, padding=1, stride=1)
    
    self.conv3 = nn.Conv2d(in_channels = 64, out_channels = 128, kernel_size = 3, padding=1, stride=1)
    
    self.conv4 = nn.Conv2d(in_channels = 128, out_channels = 256, kernel_size = 3, padding=1, stride=1)
    
    #nn.Flatten()
    
    self.fc1 = nn.Linear(in_features = 256*8*8, out_features = 8192)
    
    self.fc2 = nn.Linear(in_features = 8192, out_features = 512) 
    
    self.linear1 = nn.Linear(in_features = 512, out_features = 100) # For age class output
    self.linear2 = nn.Linear(in_features = 512, out_features = 2)   # For gender class output
 
def forward(self, x):
    out = self.conv1(x)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv2(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv3(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    out = self.conv4(out)
    out = self.relu(out)
    out = self.maxpool(out)
    
    #print(out.shape)
    out = out.view(x.size(0),-1)
    out = F.sigmoid(self.fc1(out))
    out = F.sigmoid(self.fc2(out))
    label1 = self.linear1(out)                 # Age output
    label2 = torch.sigmoid(self.linear2(out))  # Gender output
    
    return {'label1': label1, 'label2': label2}      

‘’’
‘’’
import torch.optim as optim
criterion_multioutput = nn.CrossEntropyLoss() # For multilabel output:Age
criterion_binary = nn.CrossEntropyLoss() # For binary output:Gender
optimizer = optim.Adam(net.parameters(), lr=0.001)
‘’’
‘’’
def train_model(model, criterion1, criterion2, optimizer, n_epochs=25):

# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
for epoch in range(1, n_epochs):
    train_loss = 0.0
    valid_loss = 0.0
    
    # train the model #
    model.train()    

    for batch_idx, sample_batched in enumerate(train_dataloader):
        
        image, label1, label2 = sample_batched

        # zero the parameter gradients
        optimizer.zero_grad()
        output = model(image.float())
        
        print("output label1 shape: ",output['label1'].shape) ##>output label1 :  torch.Size([50, 100])
        print("output label2 shape: ",output['label2'].shape) ##>output label2 :  torch.Size([50, 2])
        #print(type(output['label1']))                            ########
        #print(output['label2'])                                  ########
        
        label1_hat = output['label1']
        label2_hat = output['label2']
        
        print("label1 shape: ",label1.shape)      ########## > label1 shape:  torch.Size([50])
        print("label2 shape: ",label2.shape)      ########### > label2 shape:  torch.Size([50])
        #print("Label1: ", label1)                        #############
        #print("label2: ", label2)                          ############
        max_label1 = torch.max(label1)          #############
        print("max_label1: ", max_label1)       ##########
        min_label1 = torch.min(label1)          ###########
        print("min_label1: ", min_label1)       ###############

        # calculate loss
        loss1 = criterion1(label1_hat, label1)
        loss2 = criterion2(label2_hat, label2)
           
        loss = loss1+loss2
        # back prop
        loss.backward()
        # grad
        optimizer.step()
        train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
        if batch_idx % 50 == 0:
            print('Epoch %d, Batch %d loss: %.6f' %
              (epoch, batch_idx + 1, train_loss))
            
    # validate the model #
    model.eval()

    for batch_idx, sample_batched in enumerate(test_dataloader):
        image, label1, label2 = sample_batched

        output = model(image.float())
        
        label1_hat = output['label1']
        label2_hat = output['label2']
                 
        # calculate loss
        loss1=criterion1(label1_hat, label1)
        loss2=criterion2(label2_hat, label2)
      
        loss = loss1+loss2
        valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))
    
    # print training/validation statistics 
    print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
        epoch, train_loss, valid_loss))
    
    ## TODO: save the model if validation loss has decreased
    if valid_loss < valid_loss_min:
        torch.save(model, 'model.pt')
        print('Validation loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(
        valid_loss_min,
        valid_loss))
        valid_loss_min = valid_loss
# return trained model
return model

‘’’

Hi Niraja, as I’d mentioned earlier as well, your target tensor needs to have the values in [0, 99] only.

Please try and inspect the age column of your dataframe and see what data it contains. Can you post what the following code outputs?

print(df_name['age'].value_counts())

print(df[‘age’].value_counts())

26 ---- 810
35 ---- 500
28 ---- 490
32 ---- 410
30 ---- 391

91 ---- 2
101 ---- 2
116 ---- 2
111 ---- 1
103 ---- 1
Name: age, Length: 103, dtype: int64

Now as you can see there are values greater than 99 in this column.
Figure out what all values this column contains and define your linear layer accordingly.

According to this [0, nb_classes-1] I changed here age out_features to 102, because length is 103 but still it is showing error -
‘’’ self.fc1 = nn.Linear(in_features = 25688, out_features = 8192)

    self.fc2 = nn.Linear(in_features = 8192, out_features = 512) 
    
    self.linear1 = nn.Linear(in_features = 512, out_features = 102) # For age class output
    self.linear2 = nn.Linear(in_features = 512, out_features = 2)   # For gender class output

After this I have changed
‘’’
self.linear1 = nn.Linear(in_features = 512, out_features = 116) # For age class output
‘’’
‘’’
because for age .unique() it shows following.
‘’’
for column in df:
print(f’{column} : {df[column].unique()}‘)
‘’’
it shows >
age : [100 101 103 105 10 110 111 115 116 11 12 13 14 15 16 17 18 19
1 20 21 22 23 24 25 26 27 28 29 2 30 31 32 33 34 35
36 37 38 39 3 40 41 42 43 44 45 46 47 48 49 4 50 51
52 53 54 55 56 57 58 59 5 60 61 62 63 64 65 66 67 68
69 6 70 71 72 73 74 75 76 78 79 7 80 81 82 83 84 85
86 87 88 89 8 90 91 92 93 95 96 99 9]
but still after
Epoch 1, Batch 1 loss: 5.499494
Epoch 1, Batch 51 loss: 4.840973
Epoch 1, Batch 101 loss: 4.809159
this it throws IndexError: Target 116 is out of bounds. this error.

I trying my best to solve this error. Can you please guide how to fix the issue?

According to this, you have a total of 116 categories, so the output layer should have 116 nodes.
Even then, this column cannot be used directly and you need to subtract 1 from it to be able to use CrossEntropyLoss.

df['age'] = df['age'] - 1

Changes this -

to
self.linear1 = nn.Linear(in_features = 512, out_features = 116)

Hello mam,
Thank you for your guidance. My model has been worked properly.
One more question is - How to improve skills in Machine Learning and Deep Learning?