Torch7 将Tensor写入csv文件

可能是Torch7使用的人比较少,今天尝试在torch7中将tensor写入csv文件中居然查了一上午。。WTF。。
这里简单介绍一下我查到的几种方法,希望能够帮助到有同样需求的人,也欢迎各种补充。

方法一:直接写入

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("./csv-test-delete-me.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]

然后你保存的csv-test-delete-me.csv文件内容如下:

  10,6
  8,3
  8,5

方法二:csvigo

简单介绍一下csvigo,csvigo是一个专门为lua涉及的与csv文件交互的包,使用起来十分方便,安装也并不复杂:

luarocks install csvigo

更多的使用细节可以去GitHub主页示例查询。

然后,要想直接将torch.Tensor写入csv文件,需要用torch.totable方法首先将tensor转换为table,然后使用csvigo写入文件:

require 'torch'
csv = require 'csvigo'

csvf = csv.File("csv-test-delete-me.csv","w")

matrix = torch.Tensor(5,3) -- a 5x3 matrix
tensorOut = matrix:view(15)  --写入一整行

csvf:write(torch.totable(TestOut))

csvf:close()

参考:https://stackoverflow.com/questions/36158058/torch-save-tensor-to-csv-file

你可能感兴趣的:(torch7,csv)