Python Forum

Full Version: TypeError: forward() missing 1 required positional argument: 'x'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Can you please tell me how to solve the error:

Error:
TypeError Traceback (most recent call last) <ipython-input-14-e3fe2d5e1d3e> in <module>() ----> 6 run_train_test() 7 print('\nsucess!') 1 frames <ipython-input-13-3ff21b7150f2> in run_train_test() ---> 17 net = model().cuda() /usr/local/lib/python3.6/dist-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) TypeError: forward() missing 1 required positional argument: 'x'
Full code:
preprocess = transforms.Compose([
    transforms.Resize(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
class KaggleTrainDataset(Dataset):
    def __init__(self):
        dffinal =  pd.read_csv(TRAINCHECK_DATA_DIR + '/dffinal.csv')
        self.uid = dffinal['image_name']
        self.label = dffinal['target']
    def __str__(self):
        string  = ''
        string += '\tlen = %d\n'%len(self)
        return string

    def __len__(self):
        return len(self.uid)

    def __getitem__(self, index):
        image_id = self.uid[index]
        label = self.label[index]
        patth='/check/'|'/copycheck/'|'/copycheck2/'|'/copycheck3/'
        image = cv2.imread(USER_DATA + patth+ '/%s'%(image_id) +'.jpg' , cv2.IMREAD_COLOR)
        return image, image_id, label

def null_train_collate(batch):
    batch_size = len(batch)
    input = []
    image_id = []
    label = []
    for b in range(batch_size):
        input.append(batch[b][0])
        image_id.append(batch[b][1])
        label.append(batch[b][2])
    input = preprocess(input)
    label = torch.from_numpy(label)
        
    return input, image_id, label

def run_train_test():
    num_epochs = 1 
    learning_rate = 0.001
    print('load net training ...')
    model = models.resnet50(pretrained=True)

    for param in model.parameters():
        param.requires_grad = False

    model.fc = nn.Sequential(nn.Linear(2048, 512),
                                 nn.ReLU(),
                                 nn.Linear(512, 2))

    net = model().cuda()
    criterion = nn.CrossEntropyLoss().cuda()
    optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)

  
    dataset = KaggleTrainDataset()
    
    loader  = DataLoader(
        dataset,
        sampler     = SequentialSampler(dataset),
        batch_size  = 8,
        drop_last   = False,
        num_workers = 4,
        pin_memory  = True,
        collate_fn  = null_train_collate
    )


    for epoch in range(num_epochs):


         for batch_idx, (input, image_id, label) in enumerate(loader): 
         
               optimizer.zero_grad()        
               input = input.cuda()
               label = label.float().cuda()                

               loss = criterion(input, label)                           

               loss.backward()                                   
          
               optimizer.step()                                  
    
               if (batch_idx +1) % 8 == 0:                              
                   print('\nEpoch [%d/%d], Step [%d/%d], Loss: %.4f')
#                         %(epoch+1, num_epochs, batch_idx +1, len(dataset)//loader.batch_size, loss.data))

    
    print('training finished')
    torch.save(net.state_dict(), CHECKPOINT_FILE)
    print('model saved')

 
if __name__ == '__main__':
    print( '%s: calling main function ... ')
    run_train_test()
    print('\nsucess!')
looks like you aren't calling a variablex inside your function
Quote:Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise.

Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.
You haven't shown the entire traceback - there's stuff missing between the two calls, since the call to forward doesn't appear in your code.
But what exactly should I change? I didn`t create argument x

I have updated traceback
The ussue was solved by replacing net = model.cuda() insted of net = model().cuda()