View source on GitHub
|
A generic hash table that is immutable once initialized.
Inherits From: StaticHashTable, TrackableResource
tf.compat.v1.lookup.StaticHashTable(
initializer, default_value, name=None, experimental_is_anonymous=False
)
When running in graph mode, you must evaluate the tensor returned by
tf.tables_initializer() before evaluating the tensor returned by
this class's lookup() method. Example usage in graph mode:
keys_tensor = tf.constant([1, 2])
vals_tensor = tf.constant([3, 4])
input_tensor = tf.constant([1, 5])
table = tf.lookup.StaticHashTable(
tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1)
out = table.lookup(input_tensor)
with tf.Session() as sess:
sess.run(tf.tables_initializer())
print(sess.run(out))
Note that in graph mode if you set experimental_is_anonymous to
True, you should only call Session.run once, otherwise each
Session.run will create (and destroy) a new table unrelated to
each other, leading to errors such as "Table not initialized".
You can do so like this:
keys_tensor = tf.constant([1, 2])
vals_tensor = tf.constant([3, 4])
input_tensor = tf.constant([1, 5])
table = tf.lookup.StaticHashTable(
tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1,
experimental_is_anonymous=True)
with tf.control_dependencies([tf.tables_initializer()]):
out = table.lookup(input_tensor)
with tf.Session() as sess:
print(sess.run(out))
In eager mode, no special code is needed to initialize the table. Example usage in eager mode:
tf.enable_eager_execution()
keys_tensor = tf.constant([1, 2])
vals_tensor = tf.constant([3, 4])
input_tensor = tf.constant([1, 5])
table = tf.lookup.StaticHashTable(
tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1)
print(table.lookup(input_tensor))
Methods
export
export(
name=None
)
Returns tensors of all keys and values in the table.
| Args | |
|---|---|
name
|
A name for the operation (optional). |
| Returns | |
|---|---|
| A pair of tensors with the first tensor containing all keys and the second tensors containing all values in the table. |
lookup
lookup(
keys, name=None
)
Looks up keys in a table, outputs the corresponding values.
The default_value is used for keys not present in the table.
| Args | |
|---|---|
keys
|
Keys to look up. May be either a SparseTensor or dense Tensor.
|
name
|
A name for the operation (optional). |
| Returns | |
|---|---|
A SparseTensor if keys are sparse, a RaggedTensor if keys are ragged,
otherwise a dense Tensor.
|
| Raises | |
|---|---|
TypeError
|
when keys or default_value doesn't match the table data
types.
|
size
size(
name=None
)
Compute the number of elements in this table.
| Args | |
|---|---|
name
|
A name for the operation (optional). |
| Returns | |
|---|---|
| A scalar tensor containing the number of elements in this table. |
__getitem__
__getitem__(
keys
)
Looks up keys in a table, outputs the corresponding values.
View source on GitHub