Hi everyone, can someone help me out?
I am doing a project that consists in create a CNN which identifies if the image has cancer or not.
The problem is when I try to train the model, I can’t iterate the the loader. The error that it does not say anything.
This is the code:
# Training function
def train_mri(model: MRIClassifier, train_loader: DataLoader, criteration: torch.nn.BCEWithLogitsLoss, optimizer: optim.Adam, num_epochs: int):
# Set the model to training mode
model.train()
for epoch in range(num_epochs):
runnin_loss = 0.0
correct = 0
total = 0
for images, labels in train_loader:
images, labels = images.to(device), labels.float().to(device) # Move to GPU
optimizer.zero_grad() # Zero the Gradients
outputs = model(images) # Forward pass
loss = criteration(outputs, labels.unsqueeze(1)) # Compute Loss
loss.backward() # Backward Pass
optimizer.step() # Optimize Weights
runnin_loss += loss.item() # Accumulate Loss
# Calculate Accuracy
predicted = (torch.sigmoid(outputs) > 0.5).float() # Get predicted classes
total += labels.size(0)
correct += (predicted == labels.unsqueeze(1)).sum().item() # Count correct predictions
# Calculate average loss and accuracy
avg_loss = runnin_loss / len(train_loader)
accuracy = 100 * correct / total
print(f"Epoch [{epoch + 1}/{num_epochs}], Loss: {avg_loss:.4f}, Accuracy {accuracy:.4f}%")
model.to(device)
# Define the loss function and optimizer
criteration = torch.nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Train the model
train_mri(model, train_loader, criteration, optimizer, num_epochs=20)
This is the error:
KeyError Traceback (most recent call last)
File c:\Users\asus\miniconda3\envs\Deep-Learning\lib\site-packages\pandas\core\indexes\base.py:3805, in Index.get_loc(self, key)
3804 try:
-> 3805 return self._engine.get_loc(casted_key)
3806 except KeyError as err:
File index.pyx:167, in pandas._libs.index.IndexEngine.get_loc()
File index.pyx:196, in pandas._libs.index.IndexEngine.get_loc()
File pandas\\_libs\\hashtable_class_helper.pxi:7081, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas\\_libs\\hashtable_class_helper.pxi:7089, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 9
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[72], line 8
5 optimizer = optim.Adam(model.parameters(), lr=0.001)
7 # Train the model
----> 8 train_mri(model, train_loader, criteration, optimizer, num_epochs=20)
...
3815 # InvalidIndexError. Otherwise we fall through and re-raise
3816 # the TypeError.
3817 self._check_indexing_error(key)
KeyError: 9