python knn分类算法

本文详细介绍了一个基于欧几里得距离的K最近邻(KNN)分类算法实现。通过具体实例,展示了如何计算样本间的距离,选取最近邻样本进行分类预测。代码中包含了距离计算、邻居选择及响应类别获取等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import math
import operator
def euclideanDistance(inst1,inst2,length):
    distance=0
    for x in range(length):
        distance+=pow((inst1[x]-inst2[x]),2)
    return math.sqrt(distance)

def getNeightbors(trainningSet,testInstance,k):
    distances=[]
    length=len(testInstance)-1
    for x in range(len(trainingSet)):
        dist=euclideanDistance(testInstance,trainingSet[x],length)
        distances.append((trainningSet[x],dist))
    distances.sort(key=operator.itemgetter(1))
    neighbors=[]
    for x in range(k):
        neighbors.append(distances[x][0])
    return neighbors

def getResponse(neighbors):
    classvotes={}#定义字典
    for x in range(len(neighbors)):
        response=neighbors[x][-1]
        if response in classvotes:
            classvotes[response]+=1
        else:
            classvotes[response]=1
    sortedvotes=sorted(classvotes.items(),key=operator.itemgetter(1),reverse=True)
    return sortedvotes[0][0]

trainingSet=[[1,1,1,'a'],[2,2,2,'a'],[1,1,3,'a'],[4,4,4,'b'],[0,0,0,'a'],[4,4.5,4,'b']]
testInstance=[5,5,5]
k=5
neighbors=getNeightbors(trainingSet,testInstance,k)
response=getResponse(neighbors)
print(neighbors)
print(response)
### KNN分类算法的实现 KNN(K-Nearest Neighbors)是一种经典的监督学习算法,其基本原理是通过计算测试样本与训练样本之间的距离,找到离测试样本最近的K个邻居,并根据这些邻居所属的类别来决定测试样本的类别[^4]。 以下是使用Python实现KNN分类算法的具体方法: #### 数据准备 为了验证KNN算法的效果,通常会选用经典的数据集——鸢尾花数据集(Iris Dataset)。此数据集包含三类不同的鸢尾花卉,每类有50个样本,共150个样本。每个样本具有四个特征:萼片长度、萼片宽度、花瓣长度和花瓣宽度。 可以通过`scikit-learn`库加载鸢尾花数据集并对其进行预处理: ```python from sklearn.datasets import load_iris import numpy as np # 加载鸢尾花数据集 data = load_iris() X, y = data.data, data.target # 将数据划分为训练集和测试集 from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` #### 距离计算 KNN的核心在于计算样本间的距离。常用的欧氏距离公式为: \[ d(x_i, x_j) = \sqrt{\sum_{k=1}^{n}(x_{ik} - x_{jk})^2} \] 下面定义一个函数用于计算两点之间的欧氏距离: ```python def euclidean_distance(point1, point2): return np.sqrt(np.sum((point1 - point2)**2)) ``` #### 找到最近的K个邻居 对于每一个测试样本,我们需要遍历所有的训练样本,找出与其距离最小的K个邻居。 ```python def find_neighbors(train_data, test_instance, k): distances = [] for index, train_instance in enumerate(train_data): dist = euclidean_distance(test_instance, train_instance) distances.append((index, dist)) # 记录索引及其对应的距离 # 对距离列表按从小到大排序 sorted_distances = sorted(distances, key=lambda x: x[1]) # 提取前K个邻居的索引 neighbors_indices = [sorted_distances[i][0] for i in range(k)] return neighbors_indices ``` #### 投票机制确定类别 统计K个邻居中出现次数最多的类别作为最终预测结果。 ```python from collections import Counter def predict_class(neighbors_indices, labels): neighbor_labels = [labels[index] for index in neighbors_indices] most_common_label = Counter(neighbor_labels).most_common(1)[0][0] return most_common_label ``` #### 完整的KNN实现 将以上模块组合起来形成完整的KNN分类器: ```python class KNNClassifier: def __init__(self, k=3): self.k = k def fit(self, X_train, y_train): self.X_train = X_train self.y_train = y_train def predict(self, X_test): predictions = [] for test_sample in X_test: neighbors = find_neighbors(self.X_train, test_sample, self.k) predicted_class = predict_class(neighbors, self.y_train) predictions.append(predicted_class) return predictions ``` #### 测试模型性能 最后评估模型的表现: ```python if __name__ == "__main__": knn_model = KNNClassifier(k=5) knn_model.fit(X_train, y_train) predictions = knn_model.predict(X_test) accuracy = sum([1 for p, t in zip(predictions, y_test) if p == t]) / len(y_test) print(f"Accuracy of the model is {accuracy * 100:.2f}%") ``` ### 性能分析 尽管KNN算法简单易懂,但它存在一些局限性。由于每次预测都需要重新计算所有训练样本的距离,当训练集规模较大时,时间复杂度较高,效率较低[^2]。此外,在实际应用中可能会遇到噪声干扰的情况,从而影响分类精度[^3]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值