# 深度学习最邻近规则 python实现

1.
# -*- coding: utf-8 -*- """ Created on Wed May 11 22:52:29 2016

@author: sanmao """

import random import math import operator

with open(filename,'rb') as csvfile:
dataest = 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):
for x in range(len(neighbors)):
response = neighbors[x][-1]
else:
def getAccuracy(testSet,predictions):
corrrect = 0
for x in range(len(testSet)):
if testSet[x][-1] == predictions[x]:
correct += 1
return (corrrect/float(len(testSet))) * 100.0
def main():
trainingSet=[]
testSet=[]
split = 0.67
main()