LoginSignup
5
6

More than 3 years have passed since last update.

Rumaleで機械学習を試してみた

Last updated at Posted at 2019-01-17

SVMKitはRumaleに改称されました。
Rumale🦆チートシート をご覧ください

Rumaleとは

Rubyで書かれた機械学習用のライブラリ。
https://github.com/yoshoku/Rumale

インストール

gem install rumale

データの準備

ここではirisのデータセットで分類を試す。

  • label Numo::Int32#shape=[150]
  • samples Numo::DFloat#shape=[150,4]
require 'rumale'
require 'daru'
require 'rdatasets'

# データセットの読み込み
iris = RDatasets.load(:datasets, :iris)
# Daru::DataFrame

# ラベルの準備 # Numo::Int32#shape=[150]
iris_labels = iris['Species'].to_a
encoder = Rumale::Preprocessing::LabelEncoder.new
labels = encoder.fit_transform(iris_labels) 

# 特徴量の準備 Numo::DFloat#shape=[150,4]
# (Daru -> NArray の変換はやや煩雑)
samples = Numo::DFloat[*iris[0..3].to_matrix.to_a]

分類モデル

# 線形SVM
model = Rumale::LinearModel::SVC.new(
  reg_param: 0.0001,
  fit_bias: true,
  max_iter: 3000,
  random_seed: 1
)
  • いろいろ
# 決定木
model = Rumale::Tree::DecisionTreeClassifier.new(random_seed: 1)
# ランダムフォレスト
model = Rumale::Ensemble::RandomForestClassifier.new(random_seed: 1)
# K近傍法
model = Rumale::NearestNeighbors::KNeighborsClassifier.new(n_neighbors: 5)
# ナイーブベイズ
model = Rumale::NaiveBayes::GaussianNB.new

検証する

# KFold データセットの分割
kf = Rumale::ModelSelection::StratifiedKFold.new(
  n_splits: 5,
  random_seed: 1
)

# 交差検証
cv = Rumale::ModelSelection::CrossValidation.new(
  estimator: model,
  splitter: kf
)
report = cv.perform(samples, labels)

# 結果
scores = report[:test_score]
puts scores.sum / scores.size
# 0.9466666666666667

学習と予想

# 学習させる
model.fit(samples, labels)

# 予想
# 引数は 2D NArray。ここでは Numo::DFloat#shape=[150,4]
p model.predict(samples).to_a

モデルの保存、読み込み

# モデルの保存
File.binwrite("model.dat", Marshal.dump(model))

# モデルの読み込み
model = Marshal.load(File.binread("model.dat"))

参考資料

5
6
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
5
6