如何在TensorFlow中生成随机向量并将其维护以备将来使用? [英] How do I generate a random vector in TensorFlow and maintain it for further use?

查看:361
本文介绍了如何在TensorFlow中生成随机向量并将其维护以备将来使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成一个随机变量并使用两次.但是,当我第二次使用它时,生成器会创建第二个随机变量,该变量与第一个不同.这是演示代码:

I am trying to generate a random variable and use it twice. However, when I use it the second time, the generator creates a second random variable that is not identical to the first. Here is code to demonstrate:

import numpy as np
import tensorflow as tf

# A random variable
rand_var_1 = tf.random_uniform([5],0,10, dtype = tf.int32, seed = 0)
rand_var_2 = tf.random_uniform([5],0,10, dtype = tf.int32, seed = 0)

#Op1
z1 = tf.add(rand_var_1,rand_var_2)

#Op2
z2 = tf.add(rand_var_1,rand_var_2)

init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    z1_op = sess.run(z1)
    z2_op = sess.run(z2)
    print(z1_op,z2_op)

我希望z1_opz2_op相等.我认为这是因为random_uniform op被调用了两次.有没有办法使用TensorFlow(不使用NumPy)来实现这一目标?

I want z1_op and z2_op to be equal. I think this is because the random_uniform op gets called twice. Is there a way to use TensorFlow (without using NumPy) to achieve this?

(我的用例更加复杂,但这是提炼的问题.)

(My use case is more complicated, but this is the distilled question.)

推荐答案

当前代码版本将在每次调用sess.run()时为rand_var_1rand_var_2随机生成一个新值(尽管由于您设置了种子设为0,那么在一次调用sess.run()的情况下,它们将具有相同的值.

The current version of your code will randomly generate a new value for rand_var_1 and rand_var_2 on each call to sess.run() (although since you set the seed to 0, they will have the same value within a single call to sess.run()).

如果要保留随机生成的张量的值以供以后使用,则应将其分配给

If you want to retain the value of a randomly-generated tensor for later use, you should assign it to a tf.Variable:

rand_var_1 = tf.Variable(tf.random_uniform([5], 0, 10, dtype=tf.int32, seed=0))
rand_var_2 = tf.Variable(tf.random_uniform([5], 0, 10, dtype=tf.int32, seed=0))

# Or, alternatively:
rand_var_1 = tf.Variable(tf.random_uniform([5], 0, 10, dtype=tf.int32, seed=0))
rand_var_2 = tf.Variable(rand_var_1.initialized_value())

# Or, alternatively:
rand_t = tf.random_uniform([5], 0, 10, dtype=tf.int32, seed=0)
rand_var_1 = tf.Variable(rand_t)
rand_var_2 = tf.Variable(rand_t)

...然后 tf.initialize_all_variables() 达到预期的效果:

...then tf.initialize_all_variables() will have the desired effect:

# Op 1
z1 = tf.add(rand_var_1, rand_var_2)

# Op 2
z2 = tf.add(rand_var_1, rand_var_2)

init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)        # Random numbers generated here and cached.
    z1_op = sess.run(z1)  # Reuses cached values for rand_var_1, rand_var_2.
    z2_op = sess.run(z2)  # Reuses cached values for rand_var_1, rand_var_2.
    print(z1_op, z2_op)   # Will print two identical vectors.

这篇关于如何在TensorFlow中生成随机向量并将其维护以备将来使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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