RuntimeError: Expected 3D (unbatched) or 4D (batched) input to conv2d, but got input of size: [1, 1, 374, 402, 3]

username: jrTanvirHasan27
cooked: <p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/5/e/5e44b4e53dec9756376d3b9555113f75c7a3dc19.png" data-download-href="https://discuss.pytorch.org/uploads/default/5e44b4e53dec9756376d3b9555113f75c7a3dc19" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/5/e/5e44b4e53dec9756376d3b9555113f75c7a3dc19.png" alt="image" data-base62-sha1="drW5iAZskN49jOJM7LT9YzT4hXr" width="592" height="500" data-dominant-color="EFEFEF"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">897×757 38.7 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div><br>
I am getting error in this line. I can’t understand why I am getting this.</p>

username: jrTanvirHasan27
cooked: <p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/1/6/16ad695b0ac31956075532a09ec0128f7183dac9.png" data-download-href="https://discuss.pytorch.org/uploads/default/16ad695b0ac31956075532a09ec0128f7183dac9" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/1/6/16ad695b0ac31956075532a09ec0128f7183dac9.png" alt="image" data-base62-sha1="3eC2hJKpy5BO0vLnI5k67g7H5AB" width="690" height="277" data-dominant-color="F7F7F9"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1016×409 23 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div><br>
Had to add in the comment section as new users can’t upload more than one media.</p>

username: ptrblck
cooked: <p><code>nn.Conv2d</code> expects an input in the shape <code>[batch_size, channels, height, width]</code> while you are passing a 5-dimensional input as given in the error message.<br>
Remove the unnecessary dimension and <code>permute</code> the input to have the aforementioned channels-first memory layout.</p>
<p>PS: you can post code snippets by wrapping them into three backticks ```.</p>

username: Ajay_krishan_gairola
cooked: <p><a class="mention" href="/u/jrtanvirhasan27">@jrTanvirHasan27</a><br>
is your problem solved or not?<br>
i am facing the same error?</p>

username: DackJempsey
cooked: <p>You can either reduce the dimension as <a class="mention" href="/u/ptrblck">@ptrblck</a> says, or if available for your use case use the conv3d instead of the 2d counterpart.</p>

username: Giang_Phong
cooked: <p>You can use the .reshape() method to flatten the data. Specifically, if you have a tensor with dimensions [batch_size, num_frames, channels, height, width], you can use .reshape() to turn it into a tensor with dimensions [batch_size * num_frames, channels, height, width]. This means all batch and frame sizes will be stacked together to form a single large batch. Result should be : ([1, 374, 402, 3])</p>

username: fatema_hammad
cooked: <p>I have the same problem but I’m using 3D MRI images which are in nifti format<br>
the original dimension is [170, 195, 160], in which 170 is the number of slices.</p>
<p>I wrote a custom dataset class and a custom transform.</p>
<p>also I tracked the dimension they changes from ([ 1, 1, 170, 195, 160]) to ([1, 1, 1, 170, 195, 160]) before entering the model</p>
<p>how to solve this problem<br>
(I’m using 3D model with conv3d)</p>

username: deepsthecoder
cooked: <p>Hey there,<br>
nn.Conv3d expects the input in the format (N,Cin,D,H,W) → 5 dim. Yours is a 6 dim input.</p>
<ul>
<li>you could reduce a dimension with <code>torch.squeeze()</code> the appropriate dim (1 or 2)</li>
<li>Also, to double check if your inputs match with the expected input format for <code>nn.Conv3d</code>, otherwise permute it accordingly<br>
For more information: <a href="https://pytorch.org/docs/stable/generated/torch.nn.Conv3d.html" class="inline-onebox" rel="noopener nofollow ugc">Conv3d — PyTorch 2.4 documentation</a></li>
</ul>

username: fatema_hammad
cooked: <p>tahnks for quick replay, but I still have a problem.</p>
<p>I wrote this transform class</p>
<p>class ToTensorNIfTI:<br>
def <strong>call</strong>(self, img):<br>
img = np.array(img.get_fdata(), dtype=np.float32) if hasattr(img, ‘get_fdata’) else np.array(img, dtype=np.float32)</p>
<pre><code>    #print(f"Original NIfTI image shape: {img.shape}")
    
    img -= img.min()
    img /= img.max()
    img = torch.tensor(img, dtype=torch.float32)
    #print(f"Tensor shape after ToTensorNIfTI: {img.shape}")

    # Add channel dimension
    if img.ndimension() == 3:  # For 3D images
        img = img.unsqueeze(0)  # Add channel dimension

    
    return img
</code></pre>
<p>so the error was as I said<br>
Expected 4D (unbatched) or 5D (batched) input to conv3d, but got input of size: [1, 1, 1, 160, 195, 170]</p>
<p>and when I removed this lines</p>
<h1><a name="p-453533-add-channel-dimension-1" class="anchor" href="#p-453533-add-channel-dimension-1"></a>Add channel dimension</h1>
<pre><code>    if img.ndimension() == 3:  # For 3D images
        img = img.unsqueeze(0)  # Add channel dimension
</code></pre>
<p>the error became: expected 5D input (got 4D input)</p>
<p>Then I rewrote these lines.</p>
<h1><a name="p-453533-add-channel-dimension-2" class="anchor" href="#p-453533-add-channel-dimension-2"></a>Add channel dimension</h1>
<pre><code>if img.ndimension() == 3:  # For 3D images
    img = img.unsqueeze(0)  # Add channel dimension
</code></pre>
<p>and used reshape()<br>
def train(model, dataloader, optimizer, criterion, device):<br>
model.train()<br>
running_loss = 0.0<br>
corrects = 0<br>
total = 0</p>
<pre><code>for inputs, labels in dataloader:
   # Print input shape before reshaping
   #print(f"Input shape before reshaping: {inputs.shape}")

   # Reshape the input tensor to [batch_size, channels, depth, height, width]
    # Remove the extra dimension (in this case, the dimension of size 1)
 if inputs.ndimension() == 6 and inputs.size(2) == 1:
  inputs = inputs.squeeze(2)  # Remove the dimension with size 
</code></pre>
<p>but the error still<br>
expected 5D input (got 4D input)</p>
<p>so what should I do?</p>

username: ptrblck
cooked: <p>It seems you cannot narrow down where exactly the image dimensions increase so could you post a minimal, formatted, and executable code snippet reproducing the issue?</p>