"""
	Classification - KNN
	by Vincent Jeanselme
	vincent.jeanselme@gmail.com
"""

import numpy as np
from model.classifier import Classifier

class ClassifierKNN(Classifier):
	"""
	Structure for a knn classifier
	"""

	def __init__(self, distance, nearestNeighbor):
		"""
		Saves the distance to use and the number of nearest neighbors
		"""
		self.distance = distance
		self.nearestNeighbor = nearestNeighbor

	def predict(self, data, **kwargs):
		"""
		Forecasts the output given the data
		"""
		# Computes the ditance to each data point
		distances = [self.distance(data, trainD) for trainD in self.trainData]
		labelDistance = list(zip(self.trainLabels, distances))

		# Sorts it by distance
		labelDistance.sort(key=lambda x: x[1])
		neightbor = [0] * (max(self.trainLabels) - min(self.trainLabels) + 1)

		for j in labelDistance:
			if max(neightbor) < self.nearestNeighbor :
				neightbor[j[0]] += 1
			else :
				break

		return np.argmax(neightbor) + min(self.trainLabels)

	def train(self,trainData, trainLabels, testData = None, testLabels=None):
		"""
		Trains the model and measure on the test data
		"""
		self.trainData = trainData
		self.trainLabels = trainLabels

		self.test(testData, testLabels)

@@ -490,16 +490,87 @@
 a%0A%09%09%22%22%22%0A
+%09%09if self.trainData is None:%0A%09%09%09print(%22Train before predict%22)%0A%09%09else:%0A%09
 %09%09# Comp
@@ -605,16 +605,17 @@
 a point%0A
+%09
 %09%09distan
@@ -681,16 +681,17 @@
 Data%5D%0A%09%09
+%09
 labelDis
@@ -740,16 +740,17 @@
 es))%0A%0A%09%09
+%09
 # Sorts 
@@ -764,16 +764,17 @@
 istance%0A
+%09
 %09%09labelD
@@ -808,16 +808,17 @@
 x%5B1%5D)%0A%09%09
+%09
 neightbo
@@ -880,16 +880,17 @@
 ) + 1)%0A%0A
+%09
 %09%09for j 
@@ -910,16 +910,17 @@
 nce:%0A%09%09%09
+%09
 if max(n
@@ -958,16 +958,17 @@
 r :%0A%09%09%09%09
+%09
 neightbo
@@ -987,15 +987,17 @@
 %0A%09%09%09
+%09
 else :%0A
+%09
 %09%09%09%09
@@ -1003,16 +1003,17 @@
 %09break%0A%0A
+%09
 %09%09return

Update knn in order to refuse if not train