python自己实现K近邻算法

自作多情 提交于 2019-11-26 10:00:51
# -*- coding:utf-8 -*-
# /usr/bin/python
import numpy as np

class kNeighberHood():
    # weight1: object
    #
    def __init__(self,n=1,weight='uniform'):
        self.n1 = n
        self.weight1 = weight

    def fit(self,listS,y):
        self.X = np.array(listS)
        self.y = y

    def predict(self,x):
        x_test = np.array(x)
        y_test = np.zeros(len(x))
        for x_texts_index,i in enumerate(x_test):
            distanceList = np.zeros(len(self.X))
            for index , j in enumerate(self.X):
                a = np.sqrt(j.dot(j.T)+i.dot(i.T)-2*i.dot(j.T))
                distanceList[index] = a

            d = list(zip(distanceList,self.y))
            print(d)
            d =sorted(d,key=lambda x: x[0])
            print(d)
            resultSum = {}
            for i in set(self.y):
                resultSum[str(i)] = 0
            if self.weight1 == 'uniform':
                for i in d[0:self.n1]:
                    resultSum[str(i[1])]+=1
            elif self.weight1 == 'distance':
                for i in d[0:self.n1]:
                    resultSum[str(i[1])]+=1.0/i[0]
            else:
                for i in d[0:self.n1]:
                    resultSum[str(i[1])]+=self.weight1[str(i[1])]
            print(resultSum)

            result_max = max(resultSum, key=lambda x: resultSum[x])
            #y_test[x_texts_index] = self.y[distanceList.argmin(axis=0)]
            y_test[x_texts_index] =result_max
        return y_test

if __name__ == '__main__':
    a = kNeighberHood(3,{'0':2,'1':1})
    x = [[1,2],[1,3],[4,2],[5,2],[2,5],[3,3]]
    y = [0,0,1,1,0,1]
    x_test = [[6,6],[0,1]]
    a.fit(x,y)
    y_test = a.predict(x_test)
    print(y_test)


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!