tensorflow随机性设置

案例一: 

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()

上述代码重复运行会产生不一样的结果

 

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,seed=42)
print(a.eval())
print(a_shuf.eval())
sess.close()

这段代码产生相同的结果

 

案例二:
 

# using global seed
tf.set_random_seed(1)
fc1_W = tf.Variable(tf.truncated_normal(shape=(2, 2), mean=0, stddev=1))
fc2_W = tf.Variable(tf.truncated_normal(shape=(2, 2), mean=0, stddev=1))

# initialize session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print('\n variables with global seed ')
    print('round 2.0')
    print(fc1_W.eval(sess))
    print(fc2_W.eval(sess))

# new session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print('round 2.1')
    print(fc1_W.eval(sess))
    print(fc2_W.eval(sess))

第一次运行:
 variables with global seed 
round 2.0
[[-0.89710885  0.39287093]
 [ 0.4009913  -1.9170585 ]]
[[ 1.2090957  -0.13654923]
 [ 1.6384401  -0.18959242]]
round 2.1
[[-0.89710885  0.39287093]
 [ 0.4009913  -1.9170585 ]]
[[ 1.2090957  -0.13654923]
 [ 1.6384401  -0.18959242]]
第一次与第二次不断的创建图,其结果是相同的

第二次运行:
variables with global seed 
round 2.0
[[ 1.1742289   0.03763932]
 [ 0.7202809  -0.52002007]]
[[ 1.5818138   0.81615436]
 [ 1.2647419  -0.6432518 ]]
round 2.1
[[ 1.1742289   0.03763932]
 [ 0.7202809  -0.52002007]]
[[ 1.5818138   0.81615436]
 [ 1.2647419  -0.6432518 ]]

第一次运行与第二次运行结果不相同;

结论:只靠tf.set_random_seed是没有办法做到消除随机性 ,该函数可以在一次运行中,创建的多个图的结果是一样的; 因为从本质上来讲,operation-level的初始值是一样的(因为初始化一次被多个图使用),而graph-level的随机种子相同,所以对于不同的图而言,不存在随机性;

随机性由两个随机种子确认(Operations that rely on a random seed actually derive it from two seeds: the graph-level and operation-level seeds来自 于tensorflow官网)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值