簡単な遺伝的アルゴリズム

December 15, 2019

ブログタイトルの「描きたい」とは少し離れますが。

Nature of Codeを読み直しているので、その中から、To be or not to be.という文を遺伝的アルゴリズムで生成する例を動かしてみます。

https://www.borndigital.co.jp/book/5425.html

書籍のサンプルコードをJRubyArt向けに移植されているものがあったので、 ほぼそのまま使わせてもらいました。

元にしたコード

https://github.com/ruby-processing/The-Nature-of-Code-for-JRubyArt/blob/master/chp09_ga/NOC_9_01_GA_Shakespeare/NOC_9_01_GA_Shakespeare.rb

今回動かしたコード

https://github.com/tnantoka/ruby.tnantoka.com/blob/5b9743e1e784eec33dfef54d23fcf8aca09a2775/shakespeare.rb

p5のmap相当のメソッドは今後も使いそうなのでヘルパーとして切り出しておきました。

https://github.com/tnantoka/ruby.tnantoka.com/blob/5b9743e1e784eec33dfef54d23fcf8aca09a2775/helpers.rb

実行例

今回は750世代目でうまくいったようです。

1
2
3
4
5
6
7
8
9
10
11
$ bundle exec ruby shakespeare.rb 

Best phrase: To be or not to be.
total generations: 750
average fitness:   0.7596491228070177
total population:  150
mutation rate:     1
All phrases:
["l5]b9\"or not/to be.", "T, bn or nM2/to bF.", "T6 be brKnht tolbe.", "T5 ce orKnot to be.", "T, %e oG not t= be.", "1, ce o2gnot toPbu.", "T6 bn or mhtWtoRbe.", "T5 ce orKnot 7o be.", "T, bevo2gnot to be.", "T5 bn or _Mt ]o be.", "T5 bn or noe tW be.", "T, RM or notUto be.", "T, be or not<toSbe.", "Ty be or not to0ber", "T, Rn )r nht to bK.", "T6 be !rN(Mt ko be.", "T, ke <r nMt/ta be.", "T5 be or@nXt to be.", "T6 >M)or '#t<toZbK.", "T6 beQ<r not 7o be.", "T5 bn orinot Qo be.", "T5\"be orK_#t<toSbe.", "T5 be or@nXO toSbe.", "T, be or '#t<toSbe.", "T5 bn orK_#t<to ber", "T6 bn or mhtWtoRbe.", "G5 be or noy/toRbv.", "T6 bn or nMt/toZbK.", "T6 be br _ot to be.", "TL ce orinot2tuRbB.", "TW Ze9orK(Mt to ber", "T, Rn )rKnot ]o;be.", "TL ce or no- toZbe.", "T6 be or not ]o be.", "T, ce Ir not ]o be.", "T, 5e \\rlnot to be.", "T6 >M)or no$ toRMK.", "l5]be or not to bF.", "T2 be orgnot/toRbe.", "T5 ce or not to be.", "T6 be !rK(Mt tW be.", "Tq beJoG not to be.", "T5 b  Nrinot2to be.", "Te be orgnot to be.", "T6 be or not to be.", "T, be or not to Pe.", "T5 ce or not tW be.", "T6 be oJKnot so be.", "T5 be orK_ot to bF.", "T5 bn otlnot ]o be."]

finished