Writing tensor to a file in a visually readable manner

Question:

In pytorch, I want to write a tensor to a file and visually read the file contents. For example, consider T = torch.tensor([3,4,5,6]). I want to write the tensor T to a file, say file_T.txt, and want to visually read the contents of the file_T.txt, which will be 3,4,5 and 6. How can I achieve this?

Asked By: Kiran

||

Answers:

You can use numpy:

import numpy as np
np.savetxt('my_file.txt', torch.Tensor([3,4,5,6]).numpy())
Answered By: guibs35

You can use numpy.savetxt() but it won’t work if your tensor’s dimensions are higher than 2. Moreover, this method could be used only if your tensor is on a CPU.

Answered By: Tony.sy