pytorch

How to Save and Load Tensors in PyTorch?

In PyTorch, Tensors are multidimensional arrays used for storing and representing data. Tensors have many attributes and methods that enable users to perform different operations on them, such as reshaping, indexing, slicing, arithmetic, and many more. Moreover, PyTorch also provides functions that allow users to save and load tensors in PyTorch.

This blog will illustrate the method of saving and loading tensors in PyTorch.

How to Save and Load Tensors in PyTorch?

To save and load tensors in PyTorch, first, import the PyTorch library and create a desired tensor. Then, use the “torch.save()” method to save a tensor to a specific file. Next, load the saved tensor using the “torch.load()” method. Finally, print the loaded tensor for verification.

Step 1: Import PyTorch Library

First, import the torch library to save and load tensors in PyTorch:

import torch

Step 2: Create Tensor

Then, create the desired tensor. For instance, we have created the following tensor and stored it in the “Tens” variable:

Tens = torch.tensor([4, 1, 9])

Step 3: Save Tensor to File

To save a tensor to the specific file, use the “torch.save()” function, and specify the tensor object and file name as arguments:

torch.save(Tens, 'saved_tensor.pt')

Here:

  • Tens” is our PyTorch tensor.
  • saved_tensor.pt” is the file name where we want to save our tensor:

This will create a file called “saved_tensor.pt” in our current directory as seen below:

It can be observed that the tensor has been saved successfully.

Step 4: Load Tensor From a File

To load a PyTorch tensor from a file, use the “torch.load()” function and define the file name (where we have saved the tensor) as an argument:

Load_Tens = torch.load('saved_tensor.pt')

Step 5: Print Loaded Tensor

Finally, print the loaded tensor to verify whether the tensor has been loaded successfully or not:

print(Load_Tens)

The below output shows that the tensor has been loaded successfully:

Note: You can access our Google Colab Notebook at this link.

We have efficiently explained the method of saving and loading a tensor in PyTorch.

Conclusion

To save a tensor in a specific file in PyTorch, use the “torch.save()” method and specify the tensor object and file name as arguments. To load a saved tensor from a file, use the “torch.load()” method and define the saved tensor file name as an argument. This blog has illustrated the method to save and load tensors in PyTorch.

About the author

Laiba Younas

I have done bachelors in Computer Science. Being passionate about learning new technologies, I am interested in exploring different programming languages and sharing my experience with the world.