ndex_to_string_table_from_file和index_table_from_file
py3。从文件中构建int->string映射和string->int映射,分别返回tf.contrib.lookup.HashTable对象和tf.contrib.lookup.IdTableWithHashBuckets对象,其中的属性及函数参考链接。
但是index_to_string_table_from_file和index_table_from_file都返回的hashtable的key的字符串居然是bytes类型,不是str,可能是因为tf.string默认是utf-8编码的bytes,而不是py3的unicode。
输入:
B-DET
B-TYPE
E-DET
E-TYPE
I-DET
I-TYPE
O
S-DET
S-TYPE
工
代码及输出:
import tensorflow as tf
indices = tf.constant([1, 5, 9], tf.int64)
reverse_vocab_tags = tf.contrib.lookup.index_to_string_table_from_file(
'vocab.tags.txt')
values1 = reverse_vocab_tags.lookup(indices)
values = reverse_vocab_tags.export()
with tf.Session() as sess:
tf.tables_initializer().run()
print(values1.eval())
print(sess.run(values))
[b'B-TYPE' b'I-TYPE' b'\xe5\xb7\xa5']
(array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]), array([b'\xe5\xb7\xa5', b'S-TYPE', b'S-DET', b'O', b'I-TYPE', b'I-DET',
b'E-TYPE', b'E-DET', b'B-TYPE', b'B-DET'], dtype=object))
import tensorflow as tf
features = tf.constant(['工', 'a', 'O', 'b'])
# print(type('工')) # str
reverse_vocab_tags = tf.contrib.lookup.index_table_from_file(
'vocab.tags.txt', key_dtype=tf.dtypes.string
, num_oov_buckets=1)
values = reverse_vocab_tags.lookup(features)
with tf.Session() as sess:
tf.tables_initializer().run()
print(values.eval())
[ 9 10 6 10]
[tf.contrib.lookup.index_table_from_file]
[tf.contrib.lookup.index_to_string_table_from_file]
from: -柚子皮-
ref: