LoginSignup
5
11

More than 5 years have passed since last update.

TensorFlow と Numpy で乱数の seed 固定ちょい違うやも

Posted at

大変どうでも良いメモ.
TensorFlow の tf.set_random_seed() は Numpy の np.random.seed() と若干挙動が違うっぽい.
Numpy は np.random.seed() する度にシードがリセットされて再び同じ擬似乱数列が生成されるのに対して, TensorFlow はリセットされないみたい.

なんか日本語が不自由な文章を書いてしまったが, 以下のようなコードを実行してみると多分伝わる.

import numpy as np
import tensorflow as tf

print '===== Numpy ====='
np.random.seed(0)
print np.random.uniform(size=5)
print np.random.uniform(size=5)

print 'Numpy can reset seed'
np.random.seed(0)
print np.random.uniform(size=5)
print np.random.uniform(size=5)

print '===== TensorFlow ====='
tf.set_random_seed(0)
with tf.Session() as sess:
    print sess.run(tf.random_uniform([5]))
    print sess.run(tf.random_uniform([5]))

print 'TensorFlow does not reset seed'
tf.set_random_seed(0)
with tf.Session() as sess:
    print sess.run(tf.random_uniform([5]))
    print sess.run(tf.random_uniform([5]))
===== Numpy =====
[ 0.5488135   0.71518937  0.60276338  0.54488318  0.4236548 ]
[ 0.64589411  0.43758721  0.891773    0.96366276  0.38344152]
Numpy can reset seed
[ 0.5488135   0.71518937  0.60276338  0.54488318  0.4236548 ]
[ 0.64589411  0.43758721  0.891773    0.96366276  0.38344152]

===== TensorFlow =====
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 4
[ 0.32064009  0.69209957  0.7421422   0.86931682  0.95991254]
[ 0.70880806  0.3939954   0.67383504  0.34078181  0.98877013]
TensorFlow does not reset seed
[ 0.30350876  0.06209636  0.98059976  0.51447523  0.15706789]
[ 0.48785222  0.40416086  0.97456396  0.57969069  0.09107506]

コードをまるっと実行し直せばまた同じ擬似乱数列が生成されるので実験の再現性という意味では問題ないが, 例えば IPython 上で続け様に %run hoge.py とかやっているとシードがリセットされないので気を付けられたしというか, それで気付いた.

ちなみに R は Numpy と同じ宗派.

> set.seed(0)
> runif(5)
[1] 0.8966972 0.2655087 0.3721239 0.5728534 0.9082078
> set.seed(0)
> runif(5)
[1] 0.8966972 0.2655087 0.3721239 0.5728534 0.9082078

5
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
11