Advertisement
Guest User

Untitled

a guest
May 22nd, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.67 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import division
  4. import sys
  5. import random
  6. import math
  7.  
  8.  
  9. def std_deviation(points):
  10.     """ среднеквадратичное отклонение """
  11.     return math.sqrt(reduce(lambda x,y: x+(y-sum(points)/len(points))**2, points)/len(points))
  12.     #return sum(points)/len(points)
  13.  
  14.  
  15. def fitness_func(k1, k2, points):
  16.     """ при одном x разность y должна стремиться к 0 для всех точек """
  17.     deviations = map(lambda p: abs(p[1] - (k1*p[0]+k2)), points)
  18.     return std_deviation(deviations)
  19.  
  20.  
  21. def gen_population(prev_population, points):
  22.     """ prev_population = [([k1, k2,], ff),] """
  23.     best_two = sorted(prev_population, key=lambda x: abs(x[1]))[:2]
  24.     population = []
  25.     mutation_rate = 0.2
  26.     #print '======'
  27.     for parent in best_two:
  28.         population.append(parent)
  29.         for i in xrange(10):
  30.             koeffs = [parent[0][0],parent[0][1]]
  31.             rand_pos = random.randint(0, len(koeffs)-1)
  32.             koeffs[rand_pos] = koeffs[rand_pos] + (random.random()*2 - 1)  # koeffs[rand_pos]*(random.random()*2 - 1) * mutation_rate
  33.             ff = fitness_func(koeffs[0], koeffs[1], points)
  34.             #print 'y = %s*x + %s    %s' % (koeffs[0], koeffs[1], ff)
  35.             population.append(([koeffs[0], koeffs[1]], ff))
  36.     return population
  37.  
  38.  
  39. if __name__ == '__main__':
  40.     random.seed()
  41.     print 'y = k*x + b  _deviation_'
  42.     points = [(1,3), (2,5), (6,6), (3,3), (4,8)]  # y = 2x + 1
  43.     population = []
  44.     for i in xrange(10):
  45.         k1 = random.randint(-5, 5)
  46.         k2 = random.randint(-5, 5)
  47.         ff = fitness_func(k1, k2, points)
  48.         # print 'y = %s*x + %s    %s' % (k1, k2, ff)
  49.         population.append(([k1, k2], ff))
  50.  
  51.     print '=========='
  52.     import matplotlib.pyplot as plt
  53.     for i in xrange(100):
  54.         fig, ax = plt.subplots( nrows=1, ncols=1 )
  55.         x = range(-10, 10)
  56.         best = sorted(population, key=lambda x: abs(x[1]))[0]
  57.         koeffs = best[0]
  58.         ff = best[1]
  59.         y = [koeffs[0]*_x+koeffs[1] for _x in x]
  60.         ax.set_autoscaley_on(False)
  61.         ax.set_ylim([0,10])
  62.         ax.plot(x, y)
  63.         ax.plot(*zip(*points), marker='o', color='r', ls='')
  64.         lbl = 'y = %s*x + %s    %s' % (koeffs[0], koeffs[1], ff)
  65.         ax.text(0.5, 0.5,lbl,
  66.                 horizontalalignment='center',
  67.                 verticalalignment='center',
  68.                 transform = ax.transAxes)
  69.         fig.savefig('%s.png' % i)
  70.         plt.close(fig)
  71.         population = gen_population(population, points)
  72.     best_two = sorted(population, key=lambda x: abs(x[1]))[:2]
  73.     print best_two[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement