Tensorflow Update the first matching item in each row.

Based on this question I want to update the values โ€‹โ€‹of the two-dimensional tensor for the first time in a row when the tf.where condition is met. Here is an example of the code that I use for modeling:

tf.reset_default_graph() graph = tf.Graph() with graph.as_default(): val = "hello" new_val = "goodbye" matrix = tf.constant([["word","hello","hello"], ["word", "other", "hello"], ["hello", "hello","hello"], ["word", "word", "word"] ]) matching_indices = tf.where(tf.equal(matrix, val)) first_matching_idx = tf.segment_min(data = matching_indices[:, 1], segment_ids = matching_indices[:, 0]) sess = tf.InteractiveSession(graph=graph) print(sess.run(first_matching_idx)) 

This will output [1, 2, 0], where 1 is the placement of the first greeting on line 1, 2 is the placement of the first greeting on line 2, and 0 is the placement of the first greeting on line 3.

However, I canโ€™t understand how to get the first match index, which will be updated with a new value - basically I want the first โ€œhelloโ€ to be turned into โ€œgoodbyeโ€. I tried using tf.scatter_update (), but it doesn't seem to work on 2D tensors. Is there a way to change the two-dimensional tensor as described?

0
source share
1 answer

One easy way is to use tf.py_func with a numpy array

 def ch_val(array, val, new_val): idx = np.array([[s, list(row).index(val)] for s, row in enumerate(array) if val in row]) idx = tuple((idx[:, 0], idx[:, 1])) array[idx] = new_val return array ... matrix = tf.Variable([["word","hello","hello"], ["word", "other", "hello"], ["hello", "hello","hello"], ["word", "word", "word"] ]) matrix = tf.py_func(ch_val, [matrix, 'hello', 'goodbye'], tf.string) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(matrix)) # results: [['word' 'goodbye' 'hello'] ['word' 'other' 'goodbye'] ['goodbye' 'hello' 'hello'] ['word' 'word' 'word']] 
0
source

Source: https://habr.com/ru/post/1264119/


All Articles