Get RuntimeError: mat1 and mat2 shapes cannot be multiplied when trying to load a test image in the trained model

Shapes of images are the same as the training and i use Grayscale both on training and testing. Here’s the code of model training # Import dependencies
import torch
from torch import nn, save, load
from torch.optim import Adam
from import DataLoader
from RuHandwrittenLetters import RuHandwrittenDataset

Get data

train = RuHandwrittenDataset(‘labels.csv’,‘dataset’)
dataset = DataLoader(train, 64)

Image Classifier Neural Network

class ImageClassifier(nn.Module):
def init(self):
self.model = nn.Sequential(
nn.Conv2d(1, 32, (3, 3)),
nn.Conv2d(32, 64, (3, 3)),
nn.Conv2d(64, 64, (3, 3)),
nn.Linear(64 * (32 - 6) * (32 - 6), 33)

def forward(self, x):
    return self.model(x)

device = torch.device(“cpu”)

Instance of the neural network, loss, optimizer/

clf = ImageClassifier().to(device)
opt = Adam(clf.parameters(), lr=0.09)
loss_fn = nn.CrossEntropyLoss()

Training flow

if name == “main”:
for epoch in range(15): # train for 10 epochs
for batch in dataset:
X, y = batch
X, y =,
yhat = clf(X)
loss = loss_fn(yhat, y)

        # Apply backprop

    print(f"Epoch:{epoch} loss is {loss.item()}")

with open('', 'wb') as f:
    save(clf.state_dict(), f)

and model opener
from torch import load
import test2
import torch
from torchvision.transforms.functional import convert_image_dtype


with open(‘’, ‘rb’) as f:
img_tensor=convert_image_dtype(img_tensor, dtype=torch.float32)


You haven’t posted the stacktrace with the error message but I guess the shape mismatch is raised in the first linear layer. If so you should see the activation shapes as well as the weight shape of the linear layer in the error message. Change the in_features of the linear layer to the activation feature size and it should work.