# RuntimeError: stack expects each tensor to be equal size,

**URL:** <https://discuss.pytorch.org/t/runtimeerror-stack-expects-each-tensor-to-be-equal-size/202843>\
**Category:** PyTorch Live\
**Created:** [May 16, 2024, 3:31am UTC](https://discuss.pytorch.org/t/runtimeerror-stack-expects-each-tensor-to-be-equal-size/202843 "2024-05-16T03:31:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Shivakumar\_Kannan](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/shivakumar_kannan/32/70041_2.png) [@Shivakumar\_Kannan](https://discuss.pytorch.org/u/Shivakumar_Kannan)\
**Post date:** [May 16, 2024, 3:31am UTC](https://discuss.pytorch.org/t/runtimeerror-stack-expects-each-tensor-to-be-equal-size/202843/1 "2024-05-16T03:31:54Z")

</div>

How to solve this error? Can someone specifically give me a good example of why this error would happen and how to fix it?  
Here is the Error: RuntimeError: stack expects each tensor to be equal 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:** [May 16, 2024, 8:09pm UTC](https://discuss.pytorch.org/t/runtimeerror-stack-expects-each-tensor-to-be-equal-size/202843/2 "2024-05-16T20:09:40Z")

</div>

The error is raised if the shape of all samples creating the batch differs.  
Here is a small example:

```python
class MyDataset(Dataset):
    def __init__ (self, transform=None):
        self.data = [torch.randn(3, 224, 224), torch.randn(3, 250, 250)]
        self.transform = transform
        
    def __len__ (self):
        return len(self.data)
    
    def __getitem__ (self, index):
        x = self.data[index]
        if self.transform:
            x = self.transform(x)
        return x

dataset = MyDataset()

# works
loader = DataLoader(dataset, batch_size=1)
for img in loader:
    print(img.shape)
# torch.Size([1, 3, 224, 224])
# torch.Size([1, 3, 250, 250])

# fails
loader = DataLoader(dataset, batch_size=2)
for img in loader:
    print(img.shape)
# RuntimeError: stack expects each tensor to be equal size, but got [3, 224, 224] at entry 0 and [3, 250, 250] at entry 1

# works again
dataset = MyDataset(transform=transforms.Resize((224, 224)))
loader = DataLoader(dataset, batch_size=2)
for img in loader:
    print(img.shape)
# torch.Size([2, 3, 224, 224])

```

You could resize or pad the samples to create tensors in the same shape.

---

<div class="post-metadata">

**Author:** ![Shivakumar\_Kannan](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/shivakumar_kannan/32/70041_2.png) [@Shivakumar\_Kannan](https://discuss.pytorch.org/u/Shivakumar_Kannan)\
**Post date:** [May 21, 2024, 2:48pm UTC](https://discuss.pytorch.org/t/runtimeerror-stack-expects-each-tensor-to-be-equal-size/202843/3 "2024-05-21T14:48:43Z")

</div>

Here is my code for Music Genre Classification ( I cite Valerio Velardo’s Music Genre classification code and PyTorch website)  
import torch  
import torchaudio  
from torch.utils.data import DataLoader  
from torch import nn  
import numpy as np  
import matplotlib.pyplot as plt

# Global Variables

batch\_size = 20  
n\_mfcc = 40

# Gathering & Loading Data / Device

train\_data = torchaudio.datasets.GTZAN(  
root=“MUSIC\_CLIPS”,  
url=“[http://opihi.cs.uvic.ca/sound/genres.tar.gz](http://opihi.cs.uvic.ca/sound/genres.tar.gz)”,  
folder\_in\_archive=“/Users/shivakannan/PycharmProjects/MUSIC\_GENRE\_CLASSIFICATION\_project/genres\_original”,  
download=True,  
subset=“training”  
)

test\_data = torchaudio.datasets.GTZAN(  
root=“MUSIC\_CLIPS”,  
url=“[http://opihi.cs.uvic.ca/sound/genres.tar.gz](http://opihi.cs.uvic.ca/sound/genres.tar.gz)”,  
folder\_in\_archive=“/Users/shivakannan/PycharmProjects/MUSIC\_GENRE\_CLASSIFICATION\_project/genres\_original”,  
download=True,  
subset=“testing”  
)

train\_load = DataLoader(train\_data, batch\_size=batch\_size, shuffle=True)  
test\_load = DataLoader(test\_data, batch\_size=batch\_size, shuffle=True)

device = torch.device(“mps”)

# Dictionary for mapping

labels = {

```
'blues': torch.tensor(0, dtype=torch.float32),
'classical': torch.tensor(1, dtype=torch.float32),
'country': torch.tensor(2, dtype=torch.float32),
'disco': torch.tensor(3, dtype=torch.float32),
'hiphop': torch.tensor(4, dtype=torch.float32),
'jazz': torch.tensor(5, dtype=torch.float32),
'metal': torch.tensor(6, dtype=torch.float32),
'pop': torch.tensor(7, dtype=torch.float32),
'reggae': torch.tensor(8, dtype=torch.float32),
'rock': torch.tensor(9, dtype=torch.float32)

```

}

# Extracting waveforms

items\_train =   
X\_train =   
y\_train =   
for ii in range(443):  
items\_train.append(torchaudio.datasets.GTZAN. **getitem** (train\_data, n=ii))  
X\_train.append(items\_train[ii][0][0][0:660000])  
y\_train.append(labels[items\_train[ii][2]])

items\_test =   
X\_test =   
y\_test =   
for ii in range(290):  
items\_test.append(torchaudio.datasets.GTZAN. **getitem** (test\_data, n=ii))  
X\_test.append(items\_test[ii][0][0][0:660000])  
y\_test.append(labels[items\_test[ii][2]])

X\_train = torch.from\_numpy(np.array(X\_train))  
y\_train = torch.from\_numpy(np.array(y\_train))  
X\_test = torch.from\_numpy(np.array(X\_test))  
y\_test = torch.from\_numpy(np.array(y\_test))

# EVERYTHING WORKS TILL NOW

num\_segments = 100

# Extracting MFCCs

MFCC\_transform = torchaudio.transforms.MFCC(  
sample\_rate=22050,  
n\_mfcc=n\_mfcc,  
norm=“ortho”,  
log\_mels=False,  
)

MFCC\_train =

for ii in range(443):

```
temp = []
for jj in range(num_segments):

    start_idx = jj * 6600
    end_idx = start_idx + 6600

    signal = X_train[ii][start_idx:end_idx]
    temp.append(MFCC_transform(signal))

MFCC_train.append(temp)

```

MFCC\_train = torch.from\_numpy(np.array(MFCC\_train))

# Everything Works Till Here

MFCC\_test =

for ii in range(290):

```
temp = []
for jj in range(num_segments):

    start_idx = jj * 6600
    end_idx = start_idx + 6600

    signal = X_test[ii][start_idx:end_idx]
    temp.append(MFCC_transform(signal))

MFCC_test.append(temp)

```

MFCC\_test = torch.from\_numpy(np.array(MFCC\_test))

# MFCCs for Training and Testing have been Obtained

# Expected Outputs for Training and Testing have been Obtained

y\_train\_use = torch.zeros((443, 100))  
y\_test\_use = torch.zeros((290, 100))

for ii in range(443):

```
for jj in range(100):

    y_train_use[ii][jj] = y_train[ii]

```

for ii in range(290):

```
for jj in range(100):

    y_test_use[ii][jj] = y_test[ii]

```

# Everything Works Till Here

# Neural Network Class

class NN(nn.Module):

```
def __init__ (self):

    super(). __init__ ()

    self.flatten = nn.Flatten()

    self.linear_relu_stack = nn.Sequential(

        nn.Linear(40*34, 512),
        nn.ReLU(),
        nn.Linear(512, 512),
        nn.ReLU(),
        nn.Linear(512, 10)

    )

def forward(self, x):

    x = self.flatten(x)
    logits = self.linear_relu_stack(x)
    return logits

```

model = NN().to(device)

loss\_fn = nn.CrossEntropyLoss()  
optimizer = torch.optim.Adam(model.parameters(), lr=1e-6)

# Everything Works Till Here

loss\_list =   
idx\_list =   
def train(model, dataloader):

```
count = 0
size = len(dataloader.dataset)
model.train()

for ii in range(443):

    for jj in range(5):

        idx_list.append(count)
        X = MFCC_train[ii][jj * batch_size : jj * batch_size + batch_size]
        #print("XSIZE", X.size())
        y = np.array(y_train_use[ii][jj * batch_size : jj * batch_size + batch_size])
        X = X.to(device)
        y = torch.from_numpy(y).to(device)

        pred = model(X)

        loss = loss_fn(pred, y)
        #print("LOSS", type(loss))

        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        loss_list.append(loss.item())

        count += 1

plt.plot(np.array(idx_list), np.array(loss_list))
plt.show()

```

train(model, train\_load)

The plot for loss for training fluctuates so much.  
Here is the plot:

 ![Figure_1](https://discuss.pytorch.org/uploads/default/original/3X/3/a/3a986f3753cb55933c9bf9607c5841ab58f32bb0.png)

Please explain me possible issues and ways to improve this plot.
