In [3]:
import numpy as np
from sklearn import neighbors

In [55]:
# using classifier

r = 1 # Initial for model
x = 1 # increment for expanding radius
d = .01 # distance threshold for determing if two points near equidistant

# existing points and corresponding classes
existingPoints = np.array([[2,3,4,5,6,7,8],[1,3,4,5,6,7,8],[6,2,3,4,5,6,7]]) # existing points in model
existingClasses = np.array([1,2,3])

# initialize classifier
neigh = neighbors.NearestNeighbors(radius = r)

# read in new point
newPoints = np.array([2,3,4,5,6,7,8],ndmin=2)

# fit existing points to classifier
neigh.fit(existingPoints)

#distances,indices = neigh.radius_neighbors(newPoints)

newClass = classify(neigh,existingClasses,newPoints)

# Add the new point and new class to the model. Class = 0 if point is unclassified
existingPoints = np.append(existingPoints,newPoints)
existingClasses = np.append(existingClasses,newClass)

print(newClass)


2

In [54]:
def classify(neigh,existingClasses,newPoints):
    
    distances,indices = neigh.radius_neighbors(newPoints)

    # if there are no points in the radius, expand radius by x and check again before classifying point.
    if len(indices)==0 or len(indices)==1: 
        neigh.radius = r+x
        distances,indices = neigh.radius_neighbors(newPoints)         
        
    # else if there are two points from different classes that are close to the same distance
    # (within distance threshold), expand radius to see if there is another very close point
    elif len(indices) ==2 and existingClasses[indices[0]]!=existingClasses[indices[1]]:
        if abs(distances[0]-distances[1]) <= d:
            neigh.radius = r+x
    
    # predict class of new data 
    if len(indices)!=0:
        # calculate weights (arbitrary weights for now)
        weights = np.array([0,5,5])
        
        # sum weights for each class
        classes = existingClasses[indices[0]]
        classes = np.unique(classes[np.where(classes!=0)])  # ignore zero class (outliers)
                      
        classWeight = np.zeros(len(classes)) # initialize weight array
        
        for i,cl in enumerate(classes):
            classWeight[i] = sum(weights[np.where(classes==cl)])
            
        newClass = classes[np.argmax(classWeight)] 
                
    else: 
        newClass = 0
        
    return(newClass)

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: