from torchvision.datasets import ImageFolder # for using our our own custom dataset
import cv2 # for reading images
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, Dataset # DataLoader class in python where we can pass data
from torchvision.transforms import transforms
import os #manipulate different file paths and get all the images
from torch import nn as nn #neural network
from torch import optim
import torch.cuda
device = ‘cuda’ if torch.cuda.is_available() else ‘cpu’
images = #creating 2 lists where we shall append our lists of images and labels
labels =
dataPath = r’C:\Users\emman\OneDrive\Desktop\PDD\Plant_leave_diseases_dataset_without_augmentation’
subFolder = os.listdir(dataPath)
for folder in subFolder: #iterating through our subfolders to get our images
label = subFolder.index(folder)
path = os.path.join(dataPath,folder) #we are joing the data path with subfolder
for imglist in os.listdir(path):
image = cv2.imread(os.path.join(path,imglist))
images.append(image)
labels.append(label)
class DataPrep(Dataset): #defining a pytorch class
def init(self,features,labels,transform = None):
self.features = features
self.labels = labels
self.transform = transform
def getitem(self,item):
image = self.features[item]
label = self.labels[item]
if self.transform:
image = self.transform(image)
return image , label
def __len__(self): # total length of the dataset
return len(self.labels)
data_trans = transforms.Compose([ #transformation pipeline
transforms.ToTensor(),
transforms.Resize((224,224)), #Resizing images 224 x 224
transforms.Normalize(mean=[0.5], std=[0.5]), #normalise
transforms.RandomHorizontalFlip(), #flipping
transforms.RandomVerticalFlip()
])
dataset = DataPrep(images,labels,data_trans) data pipeline in a shape we want
data_loader = DataLoader(dataset, batch_size=4, shuffle=True) #this will help shuffle images
data_sample = next(iter(data_loader))
print(data_sample)
class PlantDiseaseModel(nn.Module): #class for our model
def init(self):
super(PlantDiseaseModel,self).init()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=10,kernel_size=2,stride=2,padding=0)
self.maxpool = nn.MaxPool2d(kernel_size=2,stride=2,padding=0)
self.activation = nn.ReLU() #to introduce none linearity coverts all the negative values to 0 and maintains +ves
self.linear = nn.Linear(645050,39)
self.flatten = nn.Flatten() #convert multidimensional array or matrices into one dimension vector
def forward(self,data):
data = self.conv1(data)
data = self.activation(data)
data = self.maxpool(data)
data = self.activation(data)
data = self.flatten(data)
data = self.linear(data)
return data
model = PlantDiseaseModel().to(device)
print(model.eval())
learning_rate = 0.001
epoch = 100
optimizer = optim.SGD(model.parameters(),learning_rate)
criterion = nn.CrossEntropyLoss() #loss function
for i in range(epoch):
for image,target in data_loader:
image = image.to(device)
target = target.to(device)
optimizer.zero_grad()
output = model(image)
loss = criterion(output,target) #how far you are from the target and then play with weightd
loss.backward()
optimizer.step()
print(f'Epochs: {i+1} out of {epoch} || Loss: {loss.item()}')
I receive this error RuntimeError: mat1 and mat2 shapes cannot be multiplied (4x200704 and 160000x39)