Machine learning in plain Ruby
In the last lesson Python did the learning. Rumale brings the same ideas to Ruby – with the same names: make a model, fit it to examples, let it predict, check it with score. Atsushi Tatsuma (yoshoku) wrote it, all in Ruby.
Rumale keeps its numbers in Numo arrays, Ruby's counterpart to NumPy: Numo::DFloat for decimals, Numo::Int32 for whole numbers. Their gem, numo-narray-alt, is written in C, so it does not run in a browser; here a stand-in in plain Ruby with the same methods does its job – just slower.
Rumale comes in small gems. We need the nearest neighbours, and to start, some vegetables: length and thickness in centimetres.
install_gem "rumale-nearest_neighbors"
require "rumale/nearest_neighbors"
# [length, thickness] in cm
veggies = Numo::DFloat[[18, 3], [20, 3.5], [16, 2.5], # carrots
[30, 4.5], [28, 5], [33, 5], # cucumbers
[6, 6], [5, 5.5], [7, 7]] # tomatoes
kind = Numo::Int32[0, 0, 0, 1, 1, 1, 2, 2, 2]
names = ["carrot", "cucumber", "tomato"]
veggies.shapeshape says [9, 2]: 9 rows of 2 numbers. Rumale wants the answers as numbers – 0 for carrot, 1 for cucumber, 2 for tomato – and the names go in an ordinary list.
The k-nearest-neighbours classifier is the simplest learning method there is: to judge a new vegetable, it looks for the k most similar ones it knows and lets them vote. "Similar" means close together, if you plot length and thickness as points.
neighbours = Rumale::NearestNeighbors::KNeighborsClassifier.new(n_neighbors: 3)
neighbours.fit(veggies, kind)
guesses = neighbours.predict(Numo::DFloat[[25, 4], [6, 6.5], [15, 3]])
guesses.to_a.map { |k| names[k] }25 cm long and 4 cm thick is closest to the cucumbers, the round one to the tomatoes, the thin one to the carrots. fit did not learn anything here – it only remembers the examples. The work comes in predict: measuring every distance.
Now something harder: handwriting. digits.csv holds 1797 handwritten digits, collected by UCI. Each is a picture of 8×8 squares, and each square a number from 0 to 16 – how much ink is in it. The number at the end of the line says which digit it is. The file is next to your code (in the browser, the course puts it there):
rows = File.read("digits.csv").lines.map { |line| line.split(",").map(&:to_i) }
pictures = Numo::DFloat[*rows.map { |r| r[0, 64] }]
labels = Numo::Int32[*rows.map(&:last)]
pictures.shape1797 pictures of 64 numbers each. reshape(8, 8) turns a row back into a picture – let's draw the first one with characters that get darker the more ink a square has:
picture = pictures[0, true].reshape(8, 8)
picture.to_a.each do |row|
puts row.map { |value| " .:-=+*#%@"[(value * 9 / 16).round] }.join(" ")
end
labels[0]A zero, no doubt. Now learn and test honestly: the classifier gets the first 1000 pictures to learn from and is tested on 50 more it has never seen. (In the browser Numo is plain Ruby – the test takes a few seconds.)
learner = Rumale::NearestNeighbors::KNeighborsClassifier.new(n_neighbors: 3)
learner.fit(pictures[0...1000, true], labels[0...1000]) # learn from these
learner.score(pictures[1000...1050, true], labels[1000...1050]) # test on these48 out of 50 right – with nothing but distances between 64 numbers. [0...1000, true] means rows 0 to 999, all columns.
Now it's your turn. For the letter, the classifier may learn from all 1797 pictures – the more examples, the better. Below, a letter to Chunky appears; with the mouse or a finger, write the postcode into the red boxes, one digit per box. Every time you lift the pen, the block gets all the digits written so far – 64 numbers each, just like a row of digits.csv – and its answer is stamped on the letter. Four-digit postcodes, as in Australia: try 2000, 3000 or 6000:
learner.fit(pictures, labels) # now from all 1797
places = { "2000" => "Sydney", "3000" => "Melbourne", "4000" => "Brisbane", "5000" => "Adelaide",
"6000" => "Perth", "7000" => "Hobart", "0800" => "Darwin", "2600" => "Canberra" }
show_letter(boxes: 4) do |written| # one Array of 64 numbers per box
postcode = learner.predict(Numo::DFloat[*written]).to_a.join
"#{postcode} #{places.fetch(postcode, "?")}"
endUnder the letter you see what Ruby gets: your digits as 8×8 pictures. If the classifier misreads one, look there. The digits in digits.csv were written with pens on forms in the 1990s; a mouse writes differently. Write big, fill the box from top to bottom – or change the code: n_neighbors: 1 or 5, and the letter reads your digits again straight away.
gem install rumale installs everything, the real numo-narray-alt too (it gets compiled); then require "rumale" is all you need. The code of this lesson runs unchanged – only the letter needs this page. digits.csv comes from the dataset Optical Recognition of Handwritten Digits by E. Alpaydin and C. Kaynak (UCI, CC BY 4.0); download it here. Rumale comes under the BSD licence.
# is 16, . is 0, row by row – and let learner say what it sees. Store its answer in digit, as a Ruby number.seven = <<~PICTURE
.######.
......#.
.....#..
....#...
...#....
...#....
..#.....
..#.....
PICTURE
# pixels = ... (64 numbers: # is 16, . is 0)
# digit = ... (what learner sees in it, as a Ruby number)