Knn基础实现

#!/usr/bin/env python

-- coding: utf-8 --

@Time : 2020/10/22 19:43

@Author : Scheaven

@File : 13_kNN.py

@description:

简易写法

def kNN(inX,dataSet,labels,k):
m, n = dataSet.shape
distances = []
for i in range(m):
sum = 0
for j in range(n):
sum += (inX[j] - dataSet[i][j])2
distances.append(sum
0.5)
sortDist = sorted(distances)
classCount = {}
for i in range(k):
voteLabel = labels[distances.index(sortDist[i])]
classCount[voteLabel] = classCount.get(voteLabel) + 1
sortedClass = sorted(classCount.items(), key=lambda d:d[1] ,reverse = True)
return sortedClass[0][0]

// 综合知识写法----------------------------
import math
import numpy as np
from collections import Counter

def my_kNN(inX, X_trains, labels, k):
distances = [math.sqrt(np.sum((inX - x_train) ** 2)) for x_train in X_trains]
nearest = np.argsort(distances)
topK_label = [labels[i] for i in nearest[0:k]]
votes = Counter(topK_label)
return votes.most_common(1)[0][0]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值