Tensorflow 中的 numpy 随机选择 [英] numpy random choice in Tensorflow

查看:35
本文介绍了Tensorflow 中的 numpy 随机选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there an equivalent function to numpy random choice in Tensorflow. In numpy we can get an item randomly from the given list with its weights.

 np.random.choice([1,2,3,5], 1, p=[0.1, 0, 0.3, 0.6, 0])

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

This code will select an item from the given list with p weights.

推荐答案

否,但您可以使用 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

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

The [0][0] part is here, as multinomial expects a row of unnormalized log-probabilities for each element of the batch and also has another dimension for the number of samples.

这篇关于Tensorflow 中的 numpy 随机选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆