K-近邻(k-Nearest Neighbors)
我自己的理解就是:把输入的无标签数据,和现有的有标签数据进行特征比较,在最相似的K个数据中,把次数出现最多的分类(标签),作为新数据的分类。优点:精度高,
对异常值不敏感,无数据输入假定。
缺点:计算复杂度高,空间复杂度高。
使用数据范围:数值型和标称型。
python代码:
# -*- coding: UTF-8 -*-
from numpy import *
import operator
def creatDataSet():
group = array([[1.0, 1.1],[1.0, 1.0], [0, 0], [0, 0.1]])
labels = ['A','A','B','B']
return group, labels
def classify0(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX, (dataSetSize,1)) - dataSet # tile函数,tile([1,2],[2,2]) = array([[1,2,1,2],[1,2,1,2])
spDiffMat = diffMat**2
sqDistances = spDiffMat.sum(axis=1)
distances = sqDistances**0.5
sortedDistIndicies = distances.argsort() # argsort函数返回的是数组值从小到大的索引值
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlab