[RUBY] Learning from the basics Artificial intelligence textbook Chapter 3 End-of-chapter problems

Introduction

As a study of machine learning, I am reading "* Learning from the basics: Artificial intelligence textbook *".

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

Here, it is copied with Ruby.

Chapter 3 End of Chapter Problem

kneighbor.rb


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 'Enter the top 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 that solves the classification problem by the k-nearest neighbor method.

Please enter the height to be classified: 50
Enter the top 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 50 top surface area 50 is classified as ʻA`.

Summary

Recommended Posts

Learning from the basics Artificial intelligence textbook Chapter 3 End-of-chapter problems
Learning from the basics Artificial intelligence textbook Chapter 4 Chapter end problems
Learning from the basics Artificial intelligence textbook Chapter 2 Chapter end problems
[Ruby] From the basics to the inject method
Deep Learning Java from scratch Chapter 1 Introduction
Deep Learning Java from scratch Chapter 2 Perceptron