为张量流数据集的每个 y 添加一个唯一的 id

Add a unique id to every y of a tensorflow dataset

我正在使用 MNIST 和 tensorflow 训练自动编码器。

(ds_train_original, ds_test_original), ds_info = tfds.load(
    "mnist",
    split=["train", "test"],
    shuffle_files=True,
    as_supervised=True,
    with_info=True,
)

batch_size = 2014
def normalize_img(image, label):
    """Normalizes images: `uint8` -> `float32`."""
    return tf.cast(image, tf.float32) / 255.0, label

我想让我的 x 成为图像,而我的 y 成为具有与唯一索引值 (int/float) 关联的相同图像的元组。原因是我想将该 id 传递给我的损失函数。我不想手动迭代和创建一个新的数据集,但如果这是唯一的解决方案,我会接受它。

我已经尝试了多种方法,例如将 map 方法与全局变量一起使用:

lab = -1
def add_label(x, _):
    global lab
    lab += 1
    return (x, (x, [lab]))

ds_train_original = ds_train_original.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
ds_train = ds_train_original.cache()
ds_train = ds_train.shuffle(ds_info.splits["train"].num_examples)
# replace labels by image itself and unique id for decoder/encoder
ds_train = ds_train.map(add_label)

但是,这个 return 0 作为所有输入的索引而不是唯一值。

我也曾尝试通过枚举数据集手动添加标签,但这种方式很费时间。

当应用到数据集的函数不统一时,是否有一种有效的方法来修改 TensorFlow 数据集。

所以在这种情况下我要做的是只使用目标张量的 ref() 方法。每个张量已经有一个唯一的标识符,这个方法允许你访问它。

你可以试试:

import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np

(ds_train_original, ds_test_original), ds_info = tfds.load(
    "mnist",
    split=["train", "test"],
    shuffle_files=True,
    as_supervised=True,
    with_info=True,
)

# save the references to your tensors
ids = np.array([y.ref() for _, y in ds_train_original])

# you can check that they are all unique
print(ids.shape, np.unique(ids).shape)

# find the 42th tensor using the deref()
t = ids[42].deref()
print(t)

# use np.where to find the index of a tensor reference
np.where( ids == t.ref())[0]