Created
January 14, 2015 01:05
-
-
Save yakreved/42c911332e82ea025b48 to your computer and use it in GitHub Desktop.
Играл с эволюционным алгоритмом
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Evolution | |
def initialize(sample_array, quality_func) | |
#attr_accessor :sample_array, :quality_func, :population_size, :generations_count, :mutations_in_generation | |
@sample_array = sample_array | |
@quality_func = quality_func | |
@population = [] | |
@population_size = 1000 | |
@generations_count = 100 | |
@mutations_in_generation = 100 | |
end | |
def quality_sort(generation) | |
generation.sort_by! { |x| @quality_func.call(x) } | |
end | |
def generate_samples | |
@population_size.times do | |
@population << generate_random_child | |
end | |
end | |
def generate_random_child | |
new_child = @sample_array.clone | |
new_child.each_with_index { |m,i| new_child[i] = random_gen(m) } | |
return new_child | |
end | |
def random_gen(gen,power=4) | |
if gen.class == Fixnum or gen.class == Float | |
return rand(gen*power)-gen*power/2 | |
end | |
return gen | |
end | |
def make_a_child(father,mother) | |
child = mother.clone | |
child.each_with_index do |p,i| | |
child[i] = father[i] if rand>0.5 | |
end | |
end | |
def mutate(idiot) | |
idiot.each_with_index do |p,i| | |
idiot[i] = random_gen(idiot[i],0.1) if rand>0.5 | |
end | |
end | |
def run | |
generate_samples | |
#p @population | |
@generations_count.times do |generation_num| | |
#p "generation "+ generation_num.to_s | |
quality_sort(@population) | |
new_population = [] | |
while new_population.length < @population_size #reproduction | |
new_population << make_a_child(@population.sample, @population.sample) | |
end | |
@mutations_in_generation.times do |i| #make mutations | |
mutate(new_population[-i-1]) | |
end | |
@population = @population.values_at(0..@population_size/2) #kill half | |
@population += new_population | |
end | |
quality_sort(@population) | |
return @population[0] | |
end | |
end | |
# x2 − 2x − 3 = 0; Ответ 3,-1 | |
evo = Evolution.new([5.0,4.0], lambda {|x| (x[0]**2-x[0]*2-3).abs + (x[1]**2-x[1]*2-3).abs}) | |
p evo.run.to_s | |
# -x**2 - 2x +15 = 0; Ответ -5,3 | |
evo = Evolution.new([5.0,4.0], lambda {|x| ( -x[0]**2-x[0]*2+15).abs + (-x[1]**2-x[1]*2+15).abs}) | |
p evo.run.to_s | |
#-6 + 11*x + 6x**2+ x**3 =0; Ответ 1,2,3 | |
qtest = lambda {|x| (-6 + 11*x[0] + 6*(x[0]**2)+ x[0]**3).abs + (-6 + 11*x[1] + 6*(x[1]**2)+ x[1]**3).abs + (-6 + 11*x[2] + 6*(x[2]**2)+ x[2]**3).abs} | |
evo2 = Evolution.new([5.0, -4.0, 6.0],qtest) | |
p evo2.run.to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment