Is there a way to pass dictionary in tf.data.Dataset w/ tf.py_func?

老子叫甜甜 提交于 2019-12-08 07:51:14

问题


I'm using tf.data.Dataset in data processing and I want to do apply some python code with tf.py_func.

BTW, I found that in tf.py_func, I cannot return a dictionary. Is there any way to do it or workaround?

I have code which looks like below

def map_func(images, labels):
    """mapping python function"""
    # do something
    # cannot be expressed as a tensor graph
    return {
        'images': images,
        'labels': labels,
        'new_key': new_value}
def tf_py_func(images, labels):
    return tf.py_func(map_func, [images, labels], [tf.uint8, tf.string], name='blah')

return dataset.map(tf_py_func)

===========================================================================

It's been a while and I forgot I asked this question. I solved it other way around and it was so easy that I felt I was almost a stupid. The problem was:

  1. tf.py_func cannot return dictionary.
  2. dataset.map can return dictionary.

And the answer is: map twice.

def map_func(images, labels):
    """mapping python function"""
    # do something
    # cannot be expressed as a tensor graph
    return processed_images, processed_labels

def tf_py_func(images, labels):
    return tf.py_func(map_func, [images, labels], [tf.uint8, tf.string], name='blah')

def _to_dict(images, labels):
    return { 'images': images, 'labels': labels }

return dataset.map(tf_py_func).map(_to_dict)

回答1:


You could turn the dictionary into a string which you return and then split into a dictionary.

This could look something like this:

return (images + " " + labels + " " + new value)

and then in your other function:

l = map_func(image, label).split(" ")
d['images'] = l[0]
d[
...



回答2:


I have struggled with this problem too (I wanted to pre-process textual data using non-TF functions yet keep everything under the umbrella of Tensorflow's Dataset objects). In fact, there is no need for a double-map() workaround; one has to only embed the Python function while processing each example.

Here's the full example code; tested on colab as well (the first two lines are there for installing dependencies).

!pip install tensorflow-gpu==2.0.0b1
!pip install tensorflow-datasets==1.0.2

from typing import Dict

import tensorflow as tf
import tensorflow_datasets as tfds

# Get a textual dataset using the 'tensorflow_datasets' library
dataset_builder = tfds.text.IMDBReviews()
dataset_builder.download_and_prepare()

# Do not randomly shuffle examples for demonstration purposes
ds = dataset_builder.as_dataset(shuffle_files=False)
training_ds = ds[tfds.Split.TRAIN]

print(training_ds)
# <_OptionsDataset shapes: {text: (), label: ()}, types: {text: tf.string, 
# label: tf.int64}>

# Print the first training example
for example in training_ds.take(1):
    print(example['text'])
    # tf.Tensor(b"As a lifelong fan of Dickens, I have ... realised.",
    # shape=(), dtype=string)

# some global configuration or object which we want to access in the
# processing function
we_want_upper_case = True


def process_string(t: tf.Tensor) -> str:
    # This function must have been called as tf.py_function which means
    # it's always eagerly executed and we can access the .numpy() content
    string_content = t.numpy().decode('utf-8')

    # Now we can do what we want in Python, i.e. upper-case or lower-case
    # depending on the external parameter.
    # Note that 'we_want_upper_case' is a variable defined in the outer scope
    # of the function! We cannot pass non-Tensor objects as parameters here.
    if we_want_upper_case:
        return string_content.upper()
    else:
        return string_content.lower()


def process_example(example: Dict[str, tf.Tensor]) -> Dict[str, tf.Tensor]:
    # I'm using typing (Dict, etc.) just for clarity, it's not necessary

    result = {}
    # First, simply copy all the tensor values
    for key in example:
        result[key] = tf.identity(example[key])

    # Now let's process the 'text' Tensor.
    # Call the 'process_string' function as 'tf.py_function'. Make sure the
    # output type matches the 'Tout' parameter (string and tf.string).
    # The inputs must be in a list: here we pass the string-typed Tensor 'text'.
    result['text'] = tf.py_function(func=process_string,
                                    inp=[example['text']],
                                    Tout=tf.string)
    return result


# We can call the 'map' function which consumes and produces dictionaries
training_ds = training_ds.map(lambda x: process_example(x))

for example in training_ds.take(1):
    print(example['text'])
    # tf.Tensor(b"AS A LIFELONG FAN OF DICKENS, I HAVE ...  REALISED.",
    # shape=(), dtype=string)


来源:https://stackoverflow.com/questions/55411666/is-there-a-way-to-pass-dictionary-in-tf-data-dataset-w-tf-py-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!