filename: b13.py
import csv
from math import sqrt
import random
from collections import Counter
from operator import itemgetter
dataset = []
training = []
test = []
def loaddata():
with open('iris.data','rb') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
random.shuffle(dataset)
for x in range(15):
training.append(dataset[x])
for x in range(15,20):
test.append(dataset[x])
def calculate():
for x in test:
distances = []
abc = []
for y in training:
d = pow(int(x[0])-int(y[0]),2)
distances.append([sqrt(d),y])
sorteddistance = sorted(distances,key=itemgetter(0))
topk = sorteddistance[:3]
for (a,b) in topk:
abc.append(b)
classes = Counter(t for(p,t) in abc)
print "Class for"+str(x)+':'+ max(classes, key=lambda cls:classes[cls])
def main():
loaddata()
calculate()
main()
filename: iris.data
10,A
20,A
30,A
40,A
50,A
60,B
70,B
80,B
90,B
100,B
110,C
120,C
130,C
140,C
150,c
22,A
62,B
92,B
11,A
124,C
OUTPUT
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$python B13.py
Class for['40', 'A']:A
Class for['60', 'B']:B
Class for['92', 'B']:B
Class for['124', 'C']:C
Class for['90', 'B']:B
import csv
from math import sqrt
import random
from collections import Counter
from operator import itemgetter
dataset = []
training = []
test = []
def loaddata():
with open('iris.data','rb') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
random.shuffle(dataset)
for x in range(15):
training.append(dataset[x])
for x in range(15,20):
test.append(dataset[x])
def calculate():
for x in test:
distances = []
abc = []
for y in training:
d = pow(int(x[0])-int(y[0]),2)
distances.append([sqrt(d),y])
sorteddistance = sorted(distances,key=itemgetter(0))
topk = sorteddistance[:3]
for (a,b) in topk:
abc.append(b)
classes = Counter(t for(p,t) in abc)
print "Class for"+str(x)+':'+ max(classes, key=lambda cls:classes[cls])
def main():
loaddata()
calculate()
main()
filename: iris.data
10,A
20,A
30,A
40,A
50,A
60,B
70,B
80,B
90,B
100,B
110,C
120,C
130,C
140,C
150,c
22,A
62,B
92,B
11,A
124,C
OUTPUT
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$python B13.py
Class for['40', 'A']:A
Class for['60', 'B']:B
Class for['92', 'B']:B
Class for['124', 'C']:C
Class for['90', 'B']:B
No comments:
Post a Comment