【问题标题】:Returning specific elements with Dataset api使用 Dataset api 返回特定元素
【发布时间】:2019-03-28 13:40:35
【问题描述】:

我写了一个 tfrecord 文件,其中我有图像和它们的标签。然后我可以使用它们来获取它们

    def parserTrain(record):
        keys_to_features = {
            "image_raw": tf.FixedLenFeature((), tf.string, default_value=""),
            "label": tf.FixedLenFeature((), tf.int64,
                                        default_value=tf.zeros([], dtype=tf.int64)),
        }
        parsed = tf.parse_single_example(record, keys_to_features)

        # Perform additional preprocessing on the parsed data.
        image = tf.image.decode_jpeg(parsed["image_raw"])
        image = tf.reshape(image, [256, 256, 3])

        image = tf.transpose(image, perm=[2, 0, 1])  # channels first
        image = tf.truediv(image, 255.0)
        label = tf.cast(parsed["label"], tf.int32)

        return {"image": image}, label

    # Set up training input function.
    def train_input_fn():
        """Prepare data for training."""
        train_tfrecord = 'Dataset/train_images.tfrecords'

        dataset = tf.data.TFRecordDataset(train_tfrecord)
        dataset = dataset.map(parserTrain)

之后,我想过滤掉一些例子,可能是这样的:

def f(x):
    return x[1] == 1


ds1 = dataset.filter(f)

但我收到此错误:

TypeError: f() 接受 1 个位置参数,但给出了 2 个

【问题讨论】:

    标签: python-3.x tensorflow tensorflow-datasets tfrecord


    【解决方案1】:

    因此,假设您有一个数据集(例如 TFRecordDataset),您可以按如下方式过滤示例:

      dataset = tf.data.TFRecordDataset(filenames=files)
      dataset = dataset.filter(lambda example: example["value"] == value and example["label"] == label)
      dataset = ...
    

    【讨论】:

    • 我想我不完全理解这个问题。所以你需要一个生成器,它返回一个批次,其中每个样本都有相同的标签。但是每批都有不同的标签?
    • 是的,这就是我需要的。如果我创建一个 for 循环然后根据特定标签创建数据集,我能想到的唯一方法是,但我不知道这样做的效率如何
    • @christk 请直接在您的问题中添加更多详细信息。
    • @lhlmgr 我完全改变了问题,直截了当,你可以看看:)
    【解决方案2】:

    在我找到答案后回复我的问题。 元组数据集的过滤函数的正确语法如下:

    def f(im, label):
        return tf.equal(label, 1)
    
    
    ds1 = dataset.filter(f)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      相关资源
      最近更新 更多