Keras equivalent APIs in PyTorch

Hi,

I’ve been trying to work on a project in Keras and would like to implement the same in PyTorch. But, would like some help in the conversions of modules in keras to the same in PyTorch, for eg: ImageDataGenerator, Sequential, Dense, etc.

Please share some article showing the same .
Thanks

Related:

1 Like

Third-party libraries exposing Keras-like API for PyTorch:

1 Like

Hey @GokulNC,
Let me rephrase, how do you implement the ImageDataGenerator Module of Keras with PyTorch’s equivalent.

The above doubt is to reproduce the following code (which uses keras) into a PyTorch one.

    train_image_generator = ImageDataGenerator(
        rescale=1./255,
        rotation_range=90,
        width_shift_range=0.15,
        height_shift_range=0.15,
        horizontal_flip=True,
        zoom_range=0.5,
    )

For Keras ImageDataGenerator, you will have to use a combination of torchvision.datasets.ImageFolder and torch.utils.data.DataLoader. (Refer this for syntax)

For arguments like rescale, rotation_range, width_shift_range, height_shift_range, horizontal_flip, zoom_range, you will have to use transforms or some augmentation libraries.

You have to check the PyTorch Docs for corresponding transforms of those Keras ImageLoader arguments:
TorchVision Transforms - PyTorch Docs

For example:

  • For resize:
    • You can use transforms.Normalize
  • For rotation_range, width_shift_range, height_shift_range, zoom_range:
    • You can use transforms.RandomAffine (set appropriate arguments)
  • For horizontal_flip:
    • transforms.RandomHorizontalFlip

To compose a transform, you stack multiple such transforms like this and pass it to your:

data_transform = transforms.Compose([
        transforms.RandomSizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],
                             std=[0.229, 0.224, 0.225])
    ])

dataset = ImageFolder(image_paths, transforms=data_transform)