TypeError: Compose.__call__() takes 2 positional arguments but 3 were given

username: Girum_Senay
cooked: <p>my code is which is generating error is:</p>
<p>class ToTensor(object):<br>
def <strong>call</strong>(self, sample):<br>
image, mask = sample<br>
image = torch.from_numpy(image).permute(2, 0, 1).float().unsqueeze(0)<br>
mask = torch.from_numpy(mask).long()<br>
return image, mask</p>
<p>transform = transforms.Compose([ToTensor()])<br>
train_dataset = CustomDataset(image_paths, mask_paths, transform=transform)<br>
train_loader = DataLoader(train_dataset, batch_size=2, shuffle=True)<br>
criterion = nn.CrossEntropyLoss()<br>
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)<br>
num_epochs = 10</p>
<p>for epoch in range(num_epochs):<br>
for images, masks in train_loader:<br>
optimizer.zero_grad()</p>
<pre><code>    outputs = model(images)
    loss = criterion(outputs['out'], masks)

    loss.backward()
    optimizer.step()

print(f'Epoch {epoch+1}/{num_epochs}, Loss: {loss.item()}')
</code></pre>
<p>and the error is:</p>
<hr>
<p>TypeError                                 Traceback (most recent call last)<br>
 in &lt;cell line: 2&gt;()<br>
1 num_epochs = 10<br>
2 for epoch in range(num_epochs):<br>
----&gt; 3     for images, masks in train_loader:<br>
4         optimizer.zero_grad()<br>
5</p>
<p>4 frames<br>
 in <strong>getitem</strong>(self, idx)<br>
15         # Apply transformations<br>
16         if self.transform:<br>
—&gt; 17             image, mask = self.transform(image, mask)<br>
18<br>
19         return image, mask</p>
<p>TypeError: Compose.<strong>call</strong>() takes 2 positional arguments but 3 were given<br>
can anyone help me with that</p>

username: ptrblck
cooked: <p>You would have to pass each tensor separately to your transformation as the error message explains.</p>

username: Girum_Senay
cooked: <p>thanks in advance for your help. sorry if am asking a really silly question am new to the frame work. i tried using</p>
<p>class CustomDataset(Dataset):<br>
def <strong>init</strong>(self, image_paths, mask_paths, transform=None):<br>
self.image_paths = image_paths<br>
self.mask_paths = mask_paths<br>
self.transform = transform</p>
<pre><code>def __len__(self):
    return len(self.image_paths)

def __getitem__(self, idx):
    image = load_tiff_image(self.image_paths[idx])
    mask = load_tiff_masks(self.mask_paths[idx])

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

    return image, mask
</code></pre>
<p>class ToTensor(object):<br>
def <strong>call</strong>(self, image, mask):<br>
image = torch.from_numpy(image).permute(2, 0, 1).float()<br>
mask = torch.from_numpy(mask).long()<br>
return image, mask</p>
<p>class Resize(object):<br>
def <strong>init</strong>(self, size):<br>
self.size = size</p>
<pre><code>def __call__(self, image, mask):
    image = tifffile.resize(image, self.size)
    mask = tifffile.resize(mask, self.size)

    return image, mask
</code></pre>
<p>def load_tiff_image(file_path):<br>
image = tifffile.imread(file_path)<br>
image = (image - image.min()) / (image.max() - image.min())</p>
<pre><code>return image
</code></pre>
<p>def load_tiff_masks(file_path):<br>
mask = tifffile.imread(file_path)<br>
mask = (mask &gt; 0).astype(np.uint8)</p>
<pre><code>return mask
</code></pre>
<p>image_folder = “/content/drive/MyDrive/solafun_detectsolarpanels/data/train/s2_image”<br>
mask_folder = “/content/drive/MyDrive/solafun_detectsolarpanels/data/train/mask”</p>
<p>image_file_names = os.listdir(image_folder)<br>
mask_file_names = os.listdir(mask_folder)</p>
<p>image_paths = sorted([os.path.join(image_folder, name) for name in image_file_names])<br>
mask_paths = sorted([os.path.join(mask_folder, name) for name in mask_file_names])</p>
<p>assert len(image_paths) == len(mask_paths), “Number of images and masks do not match”</p>
<p>transform = transforms.Compose([Resize((256, 256)), ToTensor()])<br>
train_dataset = CustomDataset(image_paths, mask_paths, transform=transform)<br>
train_loader = DataLoader(train_dataset, batch_size=2, shuffle=True, collate_fn=lambda x: tuple(zip(*x)))<br>
for images, masks in train_loader:<br>
print(“Batch Size:”, images.shape[1])<br>
print(“Image Shape:”, images.shape[1:])<br>
print(“Mask Shape:”, masks.shape[1:])<br>
break</p>
<p>but still am getting the same error</p>
<hr>
<p>TypeError                                 Traceback (most recent call last)<br>
 in &lt;cell line: 1&gt;()<br>
----&gt; 1 for images, masks in train_loader:<br>
2     print(“Batch Size:”, images.shape[1])<br>
3     print(“Image Shape:”, images.shape[1:])<br>
4     print(“Mask Shape:”, masks.shape[1:])<br>
5     break</p>
<p>4 frames<br>
/usr/local/lib/python3.10/dist-packages/torch/utils/data/dataloader.py in <strong>next</strong>(self)<br>
628                 # TODO(<a href="https://github.com/pytorch/pytorch/issues/76750" class="inline-onebox" rel="noopener nofollow ugc">Bug in dataloader iterator found by mypy · Issue #76750 · pytorch/pytorch · GitHub</a>)<br>
629                 self._reset()  # type: ignore[call-arg]<br>
 → 630             data = self._next_data()<br>
631             self._num_yielded += 1<br>
632             if self._dataset_kind == _DatasetKind.Iterable and \</p>
<p>/usr/local/lib/python3.10/dist-packages/torch/utils/data/dataloader.py in _next_data(self)<br>
672     def _next_data(self):<br>
673         index = self._next_index()  # may raise StopIteration<br>
 → 674         data = self._dataset_fetcher.fetch(index)  # may raise StopIteration<br>
675         if self._pin_memory:<br>
676             data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)</p>
<p>/usr/local/lib/python3.10/dist-packages/torch/utils/data/_utils/fetch.py in fetch(self, possibly_batched_index)<br>
49                 data = self.dataset.<strong>getitems</strong>(possibly_batched_index)<br>
50             else:<br>
—&gt; 51                 data = [self.dataset[idx] for idx in possibly_batched_index]<br>
52         else:<br>
53             data = self.dataset[possibly_batched_index]</p>
<p>/usr/local/lib/python3.10/dist-packages/torch/utils/data/_utils/fetch.py in (.0)<br>
49                 data = self.dataset.<strong>getitems</strong>(possibly_batched_index)<br>
50             else:<br>
—&gt; 51                 data = [self.dataset[idx] for idx in possibly_batched_index]<br>
52         else:<br>
53             data = self.dataset[possibly_batched_index]</p>
<p> in <strong>getitem</strong>(self, idx)<br>
13<br>
14         if self.transform:<br>
—&gt; 15               image, mask = self.transform(image, mask)<br>
16<br>
17         return image, mask</p>
<p>TypeError: Compose.<strong>call</strong>() takes 2 positional arguments but 3 were given</p>
<p>can u suggest to me where i should put your suggustions?</p>

username: ptrblck
cooked: <p>Your custom <code>ToTensor</code> transformation would accept two inputs, but <code>transforms.Compose</code> does not. Since you are using a single transformation only, just use <code>transform = ToTensor()</code> or also provide a custom <code>Compose</code> transformation accepting multiple inputs.</p>