np.ramdomの【rand,random,ramdom_sample】の違い


結論

  • ほとんど同じ
    • 0~1の均一分布を返す
  • 使い方がちょっと違う
    • np.random.random(3,2) …… できない
    • np.random.rand(3,2) …… できる

はじめに

種類は3つではなくて2つ

  • 2つの種類
    • np.random.rand
    • np.random.random_sample
  • np.random.randomは?
    • random_sampleが長いので短縮形ramdom(エイリアス、別名)
    • 名前違うだけで機能は同じ
  • まとめると、
    • np.random.rand
    • np.random.random_sample(np.random.random)
      みたいな感じ
    • 使い方に違いがあるので、以降で説明する

使い方の違いを説明

ここからの説明はnp.random.randnp.random.random_sampleの2つ

引数が1つの場合は使い方同じ

np.random.rand

import numpy as np
np.random.seed(100)
a = np.random.rand(10)
print(a)
[0.54340494 0.27836939 0.42451759 0.84477613 0.00471886 0.12156912
 0.67074908 0.82585276 0.13670659 0.57509333]
  • 結果が同じになるようにseedを指定
  • 10個のランダム値を作成した

np.random.random_sample

import numpy as np
np.random.seed(100)
a = np.random.random_sample(10)
print(a)
[0.54340494 0.27836939 0.42451759 0.84477613 0.00471886 0.12156912
 0.67074908 0.82585276 0.13670659 0.57509333]
  • 10個のランダム値を作成した
  • np.random.randと同じ結果になった

引数が1つでない場合

正常パターン

import numpy as np
a = np.random.rand(2,3)
b = np.random.random_sample((2,3))
print(a)
print(a.shape)
print(b)
print(b.shape)
[[0.67074908 0.82585276 0.13670659]
 [0.57509333 0.89132195 0.20920212]]
(2, 3)
[[0.18532822 0.10837689 0.21969749]
 [0.97862378 0.81168315 0.17194101]]
(2, 3)
  • いずれも同じ形状(2,3)のランダム値ndarray(NumPy配列)を返す
    (seedを未指定なので数値は違う)
  • random_sampleの引数指定がタプルになっているところが違い
    • np.random.randの方が感覚的に使用できそう

エラーパターン

import numpy as np
a = np.random.random_sample(2,3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-94-37217c6143a1> in <module>
      1 import numpy as np
----> 2 a = np.random.random_sample(2,3)

mtrand.pyx in numpy.random.mtrand.RandomState.random_sample()

TypeError: random_sample() takes at most 1 positional argument (2 given)
  • np.random.randのように指定するとエラーになる
  • 正しくは、正解パターンのようにタプルを引数にする必要がある
    誤:np.random.random_sample( 2,3 )
    正:np.random.random_sample( (2,3) )


Posted by futa