Torch : Save tensor to csv file

Viewed 19410

I have been working with Torch. And my current program requires to export a Tensor containing reduced feature matrix. I tried doing the following:

torch.save('t.csv',torch.Tensor({{1,2},{3,4}}),'ascii')

and the output was:

4
1
3
V 1
18
torch.DoubleTensor
2
2 3
3 1
1
4
2
3
V 1
19
torch.DoubleStorage
6
1 2 3 4 5 6

Expected output:

1, 2, 3
4, 5, 6

I'm hoping somebody has an idea as to how I can do this?

3 Answers

For simple tables, you can also export by converting the tensor to a Numpy array and then to a Pandas dataframe.

import pytorch as torch
import numpy as np
import pandas as pd

t = torch.tensor([[1,2],[3,4]]) #dummy data

t_np = t.numpy() #convert to Numpy array
df = pd.DataFrame(t_np) #convert to a dataframe
df.to_csv("testfile",index=False) #save to file

#Then, to reload:
df = pd.read_csv("testfile")
Related