my question is how to map tensor with a dictionary? for example like this:
dict = {1:3, 2:4}
origin_tensor = tf.Variable([1,2,1], tf.int32)
The dictionary is large. Now, How can I make a map options to map the tensor to tf.Variable([3,4,3], tf.int32) according to the dict ?
What's more, it is no way to use .eval() when mapping, you can think the origin_tensor is a label tensor from batch reader.
We can access the value of a tensor by using indexing and slicing. Indexing is used to access a single value in the tensor. slicing is used to access the sequence of values in a tensor. we can modify a tensor by using the assignment operator.
A tensor is a vector or matrix of n-dimensions that represents all types of data. All values in a tensor hold identical data type with a known (or partially known) shape. The shape of the data is the dimensionality of the matrix or array. A tensor can be originated from the input data or the result of a computation.
A Keras tensor is a symbolic tensor-like object, which we augment with certain attributes that allow us to build a Keras model just by knowing the inputs and outputs of the model. For instance, if a , b and c are Keras tensors, it becomes possible to do: model = Model(input=[a, b], output=c) Arguments.
In Tensorflow 2.0 (compatibility with earlier versions not tested) use tf.lookup
:
dictionary = {1:3, 2:4}
origin_tensor = tf.Variable([1,2,1], dtype=tf.int64)
note: dict
is reserved in python so it is replaced with dictionary
and dtype=tf.int32
is replaced with dtype=tf.int64
for compatibility with tf.lookup.KeyValueTensorInitializer
This is the original tensor:
origin_tensor
>> <tf.Variable 'Variable:0' shape=(3,) dtype=int64, numpy=array([1, 2, 1])>
This is the Tensorflow lookup table made from a key-value tensor initialized from a python dictionary:
table = tf.lookup.StaticVocabularyTable(
tf.lookup.KeyValueTensorInitializer(
list(dictionary.keys()),
list(dictionary.values()),
key_dtype=tf.int64,
value_dtype=tf.int64,
),
num_oov_buckets=1,
)
This is the actual lookup that returns the result_tensor
with desired elements based on the lookup table:
result_tensor = table.lookup(origin_tensor)
Here is the result:
result_tensor
>> <tf.Tensor: id=400475, shape=(3,), dtype=int64, numpy=array([3, 4, 3])>
Cheers!
You can use the tf.map_fn() function. Since the situation you described shows a connection of x=x+1, which can be interpreted in Tensorflow as:
elems = np.array([1, 2])
plus_one = tf.map_fn(lambda x: x + 1, elems)
# plus_one == [3, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With