实现knn算法,完整程序
2021-07-03 08:05
标签:ase main red opera app txt file else class 实现knn算法,完整程序 标签:ase main red opera app txt file else class 原文地址:http://blog.51cto.com/13831593/2173693
从文件中读初始数据------计算目标点到已归类点的距离------根据距离最近原则判断目标点归属于哪一类别
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() predicted=‘ + repr(result) + ‘, actual=‘ + repr(testSet[x][-1]))
if result == testSet[x][-1]:
correct.append(x)
# print "len:"
# print len(testSet)
# print "correct:"
# print len(correct)
accuracy = (len(correct)/float(len(testSet)))*100.0
print(‘Accuracy: ‘ + repr(accuracy) + ‘%‘)
if __name__ == ‘__main__‘:
main()