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 file I have the codes below. When I run my 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 file.

import os
import pandas as pd 
import torch
from 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 import (Dataset,DataLoader)
from Dataset_preparation_2 import CatDogDataset

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



#Load Data

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

train_set =, range(20))
test_set =, range(20, 24))

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


#using Googlenet to mimick for training.

#defining the Loss and Optimizer
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 =
        targets =

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


        # backward

        # gradient descent or adam 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

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

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

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


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.


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