• k近邻(KNN)


    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)):
            #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.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(r'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]))
        print ('predictions: ' + repr(predictions))
        accuracy = getAccuracy(testSet, predictions)
        print('Accuracy: ' + repr(accuracy) + '%')
    
    if __name__ == '__main__':
        main()
    

      

  • 相关阅读:
    python学习笔记 day14 各种推导式
    python学习笔记 day14 生成器表达式
    python学习笔记 day14 生成器进阶(二)
    python学习笔记 day14 生成器进阶
    python学习笔记 day13 迭代器
    python 学习笔记 day12 作业讲解--员工信息表
    PAT L3-020 至多删三个字符
    2019省赛训练组队赛3.26周二---FJUT 2016
    PAT L3-007 天梯地图
    POJ 2234 Matches Game
  • 原文地址:https://www.cnblogs.com/wlc297984368/p/7463037.html
Copyright © 2020-2023  润新知