python-3.x - 从张量中获取值的随机索引

标签 python-3.x tensorflow

我有一个包含一些数值的张量张量:

[ [0,0,0,1,1,1], [1,2,1,0,1,0] ... ] 

对于每个张量,我想获得零值的随机索引。 因此,对于第一个张量,可能的输出值为 0,1,2,第二个张量的可能输出值为 3,5。 (我只想从这些可能的结果中随机选择一个,例如 [0,5])

在 tensorflow 中实现此目的的最佳方法是什么?

最佳答案

这是一种可能的解决方案:

import tensorflow as tf

# Input data
nums = tf.placeholder(tf.int32, [None, None])
rows = tf.shape(nums)[0]
# Number of zeros on each row
zero_mask = tf.cast(tf.equal(nums, 0), tf.int32)
num_zeros = tf.reduce_sum(zero_mask, axis=1)
# Random values
r = tf.random_uniform([rows], 0, 1, dtype=tf.float32)
# Multiply by the number of zeros to decide which of the zeros you pick
zero_idx = tf.cast(tf.floor(r * tf.cast(num_zeros, r.dtype)), tf.int32)
# Find the indices of the smallest values, which should be the zeros
_, zero_pos = tf.nn.top_k(-nums, k=tf.maximum(tf.reduce_max(num_zeros), 1))
# Select the corresponding position of each row
result = tf.gather_nd(zero_pos, tf.stack([tf.range(rows), zero_idx], axis=1))
# Test
with tf.Session() as sess:
    x = [[0,0,0,1,1,1],
         [1,2,1,0,1,0]]
    print(sess.run(result, feed_dict={nums: x}))
    print(sess.run(result, feed_dict={nums: x}))
    print(sess.run(result, feed_dict={nums: x}))

示例输出:

[1 3]
[2 5]
[0 3]

如果某些行没有任何零,那么它将选择索引 0,尽管您可以创建一个掩码来过滤这些行,例如:

has_zeros = tf.reduce_any(tf.equal(nums, 0), axis=1)

关于python-3.x - 从张量中获取值的随机索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52226205/

相关文章:

python - 尝试从 DataFrame 或 Matrix 创建热图

python - 从非唯一的项目列表中获取独特的组合,更快吗?

python - 类型错误 : init() missing 1 required positional argument: 'message' using Multiprocessing

python - 如何重载运算符 `in`?

tensorflow - 为 Tensorflow.js 保存 TensorFlow 模型

python-3.x - 如何在 Windows 10 中的 anaconda 发行版上安装 tflearn 模块

tensorflow - 如果未提供值,则初始化占位符

python - 将 tensorflow 估计器转换为 SavedModel 时出错

python - 是否可以覆盖类的 __call__ 方法?

ios - 如何在 iOS 上运行 Tensorflow 对象检测