Skip to main content
 首页 » 编程设计

python之tensorflow之向量中的前 k 个值到二进制向量

2024年11月24日31落叶无声

假设我有一个值为 [0,4,1,2,8,7,0,2] 的向量,我怎样才能得到前 k 个值的二进制向量 (k = 3) [0,1,0,0,1,1,0,0] tensorflow?

请您参考如下方法:

TensorFlow 的 tf.math.top_k会为你找到值(value)。但是要获得二进制掩码,您需要 tf.scatter_nd .

此代码必须适用于该任务:

x = tf.convert_to_tensor([0,4,1,2,8,7,0,2]) 
_, indices = tf.math.top_k(x, k=3) 
result = tf.scatter_nd(tf.expand_dims(indices, 1), tf.ones_like(indices), tf.shape(x)) 

输出:

<tf.Tensor: id=47, shape=(8,), dtype=int32, numpy=array([0, 1, 0, 0, 1, 1, 0, 0], dtype=int32)> 

请注意,在 v1.13 之前,top_k 操作在 tf.nn.top_k 下:

_, indices = tf.nn.top_k(x, k=3)