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