静かなる名辞

pythonとプログラミングのこと


【python】numpyで乱数のseedを設定する方法

 「seed(種)」とか「random state」とか呼ばれる奴の設定方法。これを設定することで、乱数の処理に再現性を与えることができる。

方法

 np.random.seed()を呼ぶと、とりあえずseedが引数でリセットされる。

https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html

 やってみる。

>>> import numpy as np
>>> np.random.seed(0)  # seedを設定
>>> np.random.random((2,3))  # 一様乱数の配列を作ってみる
array([[0.5488135 , 0.71518937, 0.60276338],
       [0.54488318, 0.4236548 , 0.64589411]])
>>> np.random.random((2,3))  # 同じにはならない
array([[0.43758721, 0.891773  , 0.96366276],
       [0.38344152, 0.79172504, 0.52889492]])
>>> np.random.seed(0)  # もう一度設定する
>>> np.random.random((2,3))  # 最初と同じになる
array([[0.5488135 , 0.71518937, 0.60276338],
       [0.54488318, 0.4236548 , 0.64589411]])

 まあ、理解はできる。

スポンサーリンク


 ところで、np.random.seed()のドキュメントにはこう書いてあった。

This method is called when RandomState is initialized. It can be called again to re-seed the generator. For details, see RandomState.

 RandomStateというクラスが内部では動いているということなのだろうか。

https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.RandomState.html

Parameters:
seed : {None, int, array_like}, optional

Random seed used to initialize the pseudo-random number generator. Can be any integer between 0 and 2**32 - 1 inclusive, an array (or other sequence) of such integers, or None (the default). If seed is None, then RandomState will try to read data from /dev/urandom (or the Windows analogue) if available or seed from the clock otherwise.

 よくわからないが、乱数の状態のクラスなので(直訳)、たぶんインスタンス化してよろしく使えるのだと思う。

>>> rand_state = np.random.RandomState(0)
>>> rand_state.random_sample((2,3))  # なぜかrandomメソッドがなくてrandom_sampleメソッドが同じ機能を持っている・・・
array([[0.5488135 , 0.71518937, 0.60276338],
       [0.54488318, 0.4236548 , 0.64589411]])
>>> rand_state.random_sample((2,3))
array([[0.43758721, 0.891773  , 0.96366276],
       [0.38344152, 0.79172504, 0.52889492]])

 できた。それでえっと、何に便利かなこれは・・・。

 まあ、常識的な用途ではnp.random.seed()があれば困らないと思う。わざわざオブジェクト化して取り扱いたいような状況は、たぶんあるにはあるだろうけど、ライブラリとかアルゴリズムのコアなコード書いてるとき以外はほぼないだろう。

まとめ

 簡単にできる。