Loading and saving torchvision transforms

Is it possible to save and load a transform for an image? I would like to have a folder of transformations and load them into different models if possible.

You can make a .py file that contains your custom transformations and then import it

# my_transforms.py
import torchvision.transforms as T

der my_cstm_trnsfrm_1(img):
	preprocess = T.Compose([
  		T.Resize(256),
  		T.CenterCrop(224),
  		T.ToTensor(),
  		T.Normalize(
      			mean=[0.485, 0.456, 0.406],
      			std=[0.229, 0.224, 0.225]
  		)
	])
	return preprocess	

Then you can import it to where you define your dataset you can use something like Image Folder and pass your transform as parameter.

How about using scriptable transformations with torch.nn.Sequential? I tried this out on my image and got a different transformation with the same resize settings

Maybe you can post your code so it will be easier.

My goal is still to output that transformation to a file to read it in elsewhere where the original python file may not have access to. I guess pickle might be the only way since it seems you can only output transformations made to the model itself and they are not exactly the same as using Compose

Hmmm, sorry I don`t think that I am understanding your goal.

If I understand correctly, what you want is a custom module to use inside of your models/architectures (NOT some transform preprocessing for the dataset).

If that is the case you can create your custom nn.Module that you can then use it in your models either alone or inside a nn.Sequential

Still, I think it would be helpful to see the code of what you are trying to do.

Maybe you mean something like this

# File to declare your nn.Module that you want to load somewhere else
class MyCell(torch.nn.Module):
    def __init__(self):
        super(MyCell, self).__init__()

    def forward(self, x, h):
        return x + h

cell = torch.jit.script(MyCell())
print(cell.code)
cell.save('my_cell.pt')
# Other file where you load that module and use it
class MyOtherCell(torch.nn.Module):
    def __init__(self):
        super(MyOtherCell, self).__init__()
        self.loaded = torch.jit.load('my_cell.pt')
        
    def forward(self, x, h):
        return self.loaded(self.loaded(x, h), h)

x = torch.tensor([3, 4])
h = torch.tensor([1, 2])

module = MyOtherCell()
print(module(x, h))

If so, you might want to look into torchscript.