mat1 and mat2 shapes cannot be multiplied (1×7 and 1×1)

Question:

I am using a linear regression model in PyTorch to predict number of cars sold from car price using fake data:

car_price_tensor
tensor([3., 4., 5., 6., 7., 8., 9.])
number_of_car_sell_tensor
tensor([[7.5000],
        [7.0000],
        [6.5000],
        [6.0000],
        [5.5000],
        [5.0000],
        [4.5000]])

Here’s the network:

import torch.nn as nn
from torch import optim

class LinearRegression(nn.Module):
    def __init__(self, in_dim, out_dim):
        super(LinearRegression, self).__init__()
        self.linear = nn.Linear(in_dim, out_dim, bias=True)
    
    def forward(self, x):
        return self.linear(x)
    
in_dim = 1
out_dim = 1
model = LinearRegression(in_dim,out_dim) 
loss_fn = nn.MSELoss()
lr = 1e-3
epochs = 40
optimizer = optim.SGD(model.parameters(), lr=lr)
X = car_price_tensor
y = number_of_car_sell_tensor


loss_list = []
for epoch in range(epochs):
    out = model(X)
    loss = loss_fn(out, y)
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
    loss_list.append(loss/len(X))
    print("Epoch: {} train loss: {}".format(epoch+1, loss/len(X)))

I receive the following error: mat1 and mat2 shapes cannot be multiplied (1x7 and 1x1)

How can I get the network to work properly?

Asked By: George Garman

||

Answers:

Hey,

The shapes of your input tensors are not compatible for matrix multiplication. You need to reshape your input tensors so that they are compatible.

For example, you can reshape your car_price_tensor to (7,1) and your number_of_car_sell_tensor to (7,1). After reshaping them, they will be compatible with matrix multiplication.

Answered By: MotaBtw