Python Forum
TypeError: forward() missing 1 required positional argument: 'x'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TypeError: forward() missing 1 required positional argument: 'x'
#1
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!')
Reply
#2
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.
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#3
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.
Reply
#4
But what exactly should I change? I didn`t create argument x

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: a bytes-like object is required ZeroX 13 3,838 Jan-07-2023, 07:02 PM
Last Post: deanhystad
  Error TypeError: output_type_handler() takes 2 positional arguments but 6 were given paulo79 1 1,858 Oct-17-2022, 06:29 PM
Last Post: paulo79
  TypeError: a bytes-like object is required, not 'str' - Help Please. IanJ 3 4,674 Aug-29-2022, 05:53 PM
Last Post: deanhystad
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 4,766 Jul-01-2022, 01:23 PM
Last Post: deanhystad
  Error: _vhstack_dispatcher() takes 1 positional argument but 9 were given alexfrol86 3 5,720 May-09-2022, 12:49 PM
Last Post: deanhystad
  What is positional argument self? Frankduc 22 5,493 Mar-06-2022, 01:18 AM
Last Post: Frankduc
  TypeError: missing a required argument: 'y' gible 0 2,847 Dec-15-2021, 02:21 AM
Last Post: gible
  positional argument: 'self' mcmxl22 8 3,195 Dec-13-2021, 10:11 PM
Last Post: deanhystad
  TypeError: missing 3 required positional arguments: wardancer84 9 10,665 Aug-19-2021, 04:27 PM
Last Post: deanhystad
  TypeError: run_oracle_job() missing 1 required positional argument: 'connection_strin python_student 1 1,938 Aug-06-2021, 08:05 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020