[Ruby] Learning from the basics Artificial intelligence textbook Chapter 3 End of chapter problem

less than 1 minute read


As a study of machine learning, I read “Learn from basics textbook of artificial intelligence””.

The feature of this book is that a simple program of Python is included in the chapter end problem.

Here, it is transcribed in Ruby.

Chapter 3 End of Chapter Problem


itemdata = [[30, 50,'A'], [65, 40,'B'],
            [90, 100,'A'], [90, 60,'B'],
            [70, 60,'B'], [40, 50,'A'],
            [80, 50,'B']]

print'Please enter the height to be classified:'
h = gets.to_i
print'Please enter the upper surface area to be classified:'
a = gets.to_i

print itemdata.sort_by{|x, y, _| (x-h) ** 2 + (y-a) ** 2}

This is a problem to create a program to solve the classification problem by the k-nearest neighbor method.

k neighborhood method-wikipedia

Please enter the height to be classified: 50
Please enter the upper surface area to be classified: 50
[[40, 50, "A"], [65, 40, "B"], [30, 50, "A"], [70, 60, "B"], [80, 50, "B"] , [90, 60, "B"], [90, 100, "A"]]

For example, data with a height of 50 and an upper surface area of 50 is classified as A.


  • I read up to Chapter 3