Skip to content

add Nearest Neighbor #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"python.pythonPath": "/usr/bin/python3"
}
Empty file.
43 changes: 43 additions & 0 deletions allalgorithms/classification/nearest_neighbor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# -*- coding: UTF-8 -*-
#
# Nearest neighbour classifier one entry
# The All ▲lgorithms library for python
#
# Contributed by: Carlos Abraham Hernandez
# Github: @abranhe
#

from math import sqrt

class NN():
"""
Nearest neighbour classifier for two-dimensional dataset
"""
def fit(self,data,labels):
self.data = data
self.labels = labels

return self

def predict(self,x_test):
predicts = []
for row in x_test:
label = self.closest(row)
predicts.append(label)
return predicts

def euc(self,a,b):
return sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)


def closest(self,row):
#initial best distance is alwas first
best_distance = self.euc(row,self.data[0])
best_index = 0
#intering in data
for i in range(1,len(self.data)):
dist = self.euc(row,self.data[i])
if dist < best_distance:
best_distance = dist
best_index = i
return self.labels[best_index]
40 changes: 40 additions & 0 deletions tests/test_classification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import unittest
from allalgorithms.classification import nearest_neighbor

class TesteClassifications(unittest.TestCase):

def test_nn(self):
#datas
#the first data is Weight and second is number of wheels
features = [
[110,2],
[125,2],
[100,2],
[110,2],
[300,4],
[278,4],
[290,4],
[260,4],
]
#labels, the labels is classification of features line
#in this exemple 0 = Motorcicler, 1 = car
label = [
0,
0,
0,
0,
1,
1,
1,
1,
]
#instance classifier
clf = nearest_neighbor.NN()
#treaning
clf = clf.fit(features,label)
#predict
rs = clf.predict([[2,115]])
self.assertEqual(rs,0)

if __name__ == "__main__":
unittest.main()