knn algorithm--python( classifying)

---恢复内容开始---

1. observe accoding to the purpose of analysis

2. decide a model of specific algorithm

3. clear the steps 

4. write the codes

classify algorithms:

knn; backstom(贝克斯算法) ; decision tree(决策树);artificial nueral network(ANN); 支持向量机(SVM)

knn:

 eg: drink(A,B,C); bread(D,E,F); makeup(H,I,J,K)

      X: price  ;   Y: sells

d(subject, M)   select k nodes who is closed to M(d is smallest)  M is classfied into ...

test data ; train data ;lables data;

a1=n.array([1,2,3,4,6,3])
a2=tile(a1,2)
print (a2)
a3=tile(a1,(2,3))
print(a3)
a3_sum=a3.sum
print(a3_sum)
a3_sum_axis=a3.sum(axis=1)#各行相加
print(a3_sum_axis)
a3_sum_axis1=a3.sum(axis=0)#各列相加
print (a3_sum_axis1)



****************************************************************************************
build module of knn:
from numpy import *
import numpy as n
import operator
def knn(k,test_data,train_data,labels):
train_data_size=train_data.shape[0]
dif=tile(test_data,(train_data_size,1))-train_data
sqdif=dif**2
sumsqif=sqdif.sum(axis=1)
distance=sumsqif**0.5
sort_distance=distance.argsort()
count={}
for i in range(0,k):
vote=labels[sort_distance[i]]
count[vote]=count.get(vote,0)+1
sortcount=sorted(count.items(),key=operator.itemgetter(1),reverse=True)#从大到小
return sortcount[0][0]



 

转载于:https://www.cnblogs.com/rabbittail/p/8126873.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值