机器学习与深度学习(二) k近邻分类算法 (K-Nearest Neighbor) KNN

____tz_zs学习笔记


k近分类算法 (K-Nearest Neighbor) KNN

为了判断未知实例的类别,以所有已知类别的实例作为参照
     选择参数K
     计算未知实例与所有已知实例的距离
     选择最近K个已知实例
     根据少数服从多数的投票法则(majority-voting),让未知实例归类为K个最邻近样本中最多数的类别
     优化:考虑距离,根据距离加上权重

Euclidean Distance 欧几里得距离


算法优点

简单

易于理解

容易实现

通过对K的选择可具备丢噪音数据的健壮性  

算法缺点

需要大量空间储存所有已知实例

算法复杂度高(需要比较所有已知实例与要分类的实例)

当其样本分布不平衡时,比如其中一类样本过大(实例数量过多)占主导的时候,新的未知实例容易被归类为这个主导样本,因为这类样本实例的数量过大,但这个新的未知实例实际并木接近目标样本


范例:knn代码逻辑实现

import csv  
import random  
import math  
import operator  
  
# 加载数据集 (文件,划分数据集的一个值(0~1之间),训练数据集,测试数据集)  
def loadDataset(filename, split, trainingSet = [], testSet = []):  
    with open(filename, 'rb') 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])  
  
# 欧几里德距离 (实例1,实例2,维度)  
def euclideanDistance(instance1, instance2, length):  
    distance = 0  
    for x in range(length):  
        # 每一维度进行减法,然后平方,加到distance  
        distance += pow((instance1[x]-instance2[x]), 2)  
    # 开方  
    return math.sqrt(distance)  
  
# 返回最近k个neighbors    
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):  #取前k个  
        neighbors.append(distances[x][0])  
        return neighbors  
  
# 得到每一个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.iteritems(), 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('irisdata.txt', 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]))  
        accuracy = getAccuracy(testSet, predictions)  
        print('Accuracy: ' + repr(accuracy) + '%')  
  
if __name__ == '__main__':  
    main()




你可能感兴趣的:(#,人工智能_资料)