neouyghur
neouyghur

Reputation: 1647

TensorFlow returns the same value when using numpy random function

I am using Tensorflow with numpy random function, but the output is the same value. How can I generate different values? You may recommend use native tf random functions, but I need to use numpy random function.

import tensorflow as tf
import random


def get_rand():
    return random.randint(0,5)

a = get_rand()
tfprint = tf.Print(a, [a])

for i in range(10):
    print(print(get_rand()))

with tf.Session() as sess:
    for i in range(10):
        sess.run(tfprint)

Upvotes: 0

Views: 642

Answers (2)

freude
freude

Reputation: 3832

You need to feed data using placeholders and the feed_dict variable:

import tensorflow as tf
import random


def get_rand():
    return random.randint(0,5)

a = tf.placeholder(tf.int32)
tfprint = tf.Print(a, [a])


with tf.Session() as sess:
    for i in range(10):
        sess.run(tfprint, feed_dict={a: get_rand()})

You may read more about placeholders here

Upvotes: 0

neouyghur
neouyghur

Reputation: 1647

With tf.py_func, turn the Numpy function to Tensorflow function.

import tensorflow as tf
import random


def get_rand():
    return random.randint(0,5)

a = tf.py_func(get_rand, [], tf.int64)
tfprint = tf.Print(a, [a])

for i in range(10):
    print(get_rand())

with tf.Session() as sess:
    for i in range(10):
        sess.run(tfprint)

Upvotes: 1

Related Questions