如何在张量流中对数据集API中的元素对应用转换?

时间:2019-02-21 00:02:15

标签: python tensorflow tensorflow-datasets

我正在尝试提供包含图像和标签的模型样本。每个图像一个标签。此外,我不想直接输入图像,而是要输入每对图像的差异。请注意,这些图像来自视频,所以这就是我执行这种区别的原因。另外,我考虑了第二个标签,而忽略了第一个标签。

由于这个原因,我做了以下部分成功的事情:

def _parse_function(example_proto):

    # The annotation contains the following features: timestamp; arousal; valence; liking
    features = {
        'image_raw': tf.FixedLenFeature([], tf.string),
        'label': tf.FixedLenFeature([1], tf.float32)
    }

    parsed_features = tf.parse_single_example(example_proto, features)
    # This is how we create one example, that is, extract one example from the database.
    image = tf.decode_raw(parsed_features['image_raw'], tf.uint8)
    image = tf.reshape(image, [112, 112, 3])
    label = parsed_features['label']

    return label, image

def my_flat_map(labels, images):
    label_1 = tf.slice(labels, begin=[0, 0], size=[1, 1])
    label_2 = tf.slice(labels, begin=[1, 0], size=[1, 1])

    image_1 = tf.slice(images, begin=[0, 0, 0, 0], size=[1, -1, -1, -1])
    image_2 = tf.slice(images, begin=[1, 0, 0, 0], size=[1, -1, -1, -1])

    image = image_2 - image_1
    image = tf.squeeze(image, axis=0)

    to_return = tf.data.Dataset.from_tensors((label_2, image_2))
    return to_return

train_dataset = tf.data.TFRecordDataset(filename_train).map(_parse_function)\
            .batch(batch_size=2, drop_remainder=True)\
            .flat_map(my_flat_map)\
            .batch(train_batch_size)

因此,通过这种方式,我将消耗管道中的每2张图像。换句话说,我将考虑图像[image1, image2][image3, image4]依此类推...另一方面,我想得到:[image1, image2]; [image2, image3];然后对它们应用转换,以返回一张图像和一张标签。我知道我必须使用tf.data.Dataset.window api中的window函数;因此,我将batch(batch_size=2, drop_remainder=True)替换为window(size=2, shift=1, drop_remainder=True),并收到以下错误消息:

TypeError: Failed to convert object of type <class 'tensorflow.python.data.ops.dataset_ops._VariantDataset'> to Tensor. 

有什么办法可以解决这个问题?

非常感谢您的帮助。

0 个答案:

没有答案