python - 从 Tensorflow 中的张量中随机选择唯一(不重复)元素
问题描述
这是对这两个 SO 问题的跟进
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”就不能再随机选择该值。
解决方案
设置 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)
推荐阅读
- javascript - 即使 Package.json 有 ""start": "set PORT=3500 && react-scripts start"",带有 React-Service 的 Docker-compose 总是选择 PORT 3000
- c++ - JsonCpp:如何将对象转换/序列化为 Json::Value
- css - SCSS 编译从 css 中删除 -webkit 和 -ms 属性
- obiee - OBIEE:通过 Direct Query 分析执行的过程运行两次。为什么
- javascript - 如何在屏幕锁定或最小化浏览器期间禁用移动设备上的网页音频?
- slack-api - 如何让标准块套件交互组件看起来像模态输入
- c# - FIX 连接停止
- html - 乳胶到html的转换
- javascript - Framer Motion 退出动画没有在带有 react-router-dom 的手风琴上触发
- python-3.x - TypeError:只能在递归函数上将 str(不是“NoneType”)连接到 str