Tensorflow `set_random_seed` 不起作用 [英] Tensorflow `set_random_seed` not working

查看:70
本文介绍了Tensorflow `set_random_seed` 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,多次运行下面的代码在 IPython notebook 中每次都会产生不同的输出:

For example, running the code below several times inside an IPython notebook produces different output each time:

import tensorflow as tf
tf.set_random_seed(42)
sess = tf.InteractiveSession()
a = tf.constant([1, 2, 3, 4, 5])
tf.initialize_all_variables().run()
a_shuf = tf.random_shuffle(a)
print(a.eval())
print(a_shuf.eval())
sess.close()

如果我明确设置种子:a_shuf = tf.random_shuffle(a, seed=42),每次运行后的输出都是一样的.但是,如果我已经调用了 tf.set_random_seed(42),为什么还需要设置种子?

If I set the seed explicitly: a_shuf = tf.random_shuffle(a, seed=42), the output is the same after each run. But why do I need to set the seed if I already call tf.set_random_seed(42)?

使用 numpy 的等效代码就可以工作:

The equivalent code using numpy just works:

import numpy as np
np.random.seed(42)
a = [1,2,3,4,5]
np.random.shuffle(a)
print(a)

推荐答案

那只会设置图级的随机种子.如果连续多次执行此代码段,图形会发生变化,并且两个 shuffle 语句将获得不同的操作级别种子.文档字符串 用于 set_random_seed

That only sets the graph-level random seed. If you execute this snippet several times in a row, the graph will change, and two shuffle statements will get different operation-level seeds. The details are described in the doc string for set_random_seed

要获得确定性的a_shuf,您可以

To get deterministic a_shuf you can either

  1. 在调用之间调用 tf.reset_default_graph()
  2. 为shuffle设置操作级种子:a_shuf = tf.random_shuffle(a, seed=42)

这篇关于Tensorflow `set_random_seed` 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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