parent
4a24a35c77
commit
2ca5f202bc
@ -0,0 +1,54 @@
|
|||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from point import *
|
||||||
|
|
||||||
|
|
||||||
|
class Knn:
|
||||||
|
def __init__(self):
|
||||||
|
self.space = np.array([])
|
||||||
|
|
||||||
|
def addPoint(self, coord, value):
|
||||||
|
self.space = np.append(self.space, Point(coord, value))
|
||||||
|
|
||||||
|
def getValueOfPoint(self, coord,nbNearest):
|
||||||
|
points, dists = self.getNNearest(coord, nbNearest)
|
||||||
|
ttPart = 1/(dists[0]+1)
|
||||||
|
value = []
|
||||||
|
for i in points[0].value:
|
||||||
|
value.append(i * ttPart)
|
||||||
|
for idx in range(1,len(points)):
|
||||||
|
ttPart += 1/(dists[idx]+1)
|
||||||
|
tvalue = points[idx].value
|
||||||
|
for i in range(len(tvalue)):
|
||||||
|
value[i] += tvalue[i] * (1/(dists[idx]+1))
|
||||||
|
for i in range(len(value)):
|
||||||
|
value[i] = value[i] / ttPart
|
||||||
|
return value
|
||||||
|
|
||||||
|
def getNNearest(self, coord, nbNearest):
|
||||||
|
dist = np.copy(self.space)
|
||||||
|
dist = np.frompyfunc(lambda x: x.getDistFromCoord(coord), 1, 1)(dist)
|
||||||
|
if (nbNearest > len(dist)):
|
||||||
|
print("Error: not enough points")
|
||||||
|
return None, None
|
||||||
|
found = []
|
||||||
|
distance = []
|
||||||
|
for i in range(nbNearest):
|
||||||
|
found.append(self.space[i])
|
||||||
|
distance.append(dist[i])
|
||||||
|
maxDistIdx = np.argmax(distance)
|
||||||
|
for i in range(nbNearest, len(dist)):
|
||||||
|
if (dist[i] < distance[maxDistIdx]):
|
||||||
|
found[maxDistIdx] = self.space[i]
|
||||||
|
distance[maxDistIdx] = dist[i]
|
||||||
|
maxDistIdx = np.argmax(distance)
|
||||||
|
return found, distance
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
k = Knn()
|
||||||
|
|
||||||
|
k.addPoint(np.array([1, 0.8,1.5]), [0.2,0.5])
|
||||||
|
k.addPoint(np.array([0.2, 1.8,1.2]), [0.4,0.7])
|
||||||
|
|
||||||
|
print(k.getValueOfPoint(np.array([1, 0.8, 1.5]), 2))
|
@ -0,0 +1,15 @@
|
|||||||
|
import numpy as np
|
||||||
|
|
||||||
|
class Point:
|
||||||
|
def __init__(self, coord, value):
|
||||||
|
self.coord = coord
|
||||||
|
self.value = value
|
||||||
|
|
||||||
|
def setvalue(self, value):
|
||||||
|
self.value = value
|
||||||
|
|
||||||
|
def getDist(self, point):
|
||||||
|
return np.linalg.norm(self.coord - point.coord)
|
||||||
|
|
||||||
|
def getDistFromCoord(self, coord):
|
||||||
|
return np.linalg.norm(self.coord - coord)
|
Loading…
Reference in new issue