8
7

More than 5 years have passed since last update.

[Ruby] 機械学習①:Ruby入門

Last updated at Posted at 2017-11-07

前提

・Python が入っていること。
・Rubyがはいっていること : [Rails]Debian8に Ruby + Rails を導入する。

※Pyenvでの導入が簡単でいいように思います。また、Numpy、Matplotlibなど個別にインスト−する必要がある(Python側)ので、anacondaが便利かもしれません。

データサイエンティストを目指す人のpython環境構築 2016より抜粋
自分のの環境はvagrant上のDebian8です。

$ git clone https://github.com/yyuu/pyenv.git ~/.pyenv
$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc 
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
$ echo 'eval "$(pyenv init -)"' >> ~/.bashrc
$ pyenv install -l | grep ana
$ pyenv install anaconda3-2.5.0
$ pyenv rehash
$ pyenv global anaconda3-2.5.0
$ echo 'export PATH="$PYENV_ROOT/versions/anaconda3-2.5.0/bin/:$PATH"' >> ~/.bashrc
$ source ~/.bashrc
$ conda update conda

NumPy

GitHib mrkn/numpy

$ gem install numpy
test_numpy.rb
require "numpy"

np = Numpy
x = np.array([1,2,3,4,5])
y = np.array([2,4,3,5,6])
puts x + y

z= np.array([[1,2],[3,4]])
puts z.shape

a = np.array([[1,2],[3,4]])
b = np.array([10,20])
puts a * b

n_arr = np.array([[12,43],[14,40],[90,209]])
for i in 0..n_arr.shape[0] - 1
  puts n_arr[i][1]
end

c = n_arr.flatten()
puts c
puts c[np.array([0,2,4])]
puts c[c>100]

・numpyの配列に対して、eachは使えない。
・代わりに上記のようにループを適応することはできる。

Matplotlib

GitHib mrkn/matplotlib

gem install matplotlib 
test_matplotlib.rb
require 'numpy'
require 'matplotlib/pyplot'

plt = Matplotlib::Pyplot
np = Numpy

# cos and sin
x = np.arange(0,6,0.1)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x,y1)
plt.plot(x,y2, line_style="--")
plt.xlabel("x")
plt.xlabel("y")
plt.title('sin & cos')
plt.legend()
plt.show()

# 散布図
x = np.random.randn(30)
y = np.sin(x) + np.random.randn(30)
plt.plot(x, y, "ro")     # "o"は小さい円(circle marker)
plt.show()

# 棒グラフ
plt.hist(np.random.randn(1000))
plt.show()

・plt.plot(x,y1,label="cos")として、ラベルをつけようとしてもうまくいかない。

Pycallの位置づけ

Data Analysis with Ruby using PyCall by Kenta Murata

Rubyスクリプトで生成したデータをpandasで加工してmatplotlibやseabornで加工する。

Railsだったら以下のような流れだと思う。
①Rails(Ruby)でデータの整形
②PycallからPython側でデータの処理
③Rails側で表示

ハマりどころ

Linux(Ubuntu系)を使っているのですが、find_libpython': PyCall::PythonNotFound (PyCall::PythonNotFound)がで出て実行できませんでした。

自分の環境のpyenvなpythonであったので下記を参照にして解決した。
Ruby の PyCall を使って pyenv な Python を使えるようにする方法

$  which python
$  ls /opt/pyenv/versions/
# => 2.7.6  3.4.2

以下の例では、3.4.2下に、共有ライブラリを作るようにオプションを指定します。

$ CONFIGURE_OPTS="--enable-shared" pyenv install 3.4.2 

いつもいつも忘れてしまうのでruby-buildのconfigureオプションの設定についてメモっておく

CONFIGURE_OPTSは文字通り./configureにoptionを渡すことになる。

これで解決!

参照

PyCallを使ってRubyからPythonのライブラリを使い倒す

8
7
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
8
7