首页 > 解决方案 > 从 Tensorflow 中的张量中随机选择唯一(不重复)元素

问题描述

这是对这两个 SO 问题的跟进

Tensorflow:如何在排除填充值的同时从张量中选择随机值?

从 Tensorflow 中的张量中随机选择元素

给出了从 Tensorflow 张量中获取多个随机值的解决方案。

给出了以下解决方案

import numpy as np
import tensorflow as tf

nuMs  = tf.placeholder(tf.float32, shape=[None, 2]) 
size = tf.placeholder(tf.int32)
y = tf.py_func(lambda x, s: np.random.choice(x.reshape(-1),s), [nuMs , size], tf.float32)
with tf.Session() as sess:
    nuMsO, yO = sess.run([nuMs , y], {nuMs : np.random.rand(4,2), size:5})
    print('nuMs  is ', nuMsO)
    print('y is ' , yO)

这个 'y' 从 'nuMs' 中随机选择一些值(由 'size' 占位符给出)。但是,此解决方案可以多次从“nums”中选择相同的值。例如,这是此代码的示例输出

nuMs  is  [[0.71399564 0.9791763 ]
 [0.3151272  0.02476136]
 [0.26220843 0.24185595]
 [0.02700878 0.48858792]]
y is  [0.71399564 0.02476136 0.3151272  0.9791763  0.3151272 ]

'y' 的数组有两个值 '0.3151272'。

我正在寻找一种从“nums”中唯一选择值的方法。换句话说,一旦从“nuMs”中选择了一个值,“y”就不能再随机选择该值。

标签: pythontensorflow

解决方案


设置 replace=False 参数

np.random.choice(x.reshape(-1),s, replace=False)

完整代码

nuMs  = tf.placeholder(tf.float32, shape=[None, 2]) 
size = tf.placeholder(tf.int32)
y = tf.py_func(lambda x, s: np.random.choice(x.reshape(-1),s, replace=False), [nuMs , size], tf.float32)
with tf.Session() as sess:
    nuMsO, yO = sess.run([nuMs , y], {nuMs : np.random.rand(4,2), size:7})
    print('nuMs  is ', nuMsO)
    print('y is ' , yO)

推荐阅读