Tensorflow:tf.contrib.data中dataset.map()的类型不兼容

时间:2017-06-17 11:51:45

标签: tensorflow tensorflow-datasets

使用带有tf.contrib.Dataset.map()的哈希表查找时,它会因以下错误而失败:

TypeError: In op 'hash_table_Lookup', input types ([tf.string, tf.string, tf.int32]) are not compatible with expected types ([tf.string_ref, tf.string, tf.int32])

重现的代码:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

initializer = tf.contrib.lookup.KeyValueTensorInitializer(
    ['one', 'two', 'three'], [1, 2, 3])
hash_table = tf.contrib.lookup.HashTable(initializer, -1)

tensor = tf.convert_to_tensor(['one', 'two', 'three'])
dataset = tf.contrib.data.Dataset.from_tensor_slices(tensor)
dataset = dataset.map(lambda k: hash_table.lookup(k))

抱怨tf.string_reftf.string不兼容。

很奇怪它需要tf.string_ref而不是tf.string。有谁知道为什么会这样,我能做些什么呢?

这些问题与table_ref tf.string_ref here

有关

1 个答案:

答案 0 :(得分:1)

这是TensorFlow 1.3中修复的错误。如果您使用的是TensorFlow 1.2,则以下解决方法应该有效:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

# Use internal library implementation of `lookup_ops` in TensorFlow 1.2.
from tensorflow.python.ops import lookup_ops
initializer = lookup_ops.KeyValueTensorInitializer(
    ['one', 'two', 'three'], [1, 2, 3])
hash_table = lookup_ops.HashTable(initializer, -1)

tensor = tf.convert_to_tensor(['one', 'two', 'three'])
dataset = tf.contrib.data.Dataset.from_tensor_slices(tensor)
dataset = dataset.map(lambda k: hash_table.lookup(k))

直到TensorFlow 1.2,tf.contrib.lookup库使用"reference types"来表示查找表,而在内部库(用于从1.3开始实现tf.contrib.lookup)更现代和兼容使用"resource types"