knn简单使用

import numpy as np
import matplotlib.pyplot as plt


raw_data_X = [[3.393533211, 2.331273381],
              [3.110073483, 1.781539638],
              [1.343808831, 3.368360954],
              [3.582294042, 4.679179110],
              [2.280362439, 2.866990263],
              [7.423436942, 4.696522875],
              [5.745051997, 3.533989803],
              [9.172168622, 2.511101045],
              [7.792783481, 3.424088941],
              [7.939820817, 0.791637231]
             ]
raw_data_y = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]


X_train = np.array(raw_data_X)
y_train = np.array(raw_data_y)

KNN的过程

x = np.array([8.093607318, 3.365731514])
x




array([8.09360732, 3.36573151])




plt.scatter(X_train[y_train==0,0], X_train[y_train==0,1], color='g')
plt.scatter(X_train[y_train==1,0], X_train[y_train==1,1], color='r')
plt.scatter(x[0], x[1], color='b')
plt.show()

pgn

2个维度的x_train

from math import sqrt
distances = []
#for x_train in X_train: 
    #d = sqrt(np.sum((x_train -x) **2)) 
    #distances.append(d)


distances = [sqrt(np.sum((x_train - x )**2))for x_train in X_train] #y一句话打完
distances




[4.812566907609877,
 5.229270827235305,
 6.749798999160064,
 4.6986266144110695,
 5.83460014556857,
 1.4900114024329525,
 2.354574897431513,
 1.3761132675144652,
 0.3064319992975,
 2.5786840957478887]




np.argsort(distances) # 排序返回索引(从小到大)




array([8, 7, 5, 6, 9, 3, 0, 1, 4, 2], dtype=int64)




nearest = np.argsort(distances)


k = 6   #取前6个最近的点


topK_y = [y_train[i] for i in nearest[:k]]


topK_y




[1, 1, 1, 1, 1, 0]




from collections import Counter
Counter(topK_y)




Counter({1: 5, 0: 1})

1 代表的是肿瘤发生 , 0 代表的是无肿瘤

votes = Counter(topK_y)

most_common 返回一个TopN列表。如果n没有被指定,则返回所有元素。当多个元素计数值相同时,排列是无确定顺序的。 最终的投票为1
,表示预测的是肿瘤

votes.most_common(1)[0][0]




1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值