I'v writed this code to have a custom dataset in pytorch. images are in folders whose…
- User
I'v writed this code to have a custom dataset in pytorch. images are in folders whose name is class of topse images in that folder:
import torch from torch.utils.data import Dataset from pathlib import Path from PIL import Image from torchvision import transforms import matplotlib.pyplot as plt
class TrainDtaset(Dataset): def init(self, path): super().init() self.path = path self.paths = [] self.labels =[] self.path_class = [pth_train for pth_train in self.path.rglob('') if pth_train.is_dir()] self.folder_class = {path_cls.name: cls for cls, path_cls in enumerate(self.path_class)} for pth_class in self.path_class: for path_image in pth_class.rglob(''): self.paths.append(path_image) self.labels.append(self.folder_class[pth_class.name])
codedef __getitem__(self, index): image = Image.open(self.paths[index]).convert('RGB') transform = transforms.Compose( [ transforms.Resize((224, 224)), transforms.ToTensor() ] ) image_tensor = transform(image) label_tensor = torch.tensor(self.labels[index], dtype=torch.int64) return image_tensor, label_tensor def __len__(self): return len(self.paths)please critisize it from the view of eficciency. is it efficient to perform lots of work in init?
this is part of a book:
class SimpleDataset(Dataset): def init(self, X, y): super(SimpleDataset, self).init() self.X = X self.y = y def getitem(self, index): inputs = torch.tensor(self.X[index,:], dtype=torch.float32) This “work” could have gone in the constructor, but you should get into the habit of placing it in getitem. targets = torch.tensor(int(self.y[index]), dtype=torch.int64) return inputs, targets def len(self): return self.X.shape[0] dataset = SimpleDataset(X, y) Makes a PyTorch dataset Notice that we do the minimal amount of work in the constructor and instead move it into the getitem function. This is intentional design and a habit you should emulate when doing deep learning work. In many cases, we need to do non-trivial preprocessing, preparation, and conversions to get our data into a form that a neural network can learn from. If you put those tasks into the getitem function, you get the benefit of PyTorch doing the work on an as-needed basis while you wait for your GPU to finish processing some other batch of data, making your overall process more compute efficient. This becomes really important when you work on larger datasets where preprocessing would cause a long delay up front or require extra memory, and doing the prep only when needed can save you a lot of storage.
- Assistant