0

I am a beginner in Pytorch and I am stuck on a question for days. I want to save a image which is in Pytorch tensor form as .mat file. I looked but there doesn't seem to be a direct method on converting Pytoch tensors to .mat file. One possible solution which I found was to convert it to numpy array, but since I am using Nvidia GPU, when I try converting Pytorch tensor to numpy array it gives me this error :

fake_images[0] = fake_images[0].numpy()

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first

How do I save Pytorch tensor to .mat file while using GPU?

Joundill
  • 6,828
  • 12
  • 36
  • 50
user48217
  • 1
  • 1

1 Answers1

0

Do as you are told:

from scipy.io import savemat

with torch.no_grad():
  mdic = {'fake_images': [f_.cpu().numpy() for f_ in fake_images]}
  savemat('fake_images.mat', mdic)

You can see some more information on converting pytorch tensors to numpy arrays here.

Shai
  • 111,146
  • 38
  • 238
  • 371