Convolution neural network

My code is,

import os
import cv2
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

REBUILD_DATA = False

class Mea():

IMG_SIZE = 50
Mea = "T"
LABELS={ Mea:(range(0,360))}
training_data=[]
Meacount = 0

def make_training_data(self):
for label in self.LABELS:
print(label)
for f in tqdm(os.listdir(label)):
path= os.path.join(label,f)
img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
self.training_data.append([np.array(img), np.eye(360)[self.LABELS[label]]])

            np.random.shuffle(self.training_data) 
            np.save("training_data.npy", self.training_data)

if REBUILD_DATA:
MEA=Mea()
MEA.make_training_data()

training_data = np.load(“training_data.npy”,allow_pickle=True)

class Net(nn.Module):

def init(self):
super().init()
self.conv1 = nn.Conv2d(1,32,5)
self.conv2 = nn.Conv2d(32,64,5)
self.conv3 = nn.Conv2d(64,128,5)

 x= torch.randn(50,50).view(-1,1,50,50)
 self._to_linear = None
 self.convs(x)
         
 self.fc1 = nn.Linear(self._to_linear,512)
 self.fc2 = nn.Linear(512,2)

def convs(self, x):

    x=F.max_pool2d(F.relu(self.conv1(x)),(2,2))
    x=F.max_pool2d(F.relu(self.conv2(x)),(2,2))
    x=F.max_pool2d(F.relu(self.conv3(x)),(2,2))

    print(x[0].shape)

    if self._to_linear is None:
      self._to_linear = x[0].shape[0]*x[0].shape[1]*x[0].shape[2]

    return x

def forward(self, x):
x= self.convs(x)
x= x.view(-1, self._to_linear)
x= F.relu(self.fc1(x))
x= self.fc2(x)

     return F.softmax(x, dim=1)

net = Net()
#print(net)

optimizer = optim.Adam(net.parameters(), lr=0.001)
loss_function = nn.MSELoss()

x= torch.Tensor([i[0] for i in training_data]).view(-1,50,50)
x= x/255.0
y= torch.Tensor([i[1] for i in training_data])

VAL_PCT=0.1
val_size=int(len(x)*VAL_PCT)
#print(val_size)

train_x = x[:-val_size]
train_y = y[:-val_size]

test_x = x[-val_size:]
test_y = y[-val_size:]

print(len(train_x), len(test_x))

BATCH_SIZE = 100
EPOCHS = 1

for epoch in range(EPOCHS):
for i in tqdm(range(0, len(train_x), BATCH_SIZE)):
print(f"{i}:{i+BATCH_SIZE}")
batch_x = train_x[i:i+BATCH_SIZE].view(-1, 1, 50, 50)
batch_y = train_y[i:i+BATCH_SIZE]

    net.zero_grad()

    outputs = net(batch_x)
    loss = loss_function(outputs, batch_y)
    loss.backward()
    optimizer.step()   

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

im getting this error,
RuntimeError: The size of tensor a (2) must match the size of tensor b (360) at non-singleton dimension 2

Hi, Julian_Costa,

Please go ahead and set your code inside ``` block, so it looks nice.

Hi,

Could you give the full stack trace that comes with the error? That will tell you which line is causing the issue. You can add printing at this line to check the size of the Tensor and investigate why they are not what you expect.

Warning (from warnings module):
File “C:\Users\Asus\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\loss.py”, line 431
return F.mse_loss(input, target, reduction=self.reduction)
UserWarning: Using a target size (torch.Size([100, 360, 360])) that is different to the input size (torch.Size([100, 2])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.

0%| | 0/4 [00:00<?, ?it/s]
Traceback (most recent call last):
File “C:/Users/Asus/Desktop/Neural Networks/Pytorch.py”, line 115, in
loss = loss_function(outputs, batch_y)
File “C:\Users\Asus\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\module.py”, line 547, in call
result = self.forward(*input, **kwargs)
File “C:\Users\Asus\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\loss.py”, line 431, in forward
return F.mse_loss(input, target, reduction=self.reduction)
File “C:\Users\Asus\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\functional.py”, line 2189, in mse_loss
expanded_input, expanded_target = torch.broadcast_tensors(input, target)
File “C:\Users\Asus\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\functional.py”, line 53, in broadcast_tensors
return torch._C._VariableFunctions.broadcast_tensors(tensors)
RuntimeError: The size of tensor a (2) must match the size of tensor b (360) at non-singleton dimension 2

Hi, have you seen this warning in the stack trace:
Warning (from warnings module):
File “C:\Users\Asus\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\loss.py”, line 431
return F.mse_loss(input, target, reduction=self.reduction)
UserWarning: Using a target size (torch.Size([100, 360, 360])) that is different to the input size (torch.Size([100, 2])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.

So I think the problem is that what you give to your MSE loss are two tensors of different sizes, so it will give unexpected results.