Letting the machine learn
Usually you write the rule and the computer follows it. In machine learning it is the other way round: you show the computer examples, and it finds the rule itself. scikit-learn is Python's library for that – a few dozen learning methods, all used the same way: make a model, fit it to examples, let it predict.
It stands on NumPy and SciPy, so the first time this lesson loads about 19 MB. First example: an ice cream stand that wrote down, for five days, the temperature and how many ice creams it sold. How many will it sell at 25 degrees?
require "pycall"
lm = PyCall.import_module("sklearn.linear_model")
temperature = [[14], [18], [22], [26], [30]] # °C, one row per day
sales = [21, 33, 46, 60, 71] # ice creams sold
model = lm.LinearRegression.new
model.fit(temperature, sales)
model.predict([[25]])The examples come in two parts. The inputs are a list of rows, one per example – here each row has only one value, the temperature, so it is [14] and not just 14. The answers are a plain list, one per row. LinearRegression looks for the straight line that fits the points best; fit learns it, predict uses it – for 25 degrees, about 56 ice creams.
The line the model learned is just two numbers, and you can ask for them:
puts "Ice creams per degree: #{model.coef_[0].round(2)}"
puts "Starting point: #{model.intercept_.round(2)}"coef_ is how steep the line is: about 3.2 more ice creams for every degree. intercept_ is where the line would be at 0 degrees: below zero. A line doesn't know that nobody sells minus 24 ice creams – a model only knows its examples, and none were that cold. The trailing _ is scikit-learn's mark for "learned from the data".
Now something that is not a number: is an animal a cat or a fox? We measured a few – weight in kg and ear length in cm – and let a decision tree learn from them. The nice thing about a tree: you can read what it learned.
tree = PyCall.import_module("sklearn.tree")
animals = [[4.0, 6], [3.5, 5], [5.0, 7], [4.5, 6], # [weight in kg, ears in cm]
[7.0, 9], [6.5, 10], [8.0, 9], [7.5, 11]]
kinds = ["cat"] * 4 + ["fox"] * 4
judge = tree.DecisionTreeClassifier.new(random_state: 0)
judge.fit(animals, kinds)
puts tree.export_text(judge, feature_names: ["weight", "ears"])The tree asks one single question: are the ears at most 8 cm long? Then it's a cat, otherwise a fox. It found the boundary itself, halfway between the longest cat ears (7 cm) and the shortest fox ears (9 cm). Let it judge animals it has never seen:
judge.predict([[4.2, 6], [7.2, 10], [5.8, 8]]).tolist.to_aThe third one is a surprise: 5.8 kg, heavier than every cat we measured, and still the tree says cat – its ears are 8 cm. The tree never looked at the weight, because the ears alone told all its examples apart. A model is only as good as its examples: with a few heavy cats and light foxes among them, it would have had to learn more.
Real data has more than two measurements. scikit-learn comes with a few classic datasets; the best known is iris: 150 flowers of three kinds, each measured four times.
datasets = PyCall.import_module("sklearn.datasets")
selection = PyCall.import_module("sklearn.model_selection")
iris = datasets.load_iris
puts iris.feature_names
puts iris.target_names
iris.data.shapeshape says [150, 4]: 150 rows, 4 measurements each. How well can a tree tell the kinds apart? To find out honestly, we hide part of the data while it learns: train_test_split keeps 30% back. The tree learns from the rest and is then tested on flowers it has never seen:
parts = selection.train_test_split(iris.data, iris.target, test_size: 0.3, random_state: 1)
train_x, test_x, train_y, test_y = parts[0], parts[1], parts[2], parts[3]
flowers = tree.DecisionTreeClassifier.new(max_depth: 3, random_state: 0)
flowers.fit(train_x, train_y)
flowers.score(test_x, test_y)score is the share of test flowers it got right – here about 96%. max_depth: 3 allows at most three questions in a row, so the tree learns the general pattern rather than memorising each flower. Testing on hidden data is the most important habit in machine learning: a model that only knows its own examples is not much use.
pip install scikit-learn and gem install pycall, and the code of this lesson runs unchanged. For machine learning in Ruby itself, look at Rumale, which works much like scikit-learn – it is the next lesson. scikit-learn, SciPy and NumPy come under the BSD licence.
LinearRegression with them and predict the points for 6 hours. Store the prediction in forecast, as a Ruby number.require "pycall"
lm = PyCall.import_module("sklearn.linear_model")
hours = [[1], [2], [3], [4], [5]]
points = [52, 59, 66, 73, 80]
# forecast = ... (the predicted points for 6 hours)