火炬:保存张量到csv文件

火炬:保存张量到csv文件,csv,export-to-csv,torch,Csv,Export To Csv,Torch,我一直在和火炬一起工作。我现在的程序需要导出一个包含简化特征矩阵的张量。 我试着做了以下几点: torch.save('t.csv',torch.Tensor({{1,2},{3,4}}),'ascii') 结果是: 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 预期产出: 1, 2, 3 4, 5, 6 我希望有人能想到我该怎么做?保存张量时,torch

我一直在和火炬一起工作。我现在的程序需要导出一个包含简化特征矩阵的张量。 我试着做了以下几点:

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

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
预期产出:

1, 2, 3
4, 5, 6

我希望有人能想到我该怎么做?

保存张量时,torch不仅保存数据,而且还保存其他一些有用的信息,供以后反序列化使用

如果您需要csv序列化,您最好自己实现它

幸运的是,这非常简单

下面是一个简单的例子:

require 'torch'

matrix = torch.Tensor(5,3) -- a 5x3 matrix

matrix:random(1,10) -- matrix initialized with random numbers in [1,10]

print(matrix) -- let's see the matrix content

subtensor = matrix[{{1,3}, {2,3}}] -- let's create a view on the row 1 to 3, for which we take columns 2 to 3 (the view is a 3x2 matrix, note that values are bound to the original tensor)

local out = assert(io.open("./dump.csv", "w")) -- open a file for serialization

splitter = ","
for i=1,subtensor:size(1) do
    for j=1,subtensor:size(2) do
        out:write(subtensor[i][j])
        if j == subtensor:size(2) then
            out:write("\n")
        else
            out:write(splitter)
        end
    end
end

out:close()
我的计算机上矩阵的输出为:

 10  10   6
  4   8   3
  3   8   5
  5   5   5
  1   6   8
[torch.DoubleTensor of size 5x3]
和文件转储内容:

10,6
8,3
8,5

HTH

首先可以使用将张量转换为Lua表。然后使用库将表另存为csv文件。这可能是一个解决方法,但我没有遇到任何问题。

对于简单的表,也可以通过将张量转换为Numpy数组,然后转换为Pandas数据帧来导出

导入pytorch作为火炬
将numpy作为np导入
作为pd进口熊猫
t=火炬张量([[1,2],[3,4]])#虚拟数据
t_np=t.numpy()#转换为numpy数组
df=pd.DataFrame(t_np)#转换为数据帧
df.to_csv(“testfile”,index=False)#保存到文件
#然后,要重新加载:
df=pd.read\u csv(“测试文件”)