Tensorflow中的numpy随机选择

sel*_*cia 21 python numpy deep-learning tensorflow

在Tensorflow中是否存在与numpy随机选择等效的函数.在numpy中,我们可以从给定列表中随机获取一个项目及其权重.

 np.random.choice([1,2,3,5], 1, p=[0.1, 0, 0.3, 0.6, 0])
Run Code Online (Sandbox Code Playgroud)

此代码将使用p权重从给定列表中选择一个项目.

syg*_*ygi 19

不,但您可以使用tf.multinomial获得相同的结果:

elems = tf.convert_to_tensor([1,2,3,5])
samples = tf.multinomial(tf.log([[1, 0, 0.3, 0.6]]), 1) # note log-prob
elems[tf.cast(samples[0][0], tf.int32)].eval()
Out: 1
elems[tf.cast(samples[0][0], tf.int32)].eval()
Out: 5
Run Code Online (Sandbox Code Playgroud)

[0][0]部分在这里,因为multinomial期望批次的每个元素的一行非标准化的对数概率,并且还具有样本数量的另一个维度.


Pau*_*ulG 6

我和我的团队遇到了同样的问题,需要将所有操作保留为张量流操作并实现“无需替换”版本。

解决方案:

def tf_random_choice_no_replacement_v1(one_dim_input, num_indices_to_drop=3):

    input_length = tf.shape(one_dim_input)[0]

    # create uniform distribution over the sequence
    # for tf.__version__<1.11 use tf.random_uniform - no underscore in function name
    uniform_distribution = tf.random.uniform(
        shape=[input_length],
        minval=0,
        maxval=None,
        dtype=tf.float32,
        seed=None,
        name=None
    )

    # grab the indices of the greatest num_words_to_drop values from the distibution
    _, indices_to_keep = tf.nn.top_k(uniform_distribution, input_length - num_indices_to_drop)
    sorted_indices_to_keep = tf.contrib.framework.sort(indices_to_keep)

    # gather indices from the input array using the filtered actual array
    result = tf.gather(one_dim_input, sorted_indices_to_keep)
    return result
Run Code Online (Sandbox Code Playgroud)

该代码背后的想法是生成一个随机均匀分布,其维度等于您要执行选择的向量的维度。由于分布将产生一系列唯一且能够排名的数字,因此您可以获取前 k 个位置的索引,并将它们用作您的选择。由于前 k 的位置将与均匀分布一样随机,因此它相当于执行随机选择而不进行替换。

这可以对张量流中的任何一维序列执行选择操作。


小智 6

在 tensorflow 2.0tf.compat.v1.multinomial中不推荐使用tf.random.categorical