# RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 48 but got size 47 for tensor number 1 in the list

**URL:** <https://discuss.pytorch.org/t/runtimeerror-sizes-of-tensors-must-match-except-in-dimension-1-expected-size-48-but-got-size-47-for-tensor-number-1-in-the-list/207490>\
**Category:** Uncategorized\
**Created:** [August 3, 2024, 5:38pm UTC](https://discuss.pytorch.org/t/runtimeerror-sizes-of-tensors-must-match-except-in-dimension-1-expected-size-48-but-got-size-47-for-tensor-number-1-in-the-list/207490 "2024-08-03T17:38:06Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hassan\_Ghavidel](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hassan_ghavidel/32/71175_2.png) [@Hassan\_Ghavidel](https://discuss.pytorch.org/u/Hassan_Ghavidel)\
**Post date:** [August 3, 2024, 5:38pm UTC](https://discuss.pytorch.org/t/runtimeerror-sizes-of-tensors-must-match-except-in-dimension-1-expected-size-48-but-got-size-47-for-tensor-number-1-in-the-list/207490/1 "2024-08-03T17:38:06Z")

</div>

Hi, I am training 181 images with .png format for the purpose of image registration.  
and received this error:

> File “/project/med/Hassan\_Ghavidel/transformer\_target\_localization/code/main\_train\_unsup\_TransMorph.py”, line 228, in   
> train\_val\_test.train\_val\_model\_unsupervised(model, train\_loader, optimizer, config.loss\_name, config.loss\_weights,  
> File “/project/med/Hassan\_Ghavidel/transformer\_target\_localization/code/auxiliary/train\_val\_test.py”, line 61, in train\_val\_model\_unsupervised  
> train\_outputs, train\_ddf = model(torch.cat((train\_inputs, train\_targets), dim=1))  
> File “/project/med/Hassan\_Ghavidel/TransMorph\_Transformer\_for\_Medical\_Image\_Registration/myenv/lib/python3.8/site-packages/torch/nn/modules/module.py”, line 1194, in \_call\_impl  
> return forward\_call(\*input, \*\*kwargs)  
> File “/project/med/Hassan\_Ghavidel/transformer\_target\_localization/code/models/TransMorph.py”, line 838, in forward  
> out = self.up1(out, f2)  
> File “/project/med/Hassan\_Ghavidel/TransMorph\_Transformer\_for\_Medical\_Image\_Registration/myenv/lib/python3.8/site-packages/torch/nn/modules/module.py”, line 1194, in \_call\_impl  
> return forward\_call(\*input, \*\*kwargs)  
> File “/project/med/Hassan\_Ghavidel/transformer\_target\_localization/code/models/TransMorph.py”, line 707, in forward  
> x = torch.cat([x, skip], dim=1)  
> File “/project/med/Hassan\_Ghavidel/TransMorph\_Transformer\_for\_Medical\_Image\_Registration/myenv/lib/python3.8/site-packages/monai/data/meta\_tensor.py”, line 282, in **torch\_function**  
> ret = super(). **torch\_function** (func, types, args, kwargs)  
> File “/project/med/Hassan\_Ghavidel/TransMorph\_Transformer\_for\_Medical\_Image\_Registration/myenv/lib/python3.8/site-packages/torch/\_tensor.py”, line 1279, in **torch\_function**  
> ret = func(\*args, \*_kwargs)  
> RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 48 but got size 47 for tensor number 1 in the list._

the line that code is complaining is  
**x = torch.cat([x, skip], dim=1)**  
located in the following picture:

 ![Screenshot from 2024-08-03 19-32-56](https://discuss.pytorch.org/uploads/default/original/3X/2/8/28eb05c908198f6e9bcdb486dc740e53c9bda762.png)

May you give me a suggestion to solve this issue?

---

<div class="post-metadata">

**Author:** ![OEtzi007](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/o/e36b37/32.png) [@OEtzi007](https://discuss.pytorch.org/u/OEtzi007)\
**Post date:** [August 3, 2024, 5:57pm UTC](https://discuss.pytorch.org/t/runtimeerror-sizes-of-tensors-must-match-except-in-dimension-1-expected-size-48-but-got-size-47-for-tensor-number-1-in-the-list/207490/2 "2024-08-03T17:57:31Z")

</div>

Hi Hassan,  
it seems your two tensors `x` and `skip` do not match up in their dimensions/shape.  
You can check those in the debugger by hovering over their variable names. From the error message I suspect that `x` has a shape of `[48, n, ...]` and `skip` has a shape of `[47, m, ...]`. When you `cat` two tensors along dimensions `1`, that means all other dimensions (specifically dimension 0) need to match in size, e.g. `skip` should also have shape `[48, m, ...]` such that the resulting tensor has shape `[48, n+m, ...]`.  
Perhaps you want to share the shapes of `x` and `skip` (and perhaps also from `x` before the `self.up` function call) in case you have still difficulties in understanding the problem.

---

<div class="post-metadata">

**Author:** ![Hassan\_Ghavidel](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hassan_ghavidel/32/71175_2.png) [@Hassan\_Ghavidel](https://discuss.pytorch.org/u/Hassan_Ghavidel)\
**Post date:** [August 3, 2024, 7:15pm UTC](https://discuss.pytorch.org/t/runtimeerror-sizes-of-tensors-must-match-except-in-dimension-1-expected-size-48-but-got-size-47-for-tensor-number-1-in-the-list/207490/3 "2024-08-03T19:15:27Z")

</div>

Thanks OEtzi for your response.  
in main\_train\_unsup\_TransMorph.py script i had written a class to make all input images with same channels: this is the function:

```auto
class EnsureSingleChannel:
    def __init__ (self, keys):
        self.keys = keys
    def __call__ (self, data):
        for key in self.keys:
            img = data[key]
            if not isinstance(img, torch.Tensor):
                img = torch.tensor(img)
            if img.shape[0] > 1:
                img = img[0:1]
            elif img.shape[0] < 1:
                raise ValueError("Image has less than 1 channel, cannot be processed")
            data[key] = img
        return data

```

then i used it here:

```auto
train_transforms = Compose(
    [
        LoadImaged(keys=["fixed_image", "moving_image"]),
        EnsureChannelFirstd(keys=("fixed_image", "moving_image")),
        EnsureSingleChannel(keys=["fixed_image", "moving_image"]),
        ScaleIntensityRanged(
            keys=["fixed_image", "moving_image"],
            a_min=0,
            a_max=1000,
            b_min=0.0,
            b_max=1.0,
            clip=False,
        ),

```

if i dont use it i will receive imges with two different channels  
RuntimeError: Given groups=1, weight of size [48, 2, 3, 3], expected input[2, 4, 185, 185] to have 2 channels, but got 4 channels instead  
this EnsureSingleChannel function worked for some other input images that some of them were greyscales but for new set of images i receive : RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 48 but got size 47 for tensor number 1 in the list. error

i am thinking maybe i should define a different function for these new images…  
or do you think i should try to manually make `x` and `skip` tensors same size?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [August 4, 2024, 3:35pm UTC](https://discuss.pytorch.org/t/runtimeerror-sizes-of-tensors-must-match-except-in-dimension-1-expected-size-48-but-got-size-47-for-tensor-number-1-in-the-list/207490/4 "2024-08-04T15:35:12Z")

</div>

Double post from [here](https://discuss.pytorch.org/t/sizes-of-tensors-must-match-except-in-dimension-1/147785/7) with follow up.
