gpt4 book ai didi

csv - 手电筒 : Save tensor to csv file

转载 作者:行者123 更新时间:2023-12-04 14:41:21 29 4
gpt4 key购买 nike

我一直在使用 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

关于csv - 手电筒 : Save tensor to csv file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36158058/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com