import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import matplotlib.cbook as cbook

def CreateData():

    ret_data = np.array(
        [[1.0,1.1],
        [1.0,1.0],
        [0.0,0.0],
        [0.1,0.0],
        [0.0,0.1],
        [0.4, 0.5],
        [0.5,0.4]]
    )

    ret_label = np.array(["A","A","B","B","B","C","C"])
    return ret_data, ret_label

def ClassifierForKNN(pX,pRealY,pDataSet,pLabel,pK,pRetType="Class"):

    pX = np.array(pX)

    x, y = pDataSet, pLabel

    if (x.shape[1] != len(pX) or x.shape[0] != len(y) or len(y) < pK):
        return

    pX = np.tile(pX,(x.shape[0],1))

    x_ = (x - pX)**2
    x_distance = x_.sum(axis=1)
    x_sorted = np.argsort(x_distance,axis=0)

    x_label = []
    for k in np.arange(pK):
        x_label.append(y[x_sorted[k]])
    x_classes = pd.value_counts(x_label)
    x_classes.sort_values(inplace=True, ascending=False)

    if(pRetType == "Class"):
        return x_classes.index[0]
    elif(pRetType == "Prob"):
        return x_classes.values[0] * 1.0 / x_classes.sum()
    return

def PlotScatter(pX,pY):

    x = pX
    y = pY

    volume = []
    colorsOfPoint = []

    for yi in np.arange(len(y)):

        if yi == len(y) - 1:
            volume.append(200)
        else:
            volume.append(20)

        if y[yi] == "A":
            colorsOfPoint.append("r")
        elif y[yi] == "B":
            colorsOfPoint.append("g")
        elif y[yi] == "C":
            colorsOfPoint.append("b")

    print(volume)
    print(colorsOfPoint)
    plt.scatter(x[:, 0], x[:, 1], c=colorsOfPoint, s=volume)
    plt.show()

if __name__ == "__main__":
    x, y = CreateData()

    point = [0.1,0.1]
    label = "B"

    print(ClassifierForKNN(point,label,x,y,4,pRetType="prob"))

    x = np.vstack((x,point))
    y = np.hstack((y,label))
    PlotScatter(x,y)

运行结果:

KNN brute python实现

相关文章:

  • 2021-04-09
  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-18
  • 2021-11-24
猜你喜欢
  • 2021-12-14
  • 2022-12-23
  • 2021-12-31
  • 2021-07-21
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案