1

This is a follow up to these two SO questions

Tensorflow: How to select random values from tensor while excluding padded values?

Randomly selecting elements from a tensor in Tensorflow

Where a solution is given to get a number of random values from a Tensorflow tensor.

The following solution was given

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)

This 'y' randomly selects a number of values (given by the 'size' placeholder) from 'nuMs'. However, this solution can select the same values from 'nuMs' multiple times. For example, here is an example output from this code

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 ]

The array for 'y' has two values of '0.3151272'.

I am looking for a way to uniquely select values from 'nuMs'. In other words, once an value from 'nuMs' has been selected, 'y' can no longer randomly select that value.

SantoshGupta7
  • 5,607
  • 14
  • 58
  • 116

1 Answers1

0

Set replace=False parameter

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

full code

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)
SantoshGupta7
  • 5,607
  • 14
  • 58
  • 116