机器学习笔记——最邻近算法(KNN)

最邻近算法(K-Nearest Neighbor,KNN)


1、算法综述

  • Cover和Hart在1968年提出了最初的邻近算法
  • 分类(Classification)算法
  • 输入给予实例的学习(Instance-based learning),懒惰学习(lazy learning)

2、算法原理

  • 为了判断未知实例的类别,以所有已知类别的实例作为参照
  • 选择参数K
  • 计算未知实例与与所有已知实例的距离
  • 选择最近K个已知实例
  • 根据少数服从多数原则(Majority-Voting),让未知实例归类为K个最近样本中最多数的类别。

关于距离的衡量方法:

  • Euclidean Distance
    Euclidean Distance
    在具体的数据中,每一个点不一定仅存在于二维空间中,也有可能为三维,四维…..
    无论几维,其到某点( x m , y m , . . . , z m )距离计算公式都为
    E ( d ) = ( x 1 x m ) 2 + ( y 1 y m ) 2 + . . . + ( z 1 z m ) 2
  • 其他距离的衡量方式:余弦值(Cos),相关度(Correlation),曼哈顿距离(Manhattan Distance)

3、算法举例

电影名称 打斗次数 接吻次数 电影类型
Clifornia Man 3 104 Romance
He’s Not Really into Dudes 2 100 Romance
Beautiful Woman 1 81 Romance
Kevin Longblade 101 10 Action
Robo Stayer 3000 99 5 Action
Amped II 98 2 Action
Unknown 18 90 Unknown

通过以上六部电影来预测Unknown为何电影类型
***Step 1***
将每部电影转化为空间坐标中的一个点得到下表

X坐标 Y坐标 点类型
A 3 104 Romance
B 2 100 Romance
C 1 81 Romance
D 101 10 Action
E 99 5 Action
F 98 2 Action
G 18 90 Unknown

***Step 2***
使用ComputeEuclideanDistance()函数分别计算G点到其他点的距离

import math
def ComputeEuclideanDistance(x1, y1, x2, y2):
    d = math.sqrt(math.pow((x1-x2), 2) + math.pow((y1-y2), 2))
    return d

d_ag = ComputeEuclideanDistance(3, 104, 18, 90)
d_bg = ComputeEuclideanDistance(2, 100, 18, 90)
d_cg = ComputeEuclideanDistance(1, 81, 18, 90)
d_dg = ComputeEuclideanDistance(101, 10, 18, 90)
d_eg = ComputeEuclideanDistance(99, 5, 18, 90)
d_fg = ComputeEuclideanDistance(98, 2, 18, 90)

print('unknown_A:',d_ag)
print('unknown_B:',d_bg)
print('unknown_C:',d_cg)
print('unknown_D:',d_dg)
print('unknown_E:',d_eg)
print('unknown_F:',d_fg)
**运行结果**
unknown_A: 20.518284528683193
unknown_B: 18.867962264113206
unknown_C: 19.235384061671343
unknown_D: 115.27792503337315
unknown_E: 117.41379816699569
unknown_F: 118.92854997854805

***Step 3***
若K值取3,则选出距离中最短的三个,即unknown_A: 20.518284528683193、unknown_B: 18.867962264113206、unknown_C: 19.235384061671343根据少数服从多数的原则,G应属于A、B、C三个点所代表的类型,即Romance类型

4、算法的优缺点
优点:

  • 算法优点
  • 简单
  • 易于理解
  • 容易实现
  • 通过对K的选择可具备丢噪音数据的健壮性

缺点:

  • 需要大量空间储存所有已知实例
  • 算法复杂度高(需要比较所有已知实例与要分类的实例)
  • 当其样本分布不平衡时,比如其中一类样本过大(实例数量过多)占主导的时候,新的未知实例容易被归类为这个主导样本,因为这类样本实例的数量过大,但这个新的未知实例实际并木接近目标样本,如下图:

5、案例
数据集介绍:
Iris数据集数sklearn自带的数据集,其中包含150个样本,样本内容为

萼片长度(sepal length) 萼片宽度(sepal width) 花瓣长度(petal length) 花瓣宽度(petal width) 类别(type)

其中花的类别分为:Iris setosa(0), Iris versicolor(1), Iris virginica(2).三种
Iris数据集
下面通过sklearn库的Iris数据集建立最邻近算法模型以预测萼片长度为0.1,萼片宽度为0.2,花瓣长度为0.3,花瓣宽度为0.4的为何种花型。

from sklearn import neighbors
from sklearn import datasets
knn = neighbors.KNeighborsClassifier()
iris = datasets.load_iris()
#print iris
knn.fit(iris.data, iris.target)
predictedLabel = knn.predict([[0.1, 0.2, 0.3, 0.4]])
#print "hello"
#print ("predictedLabel is :" + predictedLabel)
print predictedLabel
*******运行结果*********
[0]

代码运行结果返回值为0,故可知,所预测的花型为Iris setosa

6、代码实现KNN算法
依旧以上述iris数据集为例,随机取150个样本中的一部分作为training data,另一部分作为test data
——–>数据集下载

import csv
import random
import math
import operator

def loadDataset(filename, split, trainingSet = [], testSet = []):
    with open(filename, 'rt') as csvfile:
        lines = csv.reader(csvfile)
        dataset = list(lines)
        for x in range(len(dataset)-1):
            for y in range(4):
                dataset[x][y] = float(dataset[x][y])
            if random.random() < split:
                trainingSet.append(dataset[x])
            else:
                testSet.append(dataset[x])


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


def getNeighbors(trainingSet, testInstance, k):
    distances = []
    length = len(testInstance)-1
    for x in range(len(trainingSet)):
        #testinstance
        dist = euclideanDistance(testInstance, trainingSet[x], length)
        distances.append((trainingSet[x], dist))
        #distances.append(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]


def getAccuracy(testSet, predictions):
    correct = 0
    for x in range(len(testSet)):
        if testSet[x][-1] == predictions[x]:
            correct += 1
    return (correct/float(len(testSet)))*100.0


def main():
    #prepare data
    trainingSet = []
    testSet = []
    split = 0.67
    loadDataset(r'数据文件路径', split, trainingSet, testSet)
    print('Train set: ' + repr(len(trainingSet)))
    print('Test set: ' + repr(len(testSet)))
    #generate predictions
    predictions = []
    k = 3
    for x in range(len(testSet)):
        # trainingsettrainingSet[x]
        neighbors = getNeighbors(trainingSet, testSet[x], k)
        result = getResponse(neighbors)
        predictions.append(result)
        print ('>predicted=' + repr(result) + ', actual=' + repr(testSet[x][-1]))
    print ('predictions: ' + repr(predictions))
    accuracy = getAccuracy(testSet, predictions)
    print('Accuracy: ' + repr(accuracy) + '%')

if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/Peter_Huang0623/article/details/81569421