DEV Community


Easy machine learning with Ruby using Rumale

kojix2 profile image kojix2 Updated on ・2 min read

What is Rumale

A powerful library for machine learning written in pure Ruby!
Rumale is created by @yoshoku .

Rumale (Ruby machine learning) is a machine learning library in Ruby. Rumale provides machine learning algorithms with interfaces similar to Scikit-Learn in Python. Rumale supports Linear / Kernel Support Vector Machine, Logistic Regression, Linear Regression, Ridge, Lasso, Factorization Machine, Naive Bayes, Decision Tree, AdaBoost, Gradient Tree Boosting, Random Forest, Extra-Trees, K-nearest neighbor classifier, K-Means, Gaussian Mixture Model, DBSCAN, Power Iteration Clustering, Mutidimensional Scaling, t-SNE, Principal Component Analysis, and Non-negative Matrix Factorization.


gem install rumale

Prepare a dataset

require 'rumale'
require 'daru'
require 'rdatasets'

# load datasets
iris = RDatasets.load(:datasets, :iris)
# Daru::DataFrame

# labels # Numo::Int32#shape=[150]
iris_labels = iris['Species'].to_a
encoder =
labels = encoder.fit_transform(iris_labels) 

# samples Numo::DFloat#shape=[150,4]
# (Daru -> NArray )
samples = Numo::DFloat[*iris[0..3].to_matrix.to_a]

Classification models

# Support vector machine
model =
  reg_param: 0.0001,
  fit_bias: true,
  max_iter: 3000,
  random_seed: 1

Various classifiers

model = 1)
model = 1)
model = 5)
model =
# etc...

Cross validation

# KFold
kf =
  n_splits: 5,
  random_seed: 1

cv =
  estimator: model,
  splitter: kf
report = cv.perform(samples, labels)


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

Learning and Predicting

# Learning, labels)

# Predicting
# accept 2D NArray  (Numo::DFloat#shape=[150,4])
p model.predict(samples).to_a

Save and load models

# Save a model
File.binwrite("model.dat", Marshal.dump(model))

# Load a model
model = Marshal.load(File.binread("model.dat"))


Discussion (0)

Editor guide