作成
Numpyによる乱数生成
###title 実数の乱数 ###source x = rand() # 0〜1の実数 1個 x2 = rand(10) # 0〜1の実数 10個 x2 = rand(3,5) # 0〜1の実数 3x5の行列 ###title 整数の乱数 ###source x = randint(10) # 0~10 の整数を1個 x = randint(0,10) # 0~10 の整数を1個 x2 = randint(0,10,20) # 0~10 の整数で1x20の配列 x2 = randint(0,10,(3,5)) # 0~10 の整数で3x5の行列 ###title 指定値のみから乱数を生成 ###source from numpy import * x2 = random.choice( [-1,0,1], 100) # -1,0,1 のいずれかの値を100コ ###title3 ランダムウォーク ###source from numpy import * x2 = random.choice( [-1,0,1], 10) y2 = cumsum(x2) ## x2 が以下の場合 # x2 = [ 1 1 1 -1 1 0 0 1 1 1 ] ## cumsum(x2) は以下のようになります。 # y2 = [ 1 2 3 2 3 3 3 4 5 6 ] ###title 正規分布の乱数 ###source # 平均60、標準偏差20 の 正規分布 x = normal(60,20) # 100コ x2 = normal(60,20, 100) # 10x10コ x2 = normal(60,20, (10,10)) ###title 標準正規分布の乱数 ###memo 正規分布を平均0, 標準偏差1に正規化したものを#*#標準正規分布 と言います。 ###source # 標準正規分布に従う乱数。 x = randn() # 10コ x2 = randn(10) # 10x10コ x2 = randn(10,10) ###title3 確認 ###source from numpy.random import * import matplotlib.pyplot as plt x2 = randn(10000) # 標準正規分布に従う10000個の乱数 plt.hist(x2, bins=50) # 50本の縦棒で表示 plt.show() ###center 正規分布の形になってます(^^) ###center 縦軸が個数。横軸が値。(img://7/215m) ###title disable その他の分布の乱数 ###source disable #二項分布。確率pでオモテが出るコインをn回投げて、オモテが出る個数。 x = binomial(n=100, p=0.5) #ポアソン分布。稀にしか起きない現象を長時間観測したときに起きる回数の分布。λはその平均。 x = poisson(lam=10) # λ=10 のポアソン分布 #ベータ分布。二項分布の共役事前分布などに用いる x = beta(a=3, b=5) ###source disable from numpy.random import * import matplotlib.pyplot as plt ## 二項分布の計算(試行回数:100, 確率:0.5, サンプル数:1000) x2 = binomial(100, 0.5, 1000) print(x2) plt.hist(x2, bins=100) # 100本のヒストグラムを作成 plt.show() # グラフを表示 ###title 同じ乱数を生成 ### テストしたいときにでも。 #*#seed(1000) のように一文加えます。 ###source from numpy.random import * seed(1000) # 毎回同じ値に設定。数値は適当。 x = rand() # 毎回同じ値 0.6535895854646095 x = randn() # 毎回同じ値 -0.8044583035248052 x2 = randn(10) # 毎回同じ値を(10コ) # [ 0.32093155 -0.02548288 0.64432383 -0.30079667 0.38947455 -0.1074373 # -0.47998308 0.5950355 -0.46466753 0.66728131 ] seed() # 毎回ランダムな乱数に x = randn() # 毎回異なる値
wakatta 記法
投稿の仕方
基本的な記法
エンジニア向け記法
記法のサンプル
このコンテンツを見る