tf.contrib.lookup.index_to_string_table_from_tensor和tf.nn.top_k()

tf.contrib.lookup.index_to_string_table_from_tensor(
    mapping,
    default_value='UNK',
    name=None
)

Returns a lookup table that maps a Tensor of indices into strings.

1.一維情況

import tensorflow as tf
sess=tf.Session()
mapping_string = tf.constant(["emerson", "lake", "palmer"])
indices1 = tf.constant([0,1,2], tf.int64)
indices2 = tf.constant([0,2], tf.int64)
indices3 = tf.constant([1], tf.int64)
table = tf.contrib.lookup.index_to_string_table_from_tensor(
    mapping_string)
values1 = table.lookup(indices1)
values2 = table.lookup(indices2)
values3 = table.lookup(indices3)
sess.run(tf.tables_initializer())

print(sess.run(mapping_string))

print(sess.run(indices1))
print(sess.run(values1))
print(sess.run(indices2))
print(sess.run(values2))
print(sess.run(indices3))
print(sess.run(values3))

運行結果:
[b’emerson’ b’lake’ b’palmer’]
[0 1 2]
[b’emerson’ b’lake’ b’palmer’]
[0 2]
[b’emerson’ b’palmer’]
[1]
[b’lake’]

2.二維情況

import tensorflow as tf
sess=tf.Session()
mapping_string = tf.constant(["emerson", "lake", "palmer"])
indices1 = tf.constant([[0,1],[1,2],[2,3]], tf.int64)

table = tf.contrib.lookup.index_to_string_table_from_tensor(
    mapping_string)
values1 = table.lookup(indices1)

sess.run(tf.tables_initializer())

print(sess.run(mapping_string))
print(sess.run(indices1))
print(sess.run(values1))

運行結果:
[b’emerson’ b’lake’ b’palmer’]
[[0 1]
[1 2]
[2 3]]
[[b’emerson’ b’lake’]
[b’lake’ b’palmer’]
[b’palmer’ b’UNK’]]

總結:按照張量indices的格式,返回indices中索引的值,格式不變.

3.tf.nn.top_k()
以下以一個5分類爲例,一行表示一個樣本屬於5類的概率.按下面代碼轉化完了後,輸出的每行第一個數字就代表該行樣本所屬的分類.

import tensorflow as tf
import numpy as np
sess=tf.Session()
y=np.array([[0.10,0.20,0.40,0.25,0.05],
            [0.45,0.15,0.10,0.05,0.25],
            [0.15,0.65,0.05,0.10,0.05]])

values,indices=tf.nn.top_k(y,5)
table = tf.contrib.lookup.index_to_string_table_from_tensor(
    tf.constant([str(i) for i in range(5)]))
prediction_classes = table.lookup(tf.to_int64(indices))
sess.run(tf.tables_initializer())
print(sess.run(values))
print(sess.run(indices))
print(sess.run(prediction_classes))

運行結果:
[[0.4 0.25 0.2 0.1 0.05]
[0.45 0.25 0.15 0.1 0.05]
[0.65 0.15 0.1 0.05 0.05]]
[[2 3 1 0 4]
[0 4 1 2 3]
[1 0 3 2 4]]
[[b’2’ b’3’ b’1’ b’0’ b’4’]
[b’0’ b’4’ b’1’ b’2’ b’3’]
[b’1’ b’0’ b’3’ b’2’ b’4’]]
總結: 返回的是每行由大到小排序的結果以及對應的它們在原來數組中的行索引.例如:第一行最大值爲0.4,它在原數組中行索引是2(該行第三個數字).

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章