1. 程式人生 > >機器學習(4)K最近鄰演算法

機器學習(4)K最近鄰演算法

定義:根據最近的樣本決定測試樣本的類別。

為了判斷未知例項的類別,以所有已知類別的例項作為參照

     選擇引數K     計算未知例項與所有已知例項的距離     選擇最近K個已知例項     根據少數服從多數的投票法則(majority-voting),讓未知例項歸類為K個最鄰近樣本中最多數的類別關於距離的衡量方法:

Euclidean Distance 定義

其他距離衡量:餘弦值(cos), 相關度 (correlation), 曼哈頓距離 (Manhattan distance)

上例的k=4,則綠色的樣本為紅色的類別

演算法優點:

簡單,易於理解,容易實現,通過對K的選擇可具備丟噪音資料的健壯性

缺點:

需要大量空間儲存所有已知例項, 演算法複雜度高(需要比較所有已知例項與要分類的例項)

當其樣本分佈不平衡時,比如其中一類樣本過大(例項數量過多)佔主導的時候,新的未知例項容易被歸類為這個主導樣本,因為這類樣本例項的數量過大,但這個新的未知例項實際並木接近目標樣本

例子:

150個例項萼片長度,萼片寬度,花瓣長度,花瓣寬度(sepal length, sepal width, petal length and petal width)類別:Iris setosa, Iris versicolor, Iris virginica.
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 predictedLabel


#  KNN 實現Implementation:

# Example of kNN implemented from Scratch in Python

import csv
import random
import math
import operator

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])


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)):
        dist = euclideanDistance(testInstance, trainingSet[x], length)
        distances.append((trainingSet[x], 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.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('iris.data.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)):
        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) + '%')
    
main()