Tensorflow:FailedPreconditionError:表未初始化(使用 tf.data.Dataset API)

bcl*_*man 6 python tensorflow tensorflow-datasets

我将tf.data.DatasetAPI 与tf.contrib.lookup.index_table_from_tensor.

我的数据集是这样创建的:

dataset = tf.data.Dataset.from_tensor_slices(({'reviews': x}, y)))
Run Code Online (Sandbox Code Playgroud)

这是我在做什么:

data_table = tf.contrib.lookup.index_table_from_tensor(tf.constant(data_vocab))
labels_table = tf.contrib.lookup.index_table_from_tensor(tf.constant(labels_vocab))
Run Code Online (Sandbox Code Playgroud)

然后我将一个预处理函数映射到我的dataset

def preprocess(x, y):
    # split on whitespace
    x['reviews'] = tf.string_split([x['reviews']])
    # turn into integers
    return data_table.lookup(x['reviews']), labels_table.lookup(y)
Run Code Online (Sandbox Code Playgroud)

到目前为止一切都很好。但是,当我尝试将我的数据集传递给我的 Keras 模型进行训练时,我得到:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Table not initialized.
Run Code Online (Sandbox Code Playgroud)

我用谷歌搜索,人们建议我需要包括:

sess = tf.Session()
sess.run(tf.tables_initializer())
Run Code Online (Sandbox Code Playgroud)

但现在我得到:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Table not initialized.
     [[Node: hash_table_Lookup = LookupTableFindV2[Tin=DT_STRING, Tout=DT_INT64](hash_table_lookup_placeholder, StringSplit:1, hash_table_lookup_placeholder_1)]]
     [[Node: IteratorGetNext_1 = IteratorGetNext[output_shapes=[[?,?], [?,20]], output_types=[DT_INT64, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](Iterator_1)]]
Run Code Online (Sandbox Code Playgroud)

知道为什么我的查找表仍未初始化/如何解决这个问题吗?

谢谢!

abc*_*ire 2

嗨,这很奇怪,也许以下工作示例会对您有所帮助:

x = ['this is aswesome', 'i dont like it', 'i love it', 'i hate it']
y = ['positive','negative','positive','negative']
data_vocab = list({word for sentence in x for word in sentence.split(' ')})
label_vocab = list(set(y))

dataset = tf.data.Dataset.from_tensor_slices(({'reviews': x}, y))

data_table=tf.contrib.lookup.index_table_from_tensor(tf.constant(data_vocab))
labels_table = tf.contrib.lookup.index_table_from_tensor(tf.constant(label_vocab))

def preprocess(x, y):
    # split on whitespace
    x['reviews'] = tf.string_split([x['reviews']])
    # turn into integers
    return data_table.lookup(x['reviews']), labels_table.lookup(y)

preprocessed = dataset.map(preprocess)

it = preprocessed.make_initializable_iterator()
sess = tf.Session()
sess.run(it.initializer)
sess.run(tf.tables_initializer()) 
Run Code Online (Sandbox Code Playgroud)

如果你打电话sess.run(it.get_next())你会得到(SparseTensorValue(indices=array([[0, 0], [0, 1], [0, 2]]), values=array([2, 7, 4]), dense_shape=array([1, 3])), 1)

希望对你有帮助 !