def get(): def f((x, y, z)): return ((float(x), float(y)), float(z)) #def f(args): print args; (x, y, z) = args; return ((float(x), float(y)), float(z)) return [f(line.split()) for name in ['earthquake1.txt', 'earthquake2.txt'] for line in file(name) if line.strip()] DATA = get() N = len(DATA) e = 2.718281828 def logit(x): return 1/(1 + e**(-x)) def h(x, (w0, w1)): return logit(x*w1 + w0) def frange(start, stop, n=30): nm1 = n - 1. return [(start*(nm1 - i) + stop*i)/nm1 for i in range(n)] def ffrange(lo, hi, inc=.1): return [lo+(i*inc) for i in range(1+(hi-lo)/inc)] def L1(y, y1): return abs(y-y1) def L2(y, y1): return (y-y1)**2 L = L2 def Loss(W): return sum(L(h(x, W), y) for x,y in DATA)/N def allvalues(): return [(Loss((w0,w1)), w0, w1) for w0 in frange(-10., 0.) for w1 in frange(0., 4.)] #print max(allvalues()) import heapq def vote(items): votes = [Y for _,Y in items] votes.sort() return votes[len(items)/2] def NN(X, n): return vote(heapq.nsmallest(n, ([distance(X, Xi), Yi] for Xi,Yi in DATA))) def distance((x1,y1), (x2,y2)): return (x1-x2)**2 + (y1-y2)**2 def put(n=1): global DATA DATA = get(); N = len(DATA) f = open(('nn-%d.txt' % (n,)), 'w') for x in ffrange(4.5, 7, 0.05): for y in ffrange(2.7, 7.4): if NN((x,y), n) == 1: print >> f, x, y, 1 put(1);put(3);put(5);print 'ok'