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

sepehr485: <p>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:<br>
" line 41, in <strong>getitem</strong><br>
image = self.transform(image)<br>
TypeError: ‘module’ object is not callable"</p>
<p>Does anyone know how I can fix it? Below is the code for my data preparation file as well as train.py file.</p>
<pre><code class="lang-auto">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)

</code></pre>
<pre><code class="lang-auto">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)
</code></pre>

setsailforfail: <p>Can you also show the code where you are initializing the class?</p>

sepehr485: <p>Sure. I will edit my initial code to have all codings.</p>
<p>Thanks</p>

srishti-git1110: <p>Hey, you are probably trying to pass <code>train_transform</code> as the value of the argument transform in this line :</p>
<aside class="quote no-group" data-username="sepehr485" data-post="1" data-topic="177159">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/58956e/48.png" class="avatar"> sepehr485:</div>
<blockquote>
<p><code>dataset=CatDogDataset(csv_file="Labels.csv",root_dir="C:/Users/s.eftekharia/Anaconda3/envs/py2/CatDog",transform=transforms)</code></p>
</blockquote>
</aside>
<p>As of you now you are passing the module <code>torchvision.transforms</code> as the value of the argument transform which won’t work and is causing the error.</p>

setsailforfail: <aside class="quote no-group" data-username="sepehr485" data-post="1" data-topic="177159">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/58956e/48.png" class="avatar"> sepehr485:</div>
<blockquote>
<pre><code class="lang-auto">#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()])
</code></pre>
</blockquote>
</aside>
<p>you are init. the class before you specify the transformation, that could be a potential issue.</p>
<aside class="quote no-group quote-modified" data-username="sepehr485" data-post="1" data-topic="177159">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/58956e/48.png" class="avatar"> sepehr485:</div>
<blockquote>
<pre><code class="lang-auto">#Load Data
train_transform = transforms.Compose([ transforms.Resize((224, 224)),
                                       transforms.ToTensor()])
dataset=CatDogDataset(csv_file="Labels.csv",root_dir="C:/Users/s.eftekharia/Anaconda3/envs/py2/CatDog",transform=train_transform)

</code></pre>
</blockquote>
</aside>
<p>try that</p>