高效阅读、解析和存储 .txt 文件内容到 Torch 张量中

我有大量的 .txt 文件(可能有大约1000万个),每个文件都具有相同的行/列数。它们实际上是一些单通道图像,像素值用空格隔开。以下是我编写的代码,用于执行此任务,但速度非常慢。我想知道是否有人可以建议更优化/高效的方法来完成此任务:

require 'torch'

f = assert(io.open(txtFilePath, 'r'))
local tempTensor = torch.Tensor(1, 64, 64):fill(0)
local i = 1
for line in f:lines() do
    local l = line:split(' ')
    for key, val in ipairs(l) do
        tempTensor[{1, i, key}] = tonumber(val)
    end
    i = i + 1
end
f:close()
点赞
用户1979882
用户1979882

简而言之,如果可能,修改你的源文件。

我唯一能建议的是使用二进制数据而不是txt作为源文件。 你有长期的方法:f:lines(),line:split(' ')tonumber(val)。它们都使用字符串作为变量。

据我所知,你有这样的文件:

0 10 20

11 18 22

....

所以将你的源更改为二进制,像这样:

<0> <18> <20> <11> <18> <22> ...

其中<18>是十六进制中的一个字节,即12<20>16,等等。

要读取

fid = io.open(sup_filename, "rb")
while true do
  local bytes = fid:read(1)
  if bytes == nil then break end -- EOF
  local st = bytes[0]
  print(st)
end

fid:close()

https://www.lua.org/pil/21.2.2.html 这会快得多。

或许使用正则表达式(而不是:split()lines())可以帮助你,但我不认为。

2016-10-20 07:07:33