Hi everyone! When I try to run my code below, I get a runtime error saying: Given groups=1, weight of size [64, 3, 7, 7], expected input[32, 256, 256, 3] to have 3 channels, but got 256 channels instead.
However, I wrote code to account for this issue by creating a custom dataset, but I’m not sure what’s wrong.
Custom Dataset
class BreastCancerImages(Dataset):
def __init__(self, csv_file, root_dir, n_channel=3, transform=None, lbl_col_idx=6, image_file_dir='/kaggle/input/rsna-mammography-images-as-pngs/images_as_pngs/train_images_processed'):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied on a sample.
"""
self.n_channel = n_channel
self.d_train = pd.read_csv(csv_file)
self.root_dir = root_dir
self.transform = transform
self.lbl_col_idx = lbl_col_idx
self.files = list(glob(os.path.join(image_file_dir, "**", "*.png")))
def __len__(self):
return len(self.d_train)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
# x
img_name = self.files[idx]
image = open_img(img_name, self.n_channel)
image = torch.tensor(image)
# y
labels = self.d_train.iloc[idx, self.lbl_col_idx]
labels = np.array([labels])
labels = torch.tensor(labels.astype('int'))
return image, labels
ResNet 50
resnet50 = models.resnet50(pretrained = True)
resnet50
for param in resnet50.parameters():
param.requires_grad = False
resnet50.fc = nn.Linear(1000,2)
Training Code
for epoch in range(num_epochs): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')
running_loss = 0.0
print('Finished Training')