# AI 이론/TensorFlow Function

TensorFlow tf.lookup

alz 2022. 5. 4. 10:23

tf.lookup 의 모듈에는 다음과 같은 클래스들을 가지고 있습니다.

 

 

KeyValueTensorInitalizer

tf.lookup.KeyValueTensorInitializer(
    keys, values, key_dtype=None, value_dtype=None, name=None
)​

예제를 잠시 보겠습니다.

우선 keys,values값들은 텐서로 이루어져야 합니다.

keys_tensor = tf.constant(['a', 'b', 'c'])
vals_tensor = tf.constant([7, 8, 9])
input_tensor = tf.constant(['a', 'f'])
init = tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor)
table = tf.lookup.StaticHashTable(
    init,
    default_value=-1)
table.lookup(input_tensor).numpy()

다음과같이 keys_tensor와 vals_tensor로 하나씩 mapping 하여 만들어진 dict이라고 생각하면 편할거 같습니다.

(실제로는 dict이 아닌 initializers)

 

 

위의코드를 보기 앞서, StaticHashTable를 살펴보면,

tf.lookup.StaticHashTable(
    initializer, default_value, name=None, experimental_is_anonymous=False
)

A generic hash table that is immutable once initialized. 

다음과 같이 정의되어 있습니다. "한번 초기화되어진 불변한 해쉬테이블" 이라는뜻인데,

인자로는 initalizer, default_value값을 받습니다.

여기서 initalizer를 위에서만든 KeyValueTensorInitializer를 사용합니다. 

init = {'a':7,'b':8,'c':9} 로 생각하면 편할 것같습니다.

 

keys_tensor = tf.constant(['a', 'b', 'c'])
vals_tensor = tf.constant([7, 8, 9])
input_tensor = tf.constant(['a', 'f'])
table = tf.lookup.StaticHashTable(
    tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor),
    default_value=-1)
table.lookup(input_tensor).numpy()

#Initializer Table에 a,b,c만 7,8,9로 정의되어있고, 'f'값은 아직 정의되지 않았으므로 f에 대해서는
# -1을 반환해라
array([7, -1],dtype=int32)

여기서 default_value = -1은 initalizer에 없는 값이라면 그값은 -1로 사용해라 라는 의미입니다.

 

 

StaticVocabularytTable

staticHashTable을 이해했다면 어렵지 않습니다.

tf.lookup.StaticVocabularyTable(
    initializer,
    num_oov_buckets,
    lookup_key_dtype=None,
    name=None,
    experimental_is_anonymous=False
)

 

(oov_buckets이란 out of vocabulary buckets의 줄임말)

init = tf.lookup.KeyValueTensorInitializer(
    keys=tf.constant(['emerson', 'lake', 'palmer']),
    values=tf.constant([0, 1, 2], dtype=tf.int64))
table = tf.lookup.StaticVocabularyTable(
   init,
   num_oov_buckets=5)
  • emerson -> 0
  • lake -> 1
  • palmer -> 2

num_oov_buckets이 5이므로, 3~7까지는 bucket_id로 사용됩니다.

calculated by: hash(<term>) % num_oov_buckets + vocab_size

input_tensor = tf.constant(["emerson", "lake", "palmer",
                            "king", "crimson"])
table[input_tensor].numpy()

#outputs 
array([0,1,2,6,7])

 

'# AI 이론 > TensorFlow Function' 카테고리의 다른 글

TensorFlow tf.strings  (0) 2022.05.04
TensorFlow batch,window 메서드  (0) 2022.05.03