k近邻(k-NN)算法的python实现

k-NN算法是实现分类的一种简单有效的算法,并且可以实现多类别分类。k-NN算法的三个要素为:距离度量、k值的选择以及分类决策规则。
本文采用欧式距离作为距离度量,近邻数量选取为7,采用多数票方式决定样本的类型。

from sklearn import datasets
import matplotlib.pyplot as plt # 画图工具
import numpy as np
import heapq
from collections import Counter

X, y = datasets.make_classification(n_samples=1000, n_features=10, n_classes=3, n_informative=3, random_state=1)#生成1000个样本,共有10个属性,分为3个类别
np.random.seed(0)
x_new = np.random.randint(5,20,[10,1])#生成一个随机的样本,作为新来样本

def distance():
    distances = []
    for i in range(X.shape[0]):
        t = 0
        for j in range(x_new.shape[0]):
            t += (x_new[j] - X[i][j])**2
        distances.append(t)
    result = map(distances.index, heapq.nsmallest(7, distances))#找出距离最小的7个样本在列表中的index
    y_list = []
    for i in list(result):
        y_list.append(y[i])#生成类别列表
    y_counter = Counter(y_list)#对列表列表进行统计
    for i in dict(y_counter):
        print('类别是:{}'.format(i))#展示投票法最终的结果
        break    
distance()         

运行代码后,得到最终的结果为:
输出类别

发布了5 篇原创文章 · 获赞 0 · 访问量 2102

猜你喜欢

转载自blog.csdn.net/qq_39320588/article/details/104088517