KNN(最邻近算法)

分类

属于监督学习、分类算法

算法原理

通过预测点计算距离训练样本点之间的距离,获取前k个最近的距离的训练样本点,通过该k个训练样本点所属分类投票来决定该预测点的种类(k一般取值为奇数)。(距离衡量可以为欧式距离、曼哈顿距离等等,具体看实际情况而定)

代码实现

调用库函数版:

from sklearn import neighbors
from sklearn import datasets
#得到分类器
knn = neighbors.KNeighborsClassifier()
#得到虹膜花的相关数据,特征为:萼片长度,萼片宽度,花瓣长度,花瓣宽度,标签为:Iris setosa, Iris versicolor, Iris virginica
iris = datasets.load_iris()
print(iris)
#训练算法
knn.fit(iris.data, iris.target)
#开始预测,预测:萼片长度=0.1,萼片宽度=0.2,花瓣长度=0.3,花瓣宽度=0.4的为什么种类虹膜
predictLabel = knn.predict([[0.1,0.2,0.3,0.4]])
#预测结果
print(predictLabel)

手工python代码版:

import csv
import random
import math
import operator

#载入数据
def loadDataset(filename, split, trainingSet = [], testSet = []):
    with open(filename, 'r') as csvfile:
        lines = csv.reader(csvfile)
        dataset = list(lines)
        print("dataset_type:"+str(type(dataset)))
        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)
#获取距离测试点最近的k个点的集合
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
#获取k个最近点的投票结果
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'E:/dataset/irisdata.txt', split, trainingSet, testSet)
    print ('Train set: '+str(len(trainingSet)))
    print ('Test set: ' +str(len(testSet)))
    #generate predictions
    predictions = []
    k = 11#k值,通过调节该参数来调整算法准确率
    for x in range(len(testSet)):
        # trainingsettrainingSet[x]
        neighbors = getNeighbors(trainingSet, testSet[x], k)
        result = getResponse(neighbors)
        predictions.append(result)
        print ('>predicted=' + str(result) + ', actual=' + str(testSet[x][-1]))
    print ('predictions: ' + str(predictions))
    accuracy = getAccuracy(testSet, predictions)
    print('Accuracy: ' + str(accuracy) + '%')

if __name__ == '__main__':
    main()

算法总结

算法优点

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

算法缺点

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

算法改进

考虑距离,根据距离加上权重
比如: 1/d (d: 距离)

你可能感兴趣的:(machine,learning)