Tensorflowtf.nn.top_kはマスク抽出値を生成します



Tensorflow Tf Nn Top_k Generates Mask Extraction Value



# By generating boolean tensor: a = tf.convert_to_tensor([[40, 30, 20, 10], [10, 20, 30, 40]]) b = tf.nn.top_k(a, 2) print(sess.run(b)) TopKV2(values=array([[40, 30], [40, 30]], dtype=int32), indices=array([[0, 1], [3, 2]], dtype=int32)) print(sess.run(b).values)) array([[40, 30], [40, 30]], dtype=int32) Kth = tf.reduce_min(b.values) # Find the minimum Top2 = tf.greater_equal(a, kth) # is greater than the minimum value is true print(sess.run(top2)) array([[ True, True, False, False], [False, False, True, True]], dtype=bool) # By generating id after scatter: import tensorflow as tf # Input data a = tf.placeholder(tf.float32, [None, None]) num_top = tf.placeholder(tf.int32, []) # Find top elements a_top, a_top_idx = tf.nn.top_k(a, num_top, sorted=False) # Apply softmax a_top_sm = tf.nn.softmax(a_top) # Reconstruct into original shape a_shape = tf.shape(a) a_row_idx = tf.tile(tf.range(a_shape[0])[:, tf.newaxis], (1, num_top)) Scatter_idx = tf.stack([a_row_idx, a_top_idx], axis=-1) # Generate scatter_index Result = tf.scatter_nd(scatter_idx, a_top_sm, a_shape) # # Test with tf.Session() as sess: result_val = sess.run(result, feed_dict={a: [[2, 5, 4, 7], [7, 5, 6, 8]], num_top: 2}) print(result_val) [[0. 0.11920291 0. 0.880797 ] [0.26894143 0. 0. 0.7310586 ]]