遺伝的アルゴリズムで遊ぶ 1

 学校の文化祭的なので、AI作ろうという流れになって、以前から少し興味を持ちつつ先延ばししてた遺伝的アルゴリズムに本格的に手をつけようと本を読んでいます。で、すごい簡易的ですが、交叉だけで遊んでみたので。。

# coding: utf-8
import random

generation = []
def initialize():
    global generation
    for i in range(10):
       chrom = []
       for j in range(10):
            chrom.append(random.randint(0,1))
       generation.append(chrom)

def fitness(indiv):
    count = 0
    for x in indiv:
        if x==1: count+=1
    if count <= 5: return 0.5
    return count/10.0

# 一点交叉
def crossover(p1, p2):
    max = len(p1) - 1
    point = random.randint(0,max)
    x = p1[point]
    p1[point] = p2[point]
    p2[point] = x
    return p1, p2

# バブルソート
def calculate_fit():
    global generation
    k = len(generation) - 1
    for i in range(k):
        for j in xrange(k,i,-1):
            if fitness(generation[j-1])>fitness(generation[j]):
                t = generation[j-1]
                generation[j-1] = generation[j]
                generation[j] = t
            
        
def simple_crossover():
    max = len(generation)-1
    select1 = random.randint(0,max)
    select2 = random.randint(0,max)
    while select1==select2:
        select2 = random.randint(0,max)
    p1 = generation[select1]
    p2 = generation[select2]
    p1,p2 = crossover(p1,p2)
    # fitnessの高い方を返す
    if fitness(p1)>fitness(p2): return p1
    return p2


def main():
    global generation
    initialize()
    calculate_fit()
    for i in range(10):
        next_generation = []
        next_generation.append(generation[9])
        next_generation.append(generation[8])
        for j in range(8):
            next_generation.append(simple_crossover())
        generation = next_generation
        calculate_fit()
        for x in generation[9]:
            print x,
        print "\n"

if __name__ == '__main__':
    main()

ゴミみたいなプログラムですが。。。。

出力は

% python ga_test1.py
1 1 0 1 1 0 1 1 0 1 

1 1 1 1 1 0 1 0 0 1 

0 1 1 0 1 1 1 1 1 1 

1 1 1 0 0 1 1 1 1 1 

1 1 1 1 1 1 1 1 1 1 

1 1 1 1 1 1 1 1 1 1 

1 1 1 1 1 1 1 1 1 1 

1 1 1 1 1 1 1 1 1 1 

1 1 1 1 1 1 1 1 1 1 

1 1 1 1 1 1 1 1 1 1 

うまく行くとこんな感じになりますが、うまくいかないとゴミですし、そもそもやってることが(ry