RuntimeError: mat1 and mat2 shapes cannot be multiplied (100×784 and 120×84)

Ask Questions Forum: ask Machine Learning Questions to our readersCategory: PyTorchRuntimeError: mat1 and mat2 shapes cannot be multiplied (100×784 and 120×84)
Sai Charan asked 2 weeks ago

class Multilayer_Percertron(nn.Module):
def __init__(self):
super().__init__()
self.d1 = nn.Linear(28*28*1, 120)
self.d2 = nn.Linear(120, 84)
self.d3 = nn.Linear(84, 10)

def forward(self, x):
X = F.relu(self.d1(x))
X = F.relu(self.d2(x))
X = F.relu(self.d3(x))
return F.log_softmax(X, dim=1)

model = Multilayer_Percertron()

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

epochs = 2

for _ in range(epochs):
for images, labels in tqdm(train_loader):
optimizer.zero_grad()

x = images.view(-1, 28*28)
y = model(x)
loss = criterion(y, labels)

loss.backward()
optimizer.step()

correct = 0
total = len(mnist_test)
with torch.no_grad():
for images, labels in tqdm(test_loader):
x = images.view(-1, 28*28)
y = model(x)

prediction = torch.argmax(y, dim=1)
correct += torch.sum((prediction == labels).float())

print(f"Test accuracy: {(correct/total)*100:.2f}")

Your Answer

11 + 19 =