LoginSignup
3
2

More than 3 years have passed since last update.

敢えてRubyで学ぶ「ゼロから作るDeep Learning」閑話 Numo::GSLの導入と正規乱数

Last updated at Posted at 2020-02-13

第4章に正規(ガウス)分布の乱数を生成するコードが有る。

擬似的に正規分布の乱数を最も簡単に作る方法

-0.5~0.5の乱数の12回の平均。

def norm_rand
  random = Random.new()
  result = 0
  12.times do
    result += random.rand(-0.5..0.5)
  end
  result / 12
end

とはいえ、色々面倒だし、これを使って行列を作るのもなんとも不便。
そこで、乱数を生成してくれるライブラリ、Numo::GSLを導入する。

Numo::GSLの導入

基本的にはDockerのRuby上で行っています。
環境構築に関しては、敢えてRubyで学ぶ「ゼロから作るDeep Learning」Docker環境構築編をご確認ください。

# まずは元となるGSLを導入
$ apt install -y gsl-bin
# 次にNumo::GSLのgemを導入
$ gem install numo-gsl

Numo::GSLでの正規乱数の生成

require 'numo/gsl'
require 'numo/narray'

## 標準正規分布のrow * colの行列を作る
def randn(row, col)
  r = Numo::GSL::Rng::Rand.new
  r.gaussian(1, row * col).reshape(row, col)
end

追記 Numo::Narrayから正規乱数の生成

@kojix2 さんよりコメント頂きました、Numo::NArrayで正規乱数を作る方法も記載しておきます。

require 'numo/narray'

# 標準正規分布のrow * colの行列を作る
# rand_norm = rand_norm(0,1) 平均0、標準偏差1の標準正規分布
Numo::DFloat.new(row,col).rand_norm
3
2
2

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
3
2