首页 > 解决方案 > 如何在 Pytorch 中处理大型 JSON 文件?

问题描述

我正在研究时间序列问题。不同的训练时间序列数据存储在一个大小为 30GB 的大型 JSON 文件中。在 tensorflow 中,我知道如何使用 TF 记录。pytorch中是否有类似的方法?

标签: deep-learningtime-seriespytorch

解决方案


我想IterableDatasetdocs)是你需要的,因为:

  1. 您可能想在没有随机访问的情况下遍历文件;
  2. jsons 中的样本数量不是预先计算的。

我做了一个最小的使用示例,假设数据集文件的每一行都是 json 本身,但是您可以更改逻辑。

import json
from torch.utils.data import DataLoader, IterableDataset


class JsonDataset(IterableDataset):
    def __init__(self, files):
        self.files = files

    def __iter__(self):
        for json_file in self.files:
            with open(json_file) as f:
                for sample_line in f:
                    sample = json.loads(sample_line)
                    yield sample['x'], sample['time'], ...

...

dataset = JsonDataset(['data/1.json', 'data/2.json', ...])
dataloader = DataLoader(dataset, batch_size=32)

for batch in dataloader:
    y = model(batch)

推荐阅读