遺伝的アルゴリズムの設計(超初心者)
[注意]プログラミングをはじめて1週間ほどの初心者です。
遺伝的アルゴリズムと書いていますが全く厳密なものではなく、内容は適当です。
[概要]言語:Python
1, 19の数値を20個持つリストをランダムに10体生成4をループ
2, 0を最も多く持つリスト(father)、2番目に多く持つリスト(mother)を判定
3, fatherとmotherの持つ要素をインデックス毎に集約しリスト化(samples)
4, samplesからインデックス毎にランダムに要素を取り出し新世代(newgene)を10体生成
5, 手順2
ここまでの動作は問題なく機能します。
発生している問題
何周かループすると全て同じリストになり(0の数が全て同じになる)、変化が止まるので、
その場合(newgeneが全て同率1位)のみ突然変異として、fatherの1箇所を
ランダムな数値に変更(リストの置換)する処理をしています。
この時、fatherのみ変更しているにも関わらず、なぜかmotherにも全く同じ変更が発生します。
そのため突然変異が実現できていません。
該当のソースコード
python
1import random 2 3# 0~9の数値をランダムに20個持つリスト kid を10個作成し kids にリスト化 4 5kid = [] 6kids = [] 7for _ in range(11): 8 kids.append(kid) 9 kid = [] 10 for _ in range(20): 11 kid.append(random.randint(0, 9)) 12kids.pop(0) 13 14loop = 1 15 16# --------------------以下ループ------------------------- 17# だいたい1000回以内に同率1位の状態となり、58行目がうまくいかない問題が発生する 18 19for _ in range(1000): 20 21 # kids の 0 の数をカウントし each_0_counts にリスト化 22 23 each_0_counts = [] 24 for x in kids: 25 each_0_counts.append(x.count(0)) 26 27 # 最も多い 0 の個数を max_score 28 # その次に多い 0 の個数を premax_score とする 29 30 max_score = max(each_0_counts) 31 premax_score = 0 32 for x in each_0_counts: 33 if x == max_score: 34 continue 35 elif x > premax_score: 36 premax_score = x 37 else: 38 pass 39 40 # 0の個数が全て同じ場合(同率1位)の処理 41 42 if premax_score == 0: 43 premax_score = max_score 44 else: 45 pass 46 47 # 1位、2位のリスト番号を取得し、fatherとmotherを決める 48 49 father_index = each_0_counts.index(max_score) 50 mother_index = each_0_counts.index(premax_score) 51 52 father = kids[father_index] 53 mother = kids[mother_index] 54 55 # 問題の箇所 56 # 同率1位の場合、変化の停止を避けるため、fatherの一部をランダムに変更する 57 # このときfather、motherをプリントして調べてみると、なぜかmotherまで変更される 58 59 if premax_score == max_score: 60 father[random.randint(0, 19)] = random.randint(0, 9) 61 else: 62 pass 63 64 parents = [] 65 parents.append(father) 66 parents.append(mother) 67 68 print("\n父 : " + str(father)) 69 print("母 : " + str(mother)) 70 71 # parentsの要素をインデックス毎にsamplesにリスト化 72 73 sample = [] 74 samples = [] 75 for y in range(21): 76 samples.append(sample) 77 sample = [] 78 for x in parents: 79 try: 80 sample.append(x[y]) 81 except IndexError: 82 continue 83 samples.pop(0) 84 85 # sampleからランダムに要素を追加し、新しい個体(newgenes)を10体生成 86 87 newgenes = [] 88 for _ in range(10): 89 newgenes.append([]) 90 91 xx = -1 92 xy = 0 93 for _ in range(20): 94 xx += 1 95 xy = 0 96 for _ in range(10): 97 try: 98 add = random.choice(samples[xx]) 99 newgenes[xy].append(add) 100 xy += 1 101 except IndexError: 102 continue 103 104 print("第" + str(loop) + "世代") 105 for x in newgenes: 106 print(str(x)) 107 108 # ループに戻るためnewgenesをkidsに代入 109 110 loop += 1 111 kids = newgenes
試したこと
・fatherのリスト置換に問題が起きていると考え、リストの一部を置換ではなくfather自体に
文字列や関係のないリストを代入してみたところ、motherは影響を受けませんでした。
つまりfatherの一部を置換しようと場合のみ、motherも変更されるバグが起きています。
この原因が不明です。
補足情報(FW/ツールのバージョンなど)
PC: Mac
エディタ: Atom
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/30 05:51