如何在 tensorflow_datasets 中加速将张量转换为 numpy 数组的代码?

How to accelerate the code which convert tensor to numpy array in tensorflow_datasets?

虽然我想在 tensorflow_datasets 中将张量转换为 numpy 数组,但我的代码逐渐显着变慢。 现在,我使用 lsun/bedroom 数据集,其中包含超过 300 万张图像。 如何加速我的代码?

我的代码保存每 100,000 张图像有一个 numpy 数组的元组。

train_tf = tfds.load("lsun/bedroom", data_dir="{$my_directory}", download=False)
train_tf = train_tf["train"]
for data in train_tf:
    if d_cnt==0 and d_cnt%100001==0:
        train = (tfds.as_numpy(data["image"]), )
    else:
        train += (tfds.as_numpy(data["image"]), )

    if d_cnt%100000==0 and d_cnt!=0:
        with open("{$my_directory}/lsun.pickle%d"%(d_cnt), "wb") as f:
            pickle.dump(train, f)

    d_cnt += 1

您的 if 条件永远不会在第一次通过后执行,因此您的 train 变量不断累积。

我想你希望条件为:

if d_cnt!=0 and d_cnt%100001==0:
    train = (tfds.as_numpy(data["image"]), )