Error:- TypeError: 'Tensor' object is not callable

Nevil_Shingala: <p>I am getting an error.</p>
<p><strong>TypeError: ‘Tensor’ object is not callable</strong></p>
<p>Below is my code for convolution Autoencorder for 3D images</p>
<pre><code>class Convo3DAE(nn.Module):
 def __init__(self):
    super(Convo3DAE, self).__init__()
    # Encoder
    self.encoder = nn.Sequential(
        nn.Conv3d(in_channels=3, out_channels=16, kernel_size=3, stride=2),
        nn.BatchNorm3d(num_features=16),
        nn.ReLU(True),
        nn.Conv3d(in_channels=16, out_channels=32, kernel_size=3, stride=2),
        nn.ReLU(True),
        nn.Conv3d(in_channels=32, out_channels=64, kernel_size=3, stride=2),
        nn.ReLU(True),
        nn.Conv3d(in_channels=64, out_channels=128, kernel_size=3, stride=2)
    )

    # Decoder
    self.decoder = nn.Sequential(
        nn.ConvTranspose3d(in_channels=128, out_channels=64, kernel_size=3, stride=2),
        nn.BatchNorm3d(num_features=64),  # Corrected BatchNorm placement
        nn.ReLU(True),
        nn.ConvTranspose3d(in_channels=64, out_channels=32, kernel_size=3, stride=2),
        nn.ReLU(True),
        nn.ConvTranspose3d(in_channels=32, out_channels=16, kernel_size=3, stride=2),
        nn.ReLU(True),
        nn.ConvTranspose3d(in_channels=16, out_channels=3, kernel_size=3, stride=2)
    )

 def forward(self, x):
    encoded = self.encoder(x)
    decoded = self.decoder(encoded)
    return decoded
</code></pre>
<p><strong>This is the Data Loader</strong></p>
<pre><code>def load_img(img_dir, img_list):
 images=[]
 for i, image_name in enumerate(img_list):
    if (image_name.split('.')[1] == 'npy'):

        image = np.load(img_dir+image_name)

        images.append(image)
 images = np.array(images)

 return(images)

def imageLoader(img_dir, img_list, mask_dir, mask_list, batch_size):
 # setting Length to 100
 L = len(img_list)

 #keras needs the generator infinite, so we will use while true
 while True:

    batch_start = 0
    batch_end = batch_size

    while batch_start &lt; L:
        limit = min(batch_end, L)

        X = load_img(img_dir, img_list[batch_start:limit])
        Y = load_img(mask_dir, mask_list[batch_start:limit])
        print(img_list[batch_start:limit])
        yield (X,Y) #a tuple with two numpy arrays with batch_size samples

        batch_start += batch_size
        batch_end += batch_size
        if batch_start &gt;= L:  # If reached end of dataset
            stop_flag = True
            break
    if stop_flag:  # Stop generator after completing one pass through the dataset
        break
</code></pre>
<p><strong>This is the Training Loop</strong></p>
<pre><code>np.random.seed(42)
torch.manual_seed(42)
torch.cuda.manual_seed(42)

n_epochs = 100

training_loss, test_loss = [], []

for epoch in range(n_epochs):
 training_losses, test_losses = [], []
 print(epoch)
 i=0
 for data, _ in train_img_datagen:
  if i &lt;(len(train_img_list_low)/2):
    if type(data) is np.ndarray:
        data = torch.from_numpy(data)
    x = data.permute(0, 4, 1, 2, 3).contiguous()
    x = nn.functional.interpolate(x, size=(127, 127, 127), mode='trilinear', align_corners=False)
    print(i)
    i=i+1
    trng_batch_loss = train_batch(x, model, criterion, optimizer)
    training_losses.append(trng_batch_loss.item())
 training_per_epoch_loss = np.array(training_losses).mean()

 for data, _ in val_img_datagen:
    if type(data) is np.ndarray:
        data = torch.from_numpy(data)
    x = data.permute(0, 4, 1, 2, 3).contiguous()
    x = nn.functional.interpolate(x, size=(127, 127, 127), mode='trilinear', align_corners=False)
    tst_batch_loss = eval_batch(x, model, criterion)
    test_losses.append(tst_batch_loss.item())
 test_per_epoch_loss = np.array(test_losses).mean()

 training_loss.append(training_per_epoch_loss)
 test_loss.append(test_per_epoch_loss)
 print(epoch)
 if (epoch+1) % 10==0:
    print(f'Epoch: {epoch+1}/{n_epochs}\t| Training loss: {training_per_epoch_loss:.4f} |   ', end='')
    print(f'Test loss: {test_per_epoch_loss:.4f}')
</code></pre>
<p><strong>Below is the error</strong></p>
<hr>
<p>TypeError                                 Traceback (most recent call last)<br>
 in &lt;cell line: 5&gt;()<br>
10         x = data.permute(0, 4, 1, 2, 3).contiguous()<br>
11         x = nn.functional.interpolate(x, size=(127, 127, 127), mode=‘trilinear’, align_corners=False)<br>
—&gt; 12         tst_batch_loss = eval_batch(x, model, criterion)<br>
13         test_losses.append(tst_batch_loss.item())<br>
14      test_per_epoch_loss = np.array(test_losses).mean()</p>
<p> in eval_batch(data1, model, criterion)<br>
5       output = model(data.float())<br>
6       loss = criterion(output, data.float())<br>
----&gt; 7       return loss().item()</p>
<p>TypeError: ‘Tensor’ object is not callable</p>

InnovArul: <aside class="quote no-group" data-username="Nevil_Shingala" data-post="1" data-topic="197742">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/nevil_shingala/48/61354_2.png" class="avatar"> Nevil_Shingala:</div>
<blockquote>
<p>loss = criterion(output, data.float())<br>
----&gt; 7 return loss().item()</p>
</blockquote>
</aside>
<p>I think that <code>loss</code> variable in the <code>eval_batch()</code> method is a tensor. Maybe it should be written as <code>return loss.item()</code>?.</p>