繁体   English   中英

如何从 TensorFlow 数据集中提取数据/标签

[英]How to extract data/labels back from TensorFlow dataset

有很多示例如何创建和使用 TensorFlow 数据集,例如

dataset = tf.data.Dataset.from_tensor_slices((images, labels))

我的问题是如何以 numpy 形式从 TF 数据集中取回数据/标签? 换句话说,想要的是上面那行的反向操作,即我有一个 TF 数据集,想从中取回图像和标签。

如果您的tf.data.Dataset被批处理,以下代码将检索所有 y 标签:

y = np.concatenate([y for x, y in ds], axis=0)

假设我们的 tf.data.Dataset 被称为train_dataset ,并且eager_execution (TF 2.x 中的默认设置),您可以像这样检索图像和标签:

for images, labels in train_dataset.take(1):  # only take first element of dataset
    numpy_images = images.numpy()
    numpy_labels = labels.numpy()
  • 内联操作.numpy()在 numpy 数组中转换 tf.Tensors
  • 如果要检索数据集的更多元素,只需增加take方法中的数字即可。 如果你想要所有元素,只需插入-1

我认为我们在这里得到了一个很好的例子:

https://colab.research.google.com/github/tensorflow/datasets/blob/master/docs/overview.ipynb#scrollTo=BC4pEXtkp4K-

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds

# where mnsit train is a tf dataset
mnist_train = tfds.load(name="mnist", split=tfds.Split.TRAIN)
assert isinstance(mnist_train, tf.data.Dataset)

mnist_example, = mnist_train.take(1)
image, label = mnist_example["image"], mnist_example["label"]

plt.imshow(image.numpy()[:, :, 0].astype(np.float32), cmap=plt.get_cmap("gray"))
print("Label: %d" % label.numpy())

因此,数据集的每个单独组件都可以像字典一样访问。 大概不同的数据集有不同的字段名称(波士顿住房不会有图像和价值,但可能有“特征”和“目标”或“价格”:

cnn = tfds.load(name="cnn_dailymail", split=tfds.Split.TRAIN)
assert isinstance(cnn, tf.data.Dataset)
cnn_ex, = cnn.take(1)
print(cnn_ex)

返回一个带有键 ['article', 'highlight'] 的 dict() ,里面有 numpy 字符串。

这是我自己解决问题的方法:

def dataset2numpy(dataset, steps=1):
    "Helper function to get data/labels back from TF dataset"
    iterator = dataset.make_one_shot_iterator()
    next_val = iterator.get_next()
    with tf.Session() as sess:
        for _ in range(steps):
           inputs, labels = sess.run(next_val)
           yield inputs, labels

请注意,此函数将生成数据集批次的输入/标签。 这些步骤控制将从数据集中取出的批次数量。

这对我有用

features = np.array([list(x[0].numpy()) for x in list(ds_test)])
labels = np.array([x[1].numpy() for x in list(ds_test)])



# NOTE: ds_test was created
iris, iris_info = tfds.load('iris', with_info=True)
ds_orig = iris['train']
ds_orig = ds_orig.shuffle(150, reshuffle_each_iteration=False)
ds_train = ds_orig.take(100)
ds_test = ds_orig.skip(100)

如果您可以将图像和标签保留为tf.Tensor ,您可以这样做

images, labels = tuple(zip(*dataset))

将数据集的效果视为zip(images, labels) 当我们想要取回图像和标签时,我们可以简单地解压缩它。

如果您需要 numpy 数组版本,请使用np.array()转换它们:

images = np.array(images)
labels = np.array(labels)
import numpy as np
import tensorflow as tf

batched_features = tf.constant([[[1, 3], [2, 3]],
                                [[2, 1], [1, 2]],
                                [[3, 3], [3, 2]]], shape=(3, 2, 2))
batched_labels = tf.constant([[0, 0],
                              [1, 1],
                              [0, 1]], shape=(3, 2, 1))
dataset = tf.data.Dataset.from_tensor_slices((batched_features, batched_labels))
classes = np.concatenate([y for x, y in dataset], axis=0)
unique = np.unique(classes, return_counts=True)
labels_dict = dict(zip(unique[0], unique[1]))
print(classes)
print(labels_dict)
# {0: 3, 1: 3}

TensorFlow的get_single_element()终于各地可以用来提取数据和标签从数据集中备份。

这避免了使用.map()iter()生成和使用迭代器的需要(这对于大数据集来说可能很昂贵)。

get_single_element()返回封装数据集所有成员的张量(或张量的元组或字典)。 我们需要将批量处理的数据集的所有成员传递到一个元素中。

这可用于获取作为张量数组的特征,或作为元组或字典(张量数组)的特征和标签,具体取决于原始数据集的创建方式。

在 SO 上查看此答案,以获取将特征和标签解包为张量数组元组的示例。

https://www.tensorflow.org/tutorials/images/classification

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
  for i in range(9):
  ax = plt.subplot(3, 3, i + 1)
  plt.imshow(images[i].numpy().astype("uint8"))
  plt.title(class_names[labels[i]])
  plt.axis("off")

您可以使用 TF Dataset 方法unbatch () 取消批处理数据集,然后您可以轻松地从中检索数据和标签:

ds_labels=[]
for images, labels in ds.unbatch():
    ds_labels.append(labels) # or labels.numpy().argmax() for int labels

您可以使用地图功能。

https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map

images = dataset.map(lambda images, labels: images)
labels = dataset.map(lambda images, labels: labels)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM