9951 explained code solutions for 126 technologies


python-pytorchHow do I save a PyTorch tensor to a file using Python?


To save a PyTorch tensor to a file using Python, use the following steps:

  1. Import the necessary libraries:
import torch
import numpy as np
  1. Create a tensor object:
x = torch.tensor([1, 2, 3])
  1. Save the tensor to a file:
torch.save(x, 'x_tensor.pt')
  1. Verify that the tensor has been saved correctly by loading it back into memory:
x2 = torch.load('x_tensor.pt')
print(x2)

Output example

tensor([1, 2, 3])
  1. Save the tensor as a numpy array:
np.save('x_tensor.npy', x.numpy())
  1. Verify that the numpy array has been saved correctly by loading it back into memory:
x3 = np.load('x_tensor.npy')
print(x3)

Output example

[1 2 3]
  1. Finally, you can also save the tensor to a text file:
torch.save(x, open('x_tensor.txt', 'w'))

Helpful links

Edit this code on GitHub