<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dabbler &#187; algorithm</title>
	<atom:link href="http://sethjust.com/tag/algorithm/feed/" rel="self" type="application/rss+xml" />
	<link>http://sethjust.com</link>
	<description>If it ain&#039;t broke, fix it!</description>
	<lastBuildDate>Fri, 16 Jul 2010 00:19:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Genetic Algorithms in Perl</title>
		<link>http://sethjust.com/2008/12/11/genetic-algorithms-in-perl/</link>
		<comments>http://sethjust.com/2008/12/11/genetic-algorithms-in-perl/#comments</comments>
		<pubDate>Thu, 11 Dec 2008 09:20:19 +0000</pubDate>
		<dc:creator>sethjust</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[evolution]]></category>
		<category><![CDATA[genetic]]></category>
		<category><![CDATA[genetic algorithm]]></category>

		<guid isPermaLink="false">http://sethjust.wordpress.com/?p=38</guid>
		<description><![CDATA[Inspired by recent genetic algorithms floating around, I decided to try my hand at implementing one in perl. I&#8217;d thought for a long time that it would be quite difficult, but really it&#8217;s quite easy. My biggest hangup was dealing with data structures, but once I did that, it turns out that all you really [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by <a href="http://hackaday.com/2008/12/08/genetic-programming/">recent</a> <a href="http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/">genetic</a> <a href="http://www.wreck.devisland.net/ga/">algorithms</a> floating around, I decided to try my hand at implementing one in perl. I&#8217;d thought for a long time that it would be quite difficult, but really it&#8217;s quite easy. My biggest hangup was dealing with data structures, but once I did that, it turns out that all you really need is a few functions:</p>
<ul>
<li>A fitness function, that determines which individuals are most fit to reproduce</li>
<li>A mutate function, that will add random chance into each generation</li>
<li>A breed function that allows the best individuals to reproduce.</li>
</ul>
<p>I ended up implementing a very simple algorithm, but it&#8217;s fairly fast and very generic – it can be easily adapted to just about any task. Sadly, I have no fascinating application just yet, but if I stumble across one, I&#8217;ll be sure to post about it.</p>
<p>After the jump, I&#8217;ll put up some of the code I used and a link to the script, all for your viewing pleasure.<br />
<span id="more-38"></span></p>
<p>The heart of the algorithm is the mutate and breed functions:</p>
<p>[sourcecode language='php']sub mutate{     # Mutates each allele of an individual by a random, weighted amount,<br />
                #    controlled by certain parameters. It re-initializes if the allele<br />
                #    is zero, and takes abs()<br />
    my $ind = shift;</p>
<p>    for (@$ind) {<br />
        $_ = eval($init_string) unless ($_);<br />
        $_ += (rand(2) &#8211; 1)*($mut_weight*($_)+$mut_offset);<br />
        $_ = -$_ unless ($_>0);<br />
    }</p>
<p>    return 0;<br />
}</p>
<p>sub breed{      # Breeds each individual with the top 20 percent of the population randomly<br />
                #    by averaging each allele of the individual with the corresponding allele<br />
                #    of a random individual in the top quintile. Note that this means that<br />
                #    each individual breeds with, at most (and ideally), as many individuals<br />
                #    as it has alleles, which breaks down the parent / child model slightly.<br />
    my $indvs = shift;<br />
    my @list;<br />
    ($minimize) || (@list = sort {fitness($b)  fitness($a)} @$indvs);  # Sort asc. vs. desc.<br />
    ($minimize) &#038;&#038; (@list = sort {fitness($a)  fitness($b)} @$indvs);</p>
<p>    @list = @list[1..(int(scalar(@list)/5)+1)];</p>
<p>    for (@$indvs) {              # Iterate through individuals<br />
        my $ind_ref = $_;<br />
        my $i = 0;<br />
        for (@$ind_ref) {        # Iterate through alleles<br />
            $_ = ((@list[int(rand(length(@list)-1))])->[$i] + $_)/2;      # Average given allele with<br />
                                                                          #    a random, fit,<br />
                                                                          #    corresponding allele<br />
            $_ = (rand(1)<$reset_prob?eval($init_string):$_);             # Re-init the allele some<br />
                                                                          #    percent of the time<br />
            $i++;<br />
        }<br />
    }</p>
<p>    return 0;<br />
}[/sourcecode]</p>
<p>Between the comments and the code, it should be pretty clear what's going on in here, although some of the data structures are kinda hard to get from this section. As I explain in the <a href="http://people.reed.edu/~justs/genes.pl">code</a>:</p>
<blockquote><p>A randomized population is created. An array holds references to the specified number of &#8220;individuals&#8221;. Each individual is an array of alleles (scalar values) that are chosen by evaluating a specified string. These are currently positive real numbers.</p></blockquote>
<p>These references (or references to the population array) are passed as arguments to the functions each iteration.</p>
<p>If you&#8217;re interested, be sure to check out the <a href="http://people.reed.edu/~justs/genes.pl">code</a> and please give me some feedback!</p>
<p>UPDATE: Ivan in the comments made the recommendation of using an anonymous function to intialize individuals. I made that change he recommended and updated the code.</p>
]]></content:encoded>
			<wfw:commentRss>http://sethjust.com/2008/12/11/genetic-algorithms-in-perl/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
