AIG Interview Question: Describe KNN algorithm... | Glassdoor

Interview Question

Data Analyst Interview

Describe KNN algorithm

Answer

Interview Answer

1 Answer

0

class ScrappyKNN():
    def __init__(self,k=5):
        self.k=k
    def fit(self,X_train,Y_train):
        self.X_train=X_train
        self.Y_train=Y_train

    def euc(x,y):
        return distance.euclidean(x,y)

    def closest_one(self,i):
        distances=map(lambda x:distance.euclidean(x,i),X_train)
        distiance_index=zip(range(len(X_train)),distances)
        closest_rank=sorted(distiance_index,key=lambda x:x[1])
        knn=Y_train[[i[0] for i in closest_rank[:5]]].tolist()
        return max(set(knn), key=knn.count)

    def predict(self,X_test):
        predictions=[]
        for i in X_test:
            label=self.closest_one(i)
            predictions.append(label)
        return predictions

Jiamin Xuan on Jun 19, 2016

Add Answers or Comments

To comment on this, Sign In or Sign Up.