How to solve "'module' object is not callable" for image transform

Hello. I am new to Pytorch and trying to detect my images. In my data preparation.py file I have the codes below. When I run my train.py file, I get the Error:
" line 41, in getitem
image = self.transform(image)
TypeError: ‘module’ object is not callable"

Does anyone know how I can fix it? Below is the code for my data preparation file as well as train.py file.

import os
import pandas as pd 
import torch
from torch.utils.data import Dataset
from skimage import io

class CatDogDataset(Dataset):
    def __init__(self, csv_file, root_dir, transform=None):
        self.annotations = pd.read_csv(csv_file)
        self.root_dir = root_dir
        self.transform = transform

    def __len__(self):
        return len(self.annotations)
    
    def __getitem__(self, index):
        image_path = os.path.join(self.root_dir, self.annotations.iloc[index,0])
        image = io.imread(image_path)

        # Extract file extension
        extension = os.path.splitext(image_path)[1]

        # If file extension is not .jpg, rename the file to have a .jpg extension
        if extension != ".jpg":
            new_image_path = os.path.splitext(image_path)[0] + ".jpg"
            os.rename(image_path, new_image_path)
            image_path = new_image_path
            image = io.imread(image_path)

        y_label = torch.tensor(int(self.annotations.iloc[index,1]))

        if self.transform:
            image = self.transform(image)

        return (image, y_label)

import torch
import  torch.nn as nn
import torch.optim as optim 
import torchvision.transforms as transforms
import os
import pandas as pd
import torchvision
from torch.utils.data import (Dataset,DataLoader)
from Dataset_preparation_2 import CatDogDataset



#device setting
device= torch.device('cuda' if torch.cuda.is_available() else 'cpu')

#Hyperparameters

in_channel=3
num_classes=2
learning_rate=0.001
batch_size=2
num_epochs=1



#Load Data
dataset=CatDogDataset(csv_file="Labels.csv",root_dir="C:/Users/s.eftekharia/Anaconda3/envs/py2/CatDog",transform=transforms)

train_transform = transforms.Compose([ transforms.Resize((224, 224)),
                                       transforms.ToTensor()])

train_set = torch.utils.data.Subset(dataset, range(20))
test_set = torch.utils.data.Subset(dataset, range(20, 24))

train_loader=DataLoader(dataset=train_set,batch_size=batch_size,shuffle=True)
test_loader = DataLoader(dataset=test_set, batch_size=batch_size, shuffle=True)


#test_set=DataLoader(dataset=test_set,batch_size=batch_size,shuffle=True)


#using Googlenet to mimick for training.
model=torchvision.models.googlenet(pretrained=True)
model.to(device)

#defining the Loss and Optimizer
Criterion=nn.CrossEntropyLoss()
Optimizer=optim.Adam(model.parameters(), lr=learning_rate)

# Training the  Network

for epoch in range(num_epochs):
    losses = []

    for batch_idx, (data, targets) in enumerate(train_loader):
        # Get data to cuda if possible,
        data = data.to(device=device)
        targets = targets.to(device=device)

        # forward
        scores = model(data)
        loss = Criterion(scores, targets)

        losses.append(loss.item())

        # backward
        Optimizer.zero_grad()
        loss.backward()

        # gradient descent or adam step
        Optimizer.step()

    print(f"Cost at epoch {epoch} is {sum(losses)/len(losses)}")

# Check accuracy on training to see how good our model is:
def check_accuracy(loader,model): 
    num_correct = 0
    num_samples = 0
    model.eval()

    with torch.no_grad():
        for x, y in loader:
            x = x.to(device=device)
            y = y.to(device=device)

            scores = model(x)
            _, predictions = scores.max(1)
            num_correct += (predictions == y).sum()
            num_samples += predictions.size(0)

        print(
            f"Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}"
        )

    model.train()


print("Checking accuracy on Training Set")
check_accuracy(train_loader, model)

print("Checking accuracy on Test Set")
check_accuracy(test_loader, model)

Can you also show the code where you are initializing the class?

Sure. I will edit my initial code to have all codings.

Thanks

Hey, you are probably trying to pass train_transform as the value of the argument transform in this line :

As of you now you are passing the module torchvision.transforms as the value of the argument transform which won’t work and is causing the error.

you are init. the class before you specify the transformation, that could be a potential issue.

try that

1 Like