【问题标题】:Get a random index of a value from a tensor从张量中获取值的随机索引
【发布时间】:2018-09-07 16:07:35
【问题描述】:

我有一个张量,其中包含一些数值:

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

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

在 tensorflow 中实现这一目标的最佳方法是什么?

【问题讨论】:

  • 数据中可以有负数吗? (也就是说,0 是否总是可能的最小值?)

标签: python-3.x tensorflow


【解决方案1】:

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

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)

【讨论】:

  • 谢谢!这对我有用。我会把这个问题留一点,以防万一有人想出一个适用于负数的通用解决方案,但如果没有人这样做,我会尽快标记你的答案。
  • @Xitcod13 感谢您的评论,您是对的。不过,我更新了解决方案,修复了一个错误并稍作更改,使其适用于任何值而无需更多工作。
猜你喜欢
  • 2022-10-23
  • 1970-01-01
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
相关资源
最近更新 更多