首页 > 解决方案 > 如何将 `tf.contrib.lookup.index_table_from_file` 转换为 Tensorflow v2

问题描述

我是 Tensorflow 的新手,正在处理来自 v1 Tensorflow 的代码,但是 Tensorflowtf.contrib不再支持模块,而且我在 V2 中找不到它们的替代品时遇到了麻烦。
我用这段代码禁用了 V2:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

但它仍然不起作用,tf.contrib.lookup.index_table_from_file我得到一个错误 AttributeError: module 'tensorflow_core.compat.v1' has no attribute 'contrib'我尝试在此处查看他们的官方文档,但找不到。

tf.contrib.lookup.index_table_from_fileV2 中函数的替代品是什么 ?

标签: pythontensorflowtensorflow2.0

解决方案


你可以尝试tf.lookup.StaticVocabularyTable达到同样的效果。
如果你想从 TextFile 中获取索引和值,你可以tf.lookup.TextFileInitializertf.lookup.StaticVocabularyTable.

下面是一个例子。

num_oov_buckets = 3
input_tensor = tf.constant(["emerson", "lake", "palmer", "king", "crimnson"])
table = tf.lookup.StaticVocabularyTable(
    tf.lookup.TextFileInitializer(
        filename,
        key_dtype=tf.string, key_index=tf.lookup.TextFileIndex.WHOLE_LINE,
        value_dtype=tf.int64, value_index=tf.lookup.TextFileIndex.LINE_NUMBER,
        delimiter="\t"),
    num_oov_buckets)
out = table.lookup(input_tensor)    

您可以关注Tensorflow 的官方文档以获取更多详细信息。


推荐阅读