<?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>Blog Patrick Espake</title>
	<atom:link href="http://blog.patrickespake.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.patrickespake.com</link>
	<description>O conhecimento evolui quando é compartilhado!</description>
	<lastBuildDate>Wed, 09 Jun 2010 19:43:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1-alpha</generator>
		<item>
		<title>Criando um Hello World usando a Game Engine Flixel</title>
		<link>http://blog.patrickespake.com/2010/06/09/criando-um-hello-world-usando-a-game-engine-flixel/</link>
		<comments>http://blog.patrickespake.com/2010/06/09/criando-um-hello-world-usando-a-game-engine-flixel/#comments</comments>
		<pubDate>Wed, 09 Jun 2010 19:36:11 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Flixel]]></category>
		<category><![CDATA[Jogo]]></category>
		<category><![CDATA[actionscript 3]]></category>
		<category><![CDATA[exemplo]]></category>
		<category><![CDATA[flashdevelop]]></category>
		<category><![CDATA[hello world]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1225</guid>
		<description><![CDATA[Flixel é uma game engine escrita em ActionScript 3, facilita bastante a construção de alguns tipos e formatos de jogos, especialmente jogos de plataforma. Já possuí classes e métodos para lidar com: Texto; Colisão; Imagens Efeitos Mapa; Pontos; Estados; Fases; Inimigos; Vidas; Câmera e muitas outras coisas. Esse post tem o objetivo de construir um [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/hello_world.png"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/hello_world.png" alt="" title="hello_world" width="655" height="532" class="aligncenter size-full wp-image-1257" /></a></p>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/flixel.gif"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/flixel.gif" alt="" title="flixel" width="32" height="64" class="alignleft size-full wp-image-1227" /></a> <a href="http://www.flixel.org">Flixel</a> é uma game engine escrita em ActionScript 3, facilita bastante a construção de alguns tipos e formatos de jogos, especialmente jogos de plataforma. Já possuí classes e métodos para lidar com:</p>
<ul>
<li>Texto;</li>
<li>Colisão;</li>
<li>Imagens</li>
<li>Efeitos</li>
<li>Mapa;</li>
<li>Pontos;</li>
<li>Estados;</li>
<li>Fases;</li>
<li>Inimigos;</li>
<li>Vidas;</li>
<li>Câmera</li>
<li>e muitas outras coisas.</li>
</ul>
<p>Esse post tem o objetivo de construir um Hello World, esse exemplo será o passo inicial para a construção de jogos mais complexos no futuro.</p>
<p>Em primeiro lugar você precisa conhecer o site do Flixel: <a href="http://www.flixel.org">http://www.flixel.org</a> lá você encontra a game engine para download, fórum, wiki e outros games já desenvolvidos pela comunidade.</p>
<h2>Primeiro passo: Instalação do FlashDevelop</h2>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/fdwiki.png"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/fdwiki-e1276022967502.png" alt="" title="fdwiki" width="90" height="90" class="alignleft size-full wp-image-1232" /></a> Faça o download do FlashDevelop, nós vamos usar ele como IDE de desenvolvimento. Para fazer o download: <a href="http://www.flashdevelop.org/downloads/releases/FlashDevelop-3.2.1-RTM.exe">http://www.flashdevelop.org/downloads/releases/FlashDevelop-3.2.1-RTM.exe</a>.<br />
Faça a instalação seguindo o padrão next next finish be happy! :)</p>
<h2>Segundo passo: Flex SDK</h2>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/logo_adobe.gif"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/logo_adobe.gif" alt="" title="logo_adobe" width="34" height="42" class="alignleft size-full wp-image-1236" /></a> Para construir o jogo nós precisamos do Flex SDK, que são as bibliotecas padrões do ActionScript 3, a game engine Flixel utiliza essas bibliotecas internamente e você provavelmente vai precisar de alguma delas para as customizações ou necessidades do seu jogo.<br />
Faça o download: <a href="http://opensource.adobe.com/wiki/display/flexsdk/download?build=4.1.0.16248&#038;pkgtype=1">http://opensource.adobe.com/wiki/display/flexsdk/download?build=4.1.0.16248&#038;pkgtype=1</a> e descompacte em algum diretório da sua preferência, daqui a pouco nós vamos usar ele.</p>
<h2>Terceiro passo: Download do Flixel</h2>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/flixel.gif"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/flixel.gif" alt="" title="flixel" width="32" height="64" class="alignleft size-full wp-image-1227" /></a> Vamos precisar dele para a construção do jogo, ele na verdade é um framework de desenvolvimento de jogos. Já possui muitas bibliotecas prontas que facilitam e aceleram o desenvolvimento. Faça o download em: <a href="http://github.com/AdamAtomic/flixel/archives/master">http://github.com/AdamAtomic/flixel/archives/master</a> e descompacte também em algum diretório da sua preferência.</p>
<h2>Criando um Novo Projeto</h2>
<ul>
<li>Abra o FlashDevelop;</li>
<li>Clique no menu &#8220;Project&#8221;;</li>
<li>Clique na opção &#8220;New Project&#8221;;</li>
<li>Em &#8220;Installed Templates&#8221; selecione &#8220;AS3 Project&#8221;;</li>
<li>Em &#8220;Name:&#8221; digite HelloWorld;</li>
<li>Marque o checkbox na opção &#8220;Create directory for project&#8221;;</li>
<li>Clique no botão &#8220;Ok&#8221;.</li>
</ul>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/FlashDevelop01.png"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/FlashDevelop01-1024x796.png" alt="" title="FlashDevelop01" width="620" height="481" class="aligncenter size-large wp-image-1237" /></a></p>
<h2>Configurando o Flex SDK e Flixel no Projeto</h2>
<ul>
<li>Clique no menu &#8220;Project&#8221;;</li>
<li>Clique na opção &#8220;Properties&#8230;&#8221;;</li>
<li>Clique na aba &#8220;Compiler Options&#8221;;</li>
<li>No campo &#8220;Custom Path to Flex SDK&#8221; clique no botão &#8220;&#8230;&#8221; e selecione o diretório onde você descompactou o Flex SDK;</li>
<li>Clique na aba &#8220;Classpaths&#8221;;</li>
<li>Clique no botão &#8220;Add Classpaths&#8230;&#8221; e selecione o diretório onde você descompactou o Flixel, mas você precisa entrar na pasta e selecionar a pasta &#8220;org&#8221;;</li>
<li>Clique no botão &#8220;Ok&#8221;.</li>
</ul>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/compiler_options.png"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/compiler_options.png" alt="" title="compiler_options" width="374" height="431" class="aligncenter size-full wp-image-1241" /></a></p>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/classpaths.png"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/classpaths.png" alt="" title="classpaths" width="372" height="431" class="aligncenter size-full wp-image-1242" /></a></p>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/project.png"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/project.png" alt="" title="project" width="319" height="135" class="aligncenter size-full wp-image-1243" /></a></p>
<h2>Programando o HelloWorld</h2>
<h3>HelloWorld.as</h3>
<ul>
<li>No diretório <strong>src</strong> do projeto existe o arquivo <strong>Main.as</strong>, apague esse arquivo;</li>
<li>Clique com o botão direito do mouse na pasta &#8220;<strong>src</strong>&#8221; depois &#8220;<strong>add</strong>&#8221; e &#8220;<strong>New Class&#8230;</strong>&#8220;;</li>
<li>Digite para o campo &#8220;<strong>Name</strong>:&#8221; o valor: <strong>HelloWorld</strong>.</li>
</ul>
<p>Será gerando um código inicial como esse:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span>  
<span style="color: #009900;">&#123;</span>
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * ...
	 * @author Patrick Espake
	 */</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> HelloWorld
	<span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">public</span> function HelloWorld<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> 
		<span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Vamos alterar para ficar dessa forma:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span>  
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// Importa a game engine Flixel</span>
	<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.flixel.*</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Tamanho da tela e cor de fundo</span>
	<span style="color: #009900;">&#91;</span>SWF<span style="color: #009900;">&#40;</span>width <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;640&quot;</span>, height <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;480&quot;</span>, backgroundColor <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#000000&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#93;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Classe HelloWorld</span>
	<span style="color: #666666; font-style: italic;">// herda a classe FlxGame para incorporar as funcionalidades do Flixel</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> HelloWorld <span style="color: #000000; font-weight: bold;">extends</span> FlxGame
	<span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// Método construtor</span>
		<span style="color: #000000; font-weight: bold;">public</span> function HelloWorld<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> 
		<span style="color: #009900;">&#123;</span>
			<span style="color: #666666; font-style: italic;">// Tamanho da área útil</span>
			<span style="color: #666666; font-style: italic;">// classe inicial a ser chamada depois do jogo carregar</span>
			<span style="color: #666666; font-style: italic;">// e nível de zoom</span>
			<span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">640</span>, <span style="color: #cc66cc;">480</span>, PlayState, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>	
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Através dos comentários acima você deve ser capaz de entender a maioria do código, basicamente nós definimos a dimensões do swf que será gerado, a cor de fundo, e qual classe de estado deve ser chamada após o jogo terminar de carregar, nesse exemplo PlayState que não criamos ainda.</p>
<p>E importante notar que nós herdamos no código a classe FlxGame, através desse herança podemos adquirir métodos e atributos da game engine Flixel.</p>
<p>Agora precisamos dizer para o FlashDevelop sempre compilar essa classe que acabamos de criar, clique com o botão direito do mouse sobre a classe &#8220;<strong>HelloWorld.as</strong>&#8221; e clique na opção &#8220;<strong>Always Compile</strong>&#8220;.</p>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/always_compile.png"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/06/always_compile.png" alt="" title="always_compile" width="318" height="390" class="aligncenter size-full wp-image-1252" /></a></p>
<h3>PlayState.as</h3>
<p>Crie uma nova classe no diretório <strong>src</strong> chamada <strong>PlayState</strong>.</p>
<p>Altere o seu código para ficar da seguinte forma:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span>  
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// Importa a game engine Flixel</span>
	<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.flixel.*</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Classe inicial do jogo</span>
	<span style="color: #666666; font-style: italic;">// herda de FlxState</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PlayState <span style="color: #000000; font-weight: bold;">extends</span> FlxState
	<span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// Método do Flixel</span>
		<span style="color: #666666; font-style: italic;">// usado para criar os elementos do jogo</span>
		override <span style="color: #000000; font-weight: bold;">public</span> function create<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #666666; font-style: italic;">// Criação do texto com o Hello World!</span>
			var t1<span style="color: #339933;">:</span>FlxText <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> FlxText<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, FlxG.<span style="color: #006633;">width</span>, <span style="color: #0000ff;">&quot;Hello World!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			t1.<span style="color: #006633;">alignment</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;center&quot;</span><span style="color: #339933;">;</span>
			t1.<span style="color: #006633;">size</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">48</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #666666; font-style: italic;">// Adiciona o texto na tela</span>
			add<span style="color: #009900;">&#40;</span>t1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A classe PlayState representa o estado de jogo do Flixel, a game engine possui uma máquina de estados, você pode ter vários estados, por exemplo: menu, créditos, primeira fase, segunda fase, game over e vitória. O Flixel já possui alguns métodos para realizar facilmente essa transição de estados.</p>
<p>Nessa classe nós herdamos de FlxState que possui vários métodos e atributos para lidar com estados do jogo, através do método create é criado os elementos do jogo, nesse exemplo simples apenas um texto com &#8220;Hello World!&#8221;.</p>
<p>Você pode pressionar a tecla <strong>F5</strong> para testar, caso você tenha o <strong><a href="http://www.adobe.com/support/flashplayer/downloads.html">Flash Debugger</a></strong> instalado ele já vai abrir a tela com o jogo, caso contrário você terá que ir na pasta <strong>bin</strong> e abrir o arquinvo <strong>index.html</strong> no navegador.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/06/09/criando-um-hello-world-usando-a-game-engine-flixel/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Minha Contribuição para o MongoDB</title>
		<link>http://blog.patrickespake.com/2010/06/04/minha-contribuicao-para-o-mongodb/</link>
		<comments>http://blog.patrickespake.com/2010/06/04/minha-contribuicao-para-o-mongodb/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 19:29:08 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[10gen]]></category>
		<category><![CDATA[contribuição]]></category>
		<category><![CDATA[documentação]]></category>
		<category><![CDATA[query browser]]></category>
		<category><![CDATA[tradução]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1220</guid>
		<description><![CDATA[Essa semana eu fui procurado pelo pessoal da 10gen, Meghan Gill e Alberto Lerner, para contribuir no projeto do MongoDB. A 10gen é a empresa responsável pelo MongoDB. Inicialmente eu espero ajudar na tradução da documentação do MongoDB para o português, com esse trabalho eu espero ajudar muitos desenvolvedores brasileiros, principalmente aqueles que tem alguma [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/06/logo-mongoDB1.png"><img class="aligncenter size-full wp-image-1222" title="logo-mongoDB" src="http://blog.patrickespake.com/wp-content/uploads/2010/06/logo-mongoDB1.png" alt="" width="217" height="90" /></a></p>
<p>Essa semana eu fui procurado pelo pessoal da <a href="http://www.10gen.com/index" target="_blank">10gen</a>, <a href="http://www.10gen.com/team" target="_blank">Meghan Gill</a> e <a href="http://alerner.org/" target="_blank">Alberto Lerner</a>, para contribuir no projeto do <a href="http://www.mongodb.org/" target="_blank">MongoDB</a>. A 10gen é a empresa responsável pelo MongoDB.</p>
<p>Inicialmente eu espero ajudar na tradução da documentação do MongoDB para o português, com esse trabalho eu espero ajudar muitos desenvolvedores brasileiros, principalmente aqueles que tem alguma dificuldade no idioma inglês.</p>
<p>Futuramente eu espero ajudar no desenvolvimento de ferramentas para o MongoDB, principalmente em ferramentas de monitoramento e Query Browser, que é uma das coisas que eu sinto falta no momento.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/06/04/minha-contribuicao-para-o-mongodb/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Google&#8217;s Pacman Doodle &#8211; Engenharia Reversa</title>
		<link>http://blog.patrickespake.com/2010/05/21/googles-pacman-doodle-engenharia-reversa/</link>
		<comments>http://blog.patrickespake.com/2010/05/21/googles-pacman-doodle-engenharia-reversa/#comments</comments>
		<pubDate>Fri, 21 May 2010 23:34:42 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Algoritmo]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Game]]></category>
		<category><![CDATA[Jogo]]></category>
		<category><![CDATA[Web 2.0]]></category>
		<category><![CDATA[doodle]]></category>
		<category><![CDATA[engenharia reversa]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[pac man 30th birthday]]></category>
		<category><![CDATA[PAC-MAN 30th Anniversary]]></category>
		<category><![CDATA[pacman]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1218</guid>
		<description><![CDATA[Na página do Google de hoje (21 de maio de 2010) tem um doodle do Pacman &#8211; e o mais interessante disso: é jogável! E é o primeiro doodle jogável do Google. Sendo um geek, eu decidi dar uma olhada no código-fonte para descobrir como o Google fez isso. Eu não fiz engenharia reversa do [...]]]></description>
			<content:encoded><![CDATA[<p>Na página do Google de hoje (21 de maio de 2010) tem um doodle do Pacman &#8211; e o mais interessante disso: é jogável! E é <a href="http://googleblog.blogspot.com/2010/05/celebrating-pac-mans-30th-birthday.html">o primeiro doodle jogável do Google</a>.</p>
<p>Sendo um geek, eu decidi dar uma olhada no código-fonte para descobrir como o Google fez isso.</p>
<p>Eu não fiz engenharia reversa do código inteiro, eu só queria ter uma ideia geral de como eles tinham feito isso. Parece-me que o Google, afinal, tem um código extramamente conciso e eficiente para resolver muitos dos seus problemas.</p>
<p>Assim, em primeiro lugar eles têm um elemento div que contém a área do jogo:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;div id=lga&gt;
  &lt;a href=&quot;/search?q=PAC-MAN+30th+Anniversary&amp;ct=pacman10-hp&amp;oi=ddle&quot; id=&quot;dlink&quot;&gt;
  &lt;/a&gt;
  &lt;div id=logo style=&quot;width:554px;height:186px;background:black url(logos/pacman10-hp.png) 0 0 no-repeat;position:relative;margin-bottom:9px&quot; title=&quot;PAC-MAN's 30th Birthday! Doodle with PAC-MAN™ &amp; ©1980 NAMCO BANDAI Games Inc.&quot;&gt;
    &lt;div id=&quot;logo-l&quot; style=&quot;width:200px;height:2px;left:177px;top:157px;background:#990;position:absolute;display:none;overflow:hidden&quot;&gt;
      &lt;div id=&quot;logo-b&quot; style=&quot;position:absolute;left:0;background:#ff0;height:8px;width:0&quot;&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  ...
&lt;/div&gt;</pre></div></div>

<p>E depois há o script mágico:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&lt;script&gt;
    google.pml = function() {
        function d(a) {
            if (!google.pml_installed) {
                google.pml_installed = true;
                if (!a) {
                    document.getElementById(&quot;logo&quot;).style.background = &quot;black&quot;;
                    window.setTimeout(function() {
                        var b = document.getElementById(&quot;logo-l&quot;);
                        if (b) b.style.display = &quot;block&quot;
                    }, 400)
                }
                a = document.createElement(&quot;script&quot;);
                a.type = &quot;text/javascript&quot;;
                a.src = &quot;logos/js/pacman10-hp.2.js&quot;;
                google.dom.append(a)
            }
        }
        function e() {
            if (document.f &amp;&amp; document.f.btnI) document.f.btnI.onclick = function() {
                typeof google.pacman != &quot;undefined&quot; ? google.pacman.insertCoin() : d(false);
                return false
            }
        }
        if (!google.pml_loaded) {
            google.pml_loaded = true;
            window.setTimeout(function() {
                document.f &amp;&amp; document.f.q &amp;&amp; document.f.q.value == &quot;&quot; &amp;&amp; d(true)
            }, 1E4);
            e();
            google.rein &amp;&amp; google.rein.push(e);
            google.dstr &amp;&amp; google.dstr.push(function() {
                google.pacman &amp;&amp; google.pacman.destroy();
                if (google.pml_installed) {
                    for (var a = (document.getElementById(&quot;xjsc&quot;) || document.body).getElementsByTagName(&quot;script&quot;), b = 0, c; c = a[b++];) c.src.indexOf(&quot;/logos/js&quot;) != -1 &amp;&amp; google.dom.remove(c);
                    google.pml_installed = false
                }
            });
            google.pacManQuery = function() {
                google.nav(document.getElementById(&quot;dlink&quot;).href)
            }
        }
    };
&lt;/script&gt;</pre></div></div>

<p>O que parece estar fazendo é o seguinte:</p>
<ul>
<li>Define o estilo CSS e propriedades para vários elementos HTML jogáveis;</li>
<li>Carrega o código Javascript do Pacman: <a href="http://www.google.com/logos/js/pacman10-hp.2.js">http://www.google.com/logos/js/pacman10-hp.2.js</a> (nota: esse link era válido quando eu carreguei isso em 21 de maio de 2010, o dia do doodle, mas pode ser removido mais tarde. Depende do Google, e eu não quero guardar uma cópia offline por razões legais e outros.);</li>
<li>Quando o jogo é terminado, redireciona para o link do elemento a id=&#8221;dlink&#8221;, e basicamente procura pela frase &#8220;PAC-MAN 30th Anniversary&#8221;;</li>
<li>Responde ao botão &#8220;Insert Coin&#8221; quando é pressionado e reinicia o jogo.</li>
</ul>
<p>No estilo Google: realmente puro e eficiente!</p>
<p>Eu usei dois recursos online para formatar o HTML e Javascript do Google melhor:</p>
<ul>
<li><a href="http://www.mycoolform.com/">Cool HTML formatter</a></li>
<li><a href="http://jsbeautifier.org/">Online Javascript beautifier</a></li>
</ul>
<p><em>Esse post é uma tradução do post: <a href="http://sumanrs.wordpress.com/2010/05/21/googles-pacman-doodle-reverse-engineering-101/">http://sumanrs.wordpress.com/2010/05/21/googles-pacman-doodle-reverse-engineering-101/</a> </em></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/05/21/googles-pacman-doodle-engenharia-reversa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Minha opinião na revista TIdigital sobre CouchDB vs. MongoDB</title>
		<link>http://blog.patrickespake.com/2010/05/21/minha-opiniao-na-revista-tidigital-sobre-couchdb-vs-mongodb/</link>
		<comments>http://blog.patrickespake.com/2010/05/21/minha-opiniao-na-revista-tidigital-sobre-couchdb-vs-mongodb/#comments</comments>
		<pubDate>Fri, 21 May 2010 18:31:46 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[couchdb]]></category>
		<category><![CDATA[minha]]></category>
		<category><![CDATA[opinião]]></category>
		<category><![CDATA[revista]]></category>
		<category><![CDATA[TIdigital]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1214</guid>
		<description><![CDATA[Na edição de Maio de 2010 da Revista TIdigital, saiu uma matéria sobre CouchDB vs. MongoDB, com entrevista com os criadores e opiniões a respeito de ambos banco de dados NoSQL, uma das opiniões dessa matéria é a minha. Vale a pena conferir!]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><a href="http://blog.patrickespake.com/wp-content/uploads/2010/05/capa_15_maior.jpg"><img class="aligncenter size-full wp-image-1215" title="capa_15_maior" src="http://blog.patrickespake.com/wp-content/uploads/2010/05/capa_15_maior.jpg" alt="" width="420" height="567" /></a></p>
<p style="text-align: left;">Na edição de Maio de 2010 da Revista <a href="http://www.revistatidigital.com.br/">TIdigital</a>, saiu uma matéria sobre CouchDB vs. MongoDB, com entrevista com os criadores e opiniões a respeito de ambos banco de dados NoSQL, uma das opiniões dessa matéria é a minha.</p>
<p style="text-align: left;">Vale a pena conferir!</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/05/21/minha-opiniao-na-revista-tidigital-sobre-couchdb-vs-mongodb/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Future Of Work</title>
		<link>http://blog.patrickespake.com/2010/05/20/the-future-of-work/</link>
		<comments>http://blog.patrickespake.com/2010/05/20/the-future-of-work/#comments</comments>
		<pubDate>Thu, 20 May 2010 12:18:49 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Reflexões]]></category>
		<category><![CDATA[WEB]]></category>
		<category><![CDATA[The Future Of Work]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1211</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/G8Yt4wxSblc&#038;hl=pt_BR&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/G8Yt4wxSblc&#038;hl=pt_BR&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/05/20/the-future-of-work/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Desempenho Ruby: Windows vs Linux</title>
		<link>http://blog.patrickespake.com/2010/05/12/desempenho-ruby-windows-vs-linux/</link>
		<comments>http://blog.patrickespake.com/2010/05/12/desempenho-ruby-windows-vs-linux/#comments</comments>
		<pubDate>Wed, 12 May 2010 22:45:30 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Desempenho]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[environment]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1204</guid>
		<description><![CDATA[Há um tempo atrás eu configurei todo o meu ambiente para desenvolver no Windows, com o objetivo de conseguir testar a aplicação em todos os browsers. Infelizmente o Ruby no Windows é muito mais lento que no Linux, chega ao ponto de ser inviável o uso do ambiente Windows. O que é uma pena, como [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/05/linuxxwindows.jpg"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/05/linuxxwindows.jpg" alt="" title="linuxxwindows" width="531" height="485" class="aligncenter size-full wp-image-1208" /></a></p>
<p>Há um tempo atrás eu configurei todo o meu ambiente para desenvolver no Windows, com o objetivo de conseguir testar a aplicação em todos os browsers.</p>
<p>Infelizmente o Ruby no Windows é muito mais lento que no Linux, chega ao ponto de ser inviável o uso do ambiente Windows. O que é uma pena, como linguagem de programação deveria ter desempenho parecido independente do sistema operacional.</p>
<p>Eu comecei a perceber essa lentidão no carregamento do environment.</p>
<p>Todo esse problema de environment lento era única e exclusivamente pela baixo desempenho do Ruby no Windows.</p>
<p>O <a href="http://julio.monteiro.eti.br/">Julio Monteiro</a> sugeriu eu fazer o seguinte teste no prompt/terminal:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">date
ruby script<span style="color:#006600; font-weight:bold;">/</span>console
<span style="color:#CC0066; font-weight:bold;">exit</span>
date</pre></div></div>

<p>No Windows o environment demorou: <strong>3 minutos e 50 segundos</strong> para subir.<br />
No Linux o environment demorou: <strong>13 segundos</strong> para subir.</p>
<p>É uma diferença de desempenho absurda entre o Windows e o Linux.<br />
Levando em conta o teste com a mesma aplicação usando:</p>
<ul>
<li>Ruby 1.8.7;</li>
<li>Rails 2.3.5;</li>
<li>MongoDB</li>
</ul>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/05/12/desempenho-ruby-windows-vs-linux/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Notícias relacionadas ao jogo Galaxis Farm</title>
		<link>http://blog.patrickespake.com/2010/05/11/noticias-relacionadas-ao-jogo-galaxis-farm/</link>
		<comments>http://blog.patrickespake.com/2010/05/11/noticias-relacionadas-ao-jogo-galaxis-farm/#comments</comments>
		<pubDate>Tue, 11 May 2010 21:09:20 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flixel]]></category>
		<category><![CDATA[Game]]></category>
		<category><![CDATA[PIBIC]]></category>
		<category><![CDATA[Projetos]]></category>
		<category><![CDATA[code google]]></category>
		<category><![CDATA[código fonte]]></category>
		<category><![CDATA[Galaxis Dream]]></category>
		<category><![CDATA[galaxis farm]]></category>
		<category><![CDATA[notícias]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[tecpar]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1183</guid>
		<description><![CDATA[Através da minha bolsa de iniciação científica no TECPAR, eu pude aprender muita coisa desde o ano passado até agora. Vários novos conhecimentos foram adquiridos principalmente na área de desenvolvimento de jogos, inteligência artificial aplicada a jogos e a web. Um dois primeiros frutos do meu trabalho foi o Jogo Galaxis Farm, onde eu fui [...]]]></description>
			<content:encoded><![CDATA[<p>Através da minha bolsa de iniciação científica no <a href="http://www.tecpar.br">TECPAR</a>, eu pude aprender muita coisa desde o ano passado até agora. Vários novos conhecimentos foram adquiridos principalmente na área de desenvolvimento de jogos, inteligência artificial aplicada a jogos e a web.</p>
<p>Um dois primeiros frutos do meu trabalho foi o <a href="http://www.galaxisfarm.com">Jogo Galaxis Farm</a>, onde eu fui responsável pela programação do jogo, atualmente o jogo está disponibilizado no endereço <a href="http://www.galaxisfarm.com">http://www.galaxisfarm.com</a>.</p>
<p>Eu fico muito contente pela recupersão na mídia do jogo:</p>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/05/logo_pronline.gif"><img class="aligncenter size-full wp-image-1184" title="logo_pronline" src="http://blog.patrickespake.com/wp-content/uploads/2010/05/logo_pronline.gif" alt="" width="235" height="33" /></a>09/05/2010 &#8211; <strong>Pirataria é inimiga dos produtores de games &#8211; </strong><a onclick="javascript:pageTracker._trackPageview('/outbound/article/www.parana-online.com.br');" href="http://www.parana-online.com.br/canal/tecnologia/news/445889/?noticia=PIRATARIA+E+INIMIGA+DOS+PRODUTORES+DE+GAMES">http://www.parana-online.com.br/canal/tecnologia/news/445889/?noticia=PIRATARIA+E+INIMIGA+DOS+PRODUTORES+DE+GAMES</a></p>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/05/diario_online.jpg"><img class="aligncenter size-full wp-image-1185" title="diario_online" src="http://blog.patrickespake.com/wp-content/uploads/2010/05/diario_online.jpg" alt="" width="142" height="65" /></a>29/04/2010 &#8211; <strong>Jogo para entender o funcionamento de uma fazenda leiteira &#8211; </strong><a onclick="javascript:pageTracker._trackPageview('/outbound/article/www.odiariomaringa.com.br');" href="http://www.odiariomaringa.com.br/noticia/241672">http://www.odiariomaringa.com.br/noticia/241672</a></p>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/05/agencia_noticias_pr.jpg"><img class="aligncenter size-full wp-image-1186" title="agencia_noticias_pr" src="http://blog.patrickespake.com/wp-content/uploads/2010/05/agencia_noticias_pr.jpg" alt="" width="316" height="59" /></a>28/04/2010 &#8211; <strong>Jogo eletrônico ajuda a entender funcionamento de fazenda  leiteira &#8211; </strong><a onclick="javascript:pageTracker._trackPageview('/outbound/article/www.aen.pr.gov.br');" href="http://www.aen.pr.gov.br/modules/noticias/article.php?storyid=56025&amp;tit=Jogo-eletronico-ajuda-a-entender-funcionamento-de-fazenda-leiteira&amp;ordem=170000">http://www.aen.pr.gov.br/modules/noticias/article.php?storyid=56025&amp;tit=Jogo-eletronico-ajuda-a-entender-funcionamento-de-fazenda-leiteira&amp;ordem=170000</a></p>
<p>Ainda não temos definido qual será o futuro do Jogo Galaxis Farm, por enquanto ele está na versão beta. Nas últimas semanas nós começamos a trabalhar no próximo jogo o Galaxis Dream, que tem o objetivo da difusão das boas práticas agropecuárias. Provavelmente no futuro irei escrever mais sobre o jogo Galaxis Dream.</p>
<p>Assim como o <a href="http://code.google.com/p/galaxisfarm/">Galaxis Farm</a>, o Galaxis Dream também tem o seu código fonte open source no endereço: <a href="http://code.google.com/p/galaxisdream/">http://code.google.com/p/galaxisdream/</a></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/05/11/noticias-relacionadas-ao-jogo-galaxis-farm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Construção de um Agente Inteligente que Jogue Mario</title>
		<link>http://blog.patrickespake.com/2010/05/10/construcao-de-um-agente-inteligente-que-jogue-mario/</link>
		<comments>http://blog.patrickespake.com/2010/05/10/construcao-de-um-agente-inteligente-que-jogue-mario/#comments</comments>
		<pubDate>Mon, 10 May 2010 20:54:22 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Algoritmo]]></category>
		<category><![CDATA[Game]]></category>
		<category><![CDATA[Inteligência Artificial]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Jogo]]></category>
		<category><![CDATA[Rede Neural]]></category>
		<category><![CDATA[agente inteligente]]></category>
		<category><![CDATA[construção]]></category>
		<category><![CDATA[jogador]]></category>
		<category><![CDATA[Mario]]></category>
		<category><![CDATA[Redes Neurais]]></category>
		<category><![CDATA[técnica]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1168</guid>
		<description><![CDATA[Com esse post você vai obter o resultado abaixo: Nas últimas semanas eu veio estudando a fundo a técnica de inteligência artificial de redes neurais. Não é toa que praticamente os meus dois últimos posts foram sobre esse assunto. Tudo começou com a ideia de criar um agente inteligente que conseguisse jogar Mario sozinho, a [...]]]></description>
			<content:encoded><![CDATA[<p>Com esse post você vai obter o resultado abaixo:</p>
<p><center><object height="338" width="393" codebase="http://active.macromedia.com/flash5/cabs/swflash.cab#version=7,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="http://blog.patrickespake.com/wp-content/uploads/2010/05/MarioNeuralNetworkAgent.swf" name="movie"><param value="true" name="play"><param value="false" name="loop"><param value="transparent" name="wmode"><param value="low" name="quality"><embed height="338" width="393" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" wmode="transparent" loop="false" quality="low" src="http://blog.patrickespake.com/wp-content/uploads/2010/05/MarioNeuralNetworkAgent.swf"><br />
</object></center></p>
<p>Nas últimas semanas eu veio estudando a fundo a técnica de inteligência artificial de redes neurais. Não é toa que praticamente os meus dois últimos posts foram sobre esse assunto.</p>
<p>Tudo começou com a ideia de criar um agente inteligente que conseguisse jogar Mario sozinho, a minha pretensão nunca foi muito grande, eu apenas tinha a ideia de fazer algo simples que funcionasse, mas não tinha a grande pretensão de fazer um super agente inteligente capaz de passar por vários níveis diferentes de dificuldade do jogo Mario. Partindo disso, com o único objetivo de aprendizado, eu decidi usar a técnica de redes neurais e fazer o Mario passar pela primeira fase.</p>
<p>Para simplificar mais ainda, eu fiz por padrão o Mario andar para a direita e a única ação que é aplicada inteligência artificial é a decisão se o Mario deve ou não pular.</p>
<p>O código do jogo Mario eu obtive do site: <a href="http://www.marioai.org/gameplay-track/getting-started">http://www.marioai.org/gameplay-track/getting-started</a>, esse é o site da competição que tem o foco na criação de agentes inteligentes e criação de fases para o Mario, usando inteligência artificial. Eles não disponibilizam o código da parte de inteligência artificial, cabe a cada participante implementar o seu algoritmo e enviar para a competição, o melhor agente inteligente vence. Eu também não tinha a ideia de vencer essa competição, não tenho nível e conhecimento suficiente para isso ainda.</p>
<p>Antes de entrarmos em código e implementação, é importante entender do que consiste a técnica de redes neurais.</p>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/05/neuronio.jpg"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/05/neuronio.jpg" alt="" title="neuronio" width="323" height="218" class="aligncenter size-full wp-image-1173" /></a></p>
<p>De forma resumida, uma rede neural é constituída por um neurônio (perceptron), que possui a seguinte estrutra:</p>
<ul>
<li>Dendritos;</li>
<li>Corpo celular;</li>
<li>Axônio.</li>
</ul>
<p>O dendrito(s) corresponde(m) as entradas (inputs) do neurônio, o corpo celular é responsável pelo processamento e o axônio representa a saída (output).</p>
<p>O algoritmo de uma rede neural se resume em:</p>
<ul>
<li>Os dendritos recebem um valor de entrada cada um, esse valor é multiplicado por um peso, uma soma ponderada na verdade;</li>
<li>O neurônio, corpo celular, recebe a soma ponderada e através de uma verificação matemática, decide o valor de saída para o neurônio. Isso é conhecido por função de ativação, que em muitas vezes se resume em um if que testa se a soma é maior ou menor que zero;</li>
<li>O axônio transmite essa saída</li>
</ul>
<p>Você pode pensar &#8220;Hum muito bem, onde está a inteligência artificial nisso?&#8221;, a inteligência artificial está no próximo passo do algoritmo, o neurônio deve ser treinado, ele deve receber um conjunto de valores de entrada para os dendritos e a saída válida, saída conhecida para esse conjunto de entradas. Com posse disso o neurônio é treinado, e o grande segredo de uma rede neural é o ajuste dos pesos que são multiplicados pelas entradas no dendritos, nessa parte que consta a inteligência artificial. O grande foco e obter os pesos ideias para que a rede neural se comporte da melhor forma, depois de encontrar esses pesos basta em usá-los sempre.</p>
<p>Na verdade tudo é matemática.</p>
<p>Agora que está claro como tudo acontece vamos ver a implementação. Vamos começar pelas estruturas de dados mais básicas e avançamos para as mais complexas.</p>
<h2>Dendrito</h2>
<p><strong>Dendrite.java</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.pucpr.neuralnetwork</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Classe que representa um dendrito</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Dendrite <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// Valor para o dendrito</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> value<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Método construtor</span>
	<span style="color: #666666; font-style: italic;">// aceita como parâmetro:</span>
	<span style="color: #666666; font-style: italic;">// * value = valor para o dendrito</span>
	<span style="color: #000000; font-weight: bold;">public</span> Dendrite<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> value<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">value</span> <span style="color: #339933;">=</span> value<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Obtém o valor atual do dendrito</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> getValue<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> value<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Axônio</h2>
<p><strong>Axon.java</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.pucpr.neuralnetwork</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Classe que representa um axônio</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Axon <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// Sinal de saída</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> sign<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Obtém o sinal do axônio</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> getSign<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> sign<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Define o sinal para o axônio</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setSign<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> sign<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">sign</span> <span style="color: #339933;">=</span> sign<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Transforma o sinal em um valor booleano</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> signToBoolean<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>sign <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Neurônio</h2>
<p><strong>Neuron.java</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.pucpr.neuralnetwork</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Classe que representa um neurônio</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Neuron <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// Dendritos</span>
	<span style="color: #000000; font-weight: bold;">private</span> Dendrite<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> dendrites<span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// Axônio</span>
	<span style="color: #000000; font-weight: bold;">private</span> Axon axon<span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// Pesos</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">float</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> weights<span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// Pesos padrões</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">float</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> defaultWeights<span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// Tipo da função de ativação</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> activationType<span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// Constante de aprendizado</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">float</span> constantLearning<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Método construtor</span>
	<span style="color: #666666; font-style: italic;">// aceita como pârametros:</span>
	<span style="color: #666666; font-style: italic;">// * numberDendrites = Número de dendritos</span>
	<span style="color: #666666; font-style: italic;">// * defaultWeights = Pesos padrão</span>
	<span style="color: #666666; font-style: italic;">// * activationType = tipo da função de ativação</span>
	<span style="color: #000000; font-weight: bold;">public</span> Neuron<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> numberDendrites, <span style="color: #000066; font-weight: bold;">float</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> defaultWeights, <span style="color: #003399;">String</span> activationType<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// Define os pesos padrões</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">defaultWeights</span> <span style="color: #339933;">=</span> defaultWeights<span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Se não for definida o tipo da função de ativação,</span>
		<span style="color: #666666; font-style: italic;">// então define como sign</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>activationType <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">activationType</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;sign&quot;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Pesos</span>
		weights <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">float</span><span style="color: #009900;">&#91;</span>numberDendrites<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">// Dendritos</span>
		dendrites <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Dendrite<span style="color: #009900;">&#91;</span>numberDendrites<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Cria valores iniciais randômicos para os pesos</span>
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> weights.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			weights<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #003399;">Util</span>.<span style="color: #006633;">random</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Constante de aprendizado</span>
		constantLearning <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span><span style="color: #009900;">&#41;</span><span style="color: #cc66cc;">0.0001</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">// Axônio</span>
		axon <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Axon<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Soma os dendritos com os seus pesos</span>
	<span style="color: #666666; font-style: italic;">// média ponderada</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">float</span> sumDendrites<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">float</span> sum <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>defaultWeights <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">&amp;&amp;</span> defaultWeights.<span style="color: #006633;">length</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> defaultWeights.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				weights<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> defaultWeights<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> weights.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			sum <span style="color: #339933;">+=</span> dendrites<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #006633;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> weights<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> sum<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Método de ativação</span>
	<span style="color: #666666; font-style: italic;">// dependendo da soma e do tipo de ativação</span>
	<span style="color: #666666; font-style: italic;">// envia o sinal -1 ou 1 para o axônio</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> activation<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">float</span> sum <span style="color: #339933;">=</span> sumDendrites<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		axon.<span style="color: #006633;">setSign</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>sum <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			axon.<span style="color: #006633;">setSign</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Treina o neurônio, afim de obter os melhores pesos para os dendritos</span>
	<span style="color: #666666; font-style: italic;">// aceita como parâmetros:</span>
	<span style="color: #666666; font-style: italic;">// * numberTimes = número de épocas</span>
	<span style="color: #666666; font-style: italic;">// * percentageCorrect = percentual correto para o treinamento ser considerado bem sucedido</span>
	<span style="color: #666666; font-style: italic;">// * examplesTraining = exemplos para o treinamento</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> train<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> numberTimes, <span style="color: #000066; font-weight: bold;">int</span> percentageCorrect, <span style="color: #003399;">Point</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> examplesTraining<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Treinamento iniciado...&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Quantidade de treinamento verificado</span>
		<span style="color: #000066; font-weight: bold;">int</span> totalVerified <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">// Quantidade de treinamento verificado errado</span>
		<span style="color: #000066; font-weight: bold;">int</span> totalVerifiedWrong <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">// Quantidade de treinamento verificado correto</span>
		<span style="color: #000066; font-weight: bold;">int</span> totalVerifiedCorrect <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Repete até o número de épocas ser satisfeito</span>
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> numberTimes<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #666666; font-style: italic;">// Percorre todos os exemplos de treinamento</span>
			<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> examplesTraining.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #666666; font-style: italic;">// Obtém a saída adivinhada pelo neurônio</span>
				<span style="color: #000066; font-weight: bold;">int</span> result <span style="color: #339933;">=</span> guess<span style="color: #009900;">&#40;</span>examplesTraining<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #666666; font-style: italic;">// Calcula o fator de mudança do peso baseado no erro</span>
				<span style="color: #666666; font-style: italic;">// erro = saída desejada - saída adivinhada</span>
				<span style="color: #666666; font-style: italic;">// multiplica pela constante de aprendizado</span>
				<span style="color: #000066; font-weight: bold;">float</span> weightChange <span style="color: #339933;">=</span> constantLearning <span style="color: #339933;">*</span> <span style="color: #009900;">&#40;</span>examplesTraining<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span>.<span style="color: #006633;">getOutput</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> result<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #666666; font-style: italic;">// Ajusta os pesos baseado no fator de mudança * a entrada</span>
				<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> k <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> k <span style="color: #339933;">&lt;</span> weights.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> k<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
					weights<span style="color: #009900;">&#91;</span>k<span style="color: #009900;">&#93;</span> <span style="color: #339933;">+=</span> weightChange <span style="color: #339933;">*</span> examplesTraining<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span>.<span style="color: #006633;">getVals</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>k<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
				<span style="color: #009900;">&#125;</span>
&nbsp;
				<span style="color: #666666; font-style: italic;">// Contabiliza se o valor adivinhado foi correto ou não</span>
				<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>result <span style="color: #339933;">==</span> examplesTraining<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span>.<span style="color: #006633;">getOutput</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
					totalVerifiedCorrect<span style="color: #339933;">++;</span>
				<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
					totalVerifiedWrong<span style="color: #339933;">++;</span>
				<span style="color: #009900;">&#125;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Quantidade de treinamentos verificados</span>
		totalVerified <span style="color: #339933;">=</span> totalVerifiedWrong <span style="color: #339933;">+</span> totalVerifiedCorrect<span style="color: #339933;">;</span>
		<span style="color: #000066; font-weight: bold;">float</span> totalPercentageCorrect <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">100</span> <span style="color: #339933;">*</span> totalVerifiedCorrect <span style="color: #009900;">&#41;</span> <span style="color: #339933;">/</span> totalVerified<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Treinamento terminado...&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Resultados obtidos:&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot; - Número de épocas executadas: &quot;</span> <span style="color: #339933;">+</span> numberTimes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #003399;">String</span> indicativeSuccess <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;bem sucedido&quot;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>totalPercentageCorrect <span style="color: #339933;">&lt;</span> percentageCorrect<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			indicativeSuccess <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;mal sucedido&quot;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot; - Indicativo de sucesso: Treinamento &quot;</span> <span style="color: #339933;">+</span> indicativeSuccess<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot; - Porcentagem correto: &quot;</span> <span style="color: #339933;">+</span> totalPercentageCorrect<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot; - Pesos:&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>defaultWeights <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">&amp;&amp;</span> defaultWeights.<span style="color: #006633;">length</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> defaultWeights.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				weights<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> defaultWeights<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> weights.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;   - Peso &quot;</span> <span style="color: #339933;">+</span> i <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;: &quot;</span> <span style="color: #339933;">+</span> weights<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Método que adivinha a saída esperada</span>
	<span style="color: #666666; font-style: italic;">// baseada nas entradas, de acordo com os pesos</span>
	<span style="color: #666666; font-style: italic;">// calculados</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> guess<span style="color: #009900;">&#40;</span><span style="color: #003399;">Point</span> point<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// Define os valores para os dendritos</span>
		setDendrites<span style="color: #009900;">&#40;</span>point.<span style="color: #006633;">getVals</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">// Faz a ativação</span>
		activation<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">// Sinal de ativação</span>
		<span style="color: #000000; font-weight: bold;">return</span> axon.<span style="color: #006633;">getSign</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Define os valores para os dendritos</span>
	<span style="color: #666666; font-style: italic;">// de acordo com um array de valores</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setDendrites<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> vals<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> vals.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			dendrites<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Dendrite<span style="color: #009900;">&#40;</span>vals<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Obtém a constante de aprendizado</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">float</span> getConstantLearning<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> constantLearning<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Define uma nova constante de aprendizado</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setConstantLearning<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> constantLearning<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">constantLearning</span> <span style="color: #339933;">=</span> constantLearning<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Obtém o axônio</span>
	<span style="color: #000000; font-weight: bold;">public</span> Axon getAxon<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> axon<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Obtém o tipo da função de ativação usada</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getActivationType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> activationType<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Ponto</h2>
<p><strong>Point.java</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">br.pucpr.neuralnetwork</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Classe que representa um ponto de treinamento</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> <span style="color: #003399;">Point</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// Valores de entrada</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> vals<span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// Saída esperada</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> output<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Método construtor</span>
	<span style="color: #666666; font-style: italic;">// aceita os parâmetros:</span>
	<span style="color: #666666; font-style: italic;">// * obs1 = tipo de obstáculo na posição 1</span>
	<span style="color: #666666; font-style: italic;">// * obs2 = tipo de obstáculo na posição 2</span>
	<span style="color: #666666; font-style: italic;">// * output = saída esperada</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> obs1, <span style="color: #000066; font-weight: bold;">int</span> obs2, <span style="color: #000066; font-weight: bold;">int</span> output<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		vals <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">3</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		vals<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> obs1<span style="color: #339933;">;</span>
		vals<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> obs2<span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">// Bias para quando as entradas forem zero</span>
		vals<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">output</span> <span style="color: #339933;">=</span> output<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Valores de entrada</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> getVals<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> vals<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Saída esperada</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> getOutput<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> output<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>	
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Agente Inteligente</h2>
<p><strong>NeuralNetworkAgent.java</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">ch.idsia.ai.agents.controllers</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.pucpr.neuralnetwork.Neuron</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">br.pucpr.neuralnetwork.Point</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">ch.idsia.ai.agents.Agent</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">ch.idsia.mario.engine.sprites.Mario</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">ch.idsia.mario.environments.Environment</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Classe que representa um agente inteligente que utiliza rede neural</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> NeuralNetworkAgent <span style="color: #000000; font-weight: bold;">extends</span> BasicAIAgent <span style="color: #000000; font-weight: bold;">implements</span> Agent <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Neurônio</span>
	<span style="color: #000000; font-weight: bold;">private</span> Neuron neuron<span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// Pontos para treinamento</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> examplesTraining<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> NeuralNetworkAgent<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;NeuralNetworkAgent&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Instância um neurônio</span>
		<span style="color: #666666; font-style: italic;">// Com 3 dendritos, obstáculo 1, obstáculo 2 e </span>
		<span style="color: #666666; font-style: italic;">// bias para quando as primeiras entradas forem zero</span>
		neuron <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Neuron<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">3</span>, <span style="color: #000066; font-weight: bold;">null</span>, <span style="color: #0000ff;">&quot;sign&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Com pesos padrões</span>
		<span style="color: #666666; font-style: italic;">// float[] defaultWeights = new float[3];</span>
		<span style="color: #666666; font-style: italic;">// defaultWeights[0] = (float)0.12533271;</span>
		<span style="color: #666666; font-style: italic;">// defaultWeights[1] = (float)-0.15752053;</span>
		<span style="color: #666666; font-style: italic;">// defaultWeights[2] = (float)-0.22475332;</span>
		<span style="color: #666666; font-style: italic;">// neuron = new Neuron(3, defaultWeights, &quot;sign&quot;);</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Cria os pontos para o treinamento</span>
		setExamplesTraining<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Realiza o treinamento</span>
		neuron.<span style="color: #006633;">train</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">300</span>, <span style="color: #cc66cc;">43</span>, examplesTraining<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		reset<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> reset<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		action <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">boolean</span><span style="color: #009900;">&#91;</span><span style="color: #003399;">Environment</span>.<span style="color: #006633;">numberOfButtons</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		action<span style="color: #009900;">&#91;</span>Mario.<span style="color: #006633;">KEY_RIGHT</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> getAction<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// Através dos pesos calculados no treinamento</span>
		<span style="color: #666666; font-style: italic;">// tenta jogar Mario sozinho</span>
		<span style="color: #666666; font-style: italic;">// Define o valor para os dendritos baseado nos obstáculos do jogo</span>
		<span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> vals <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		vals<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> mergedObservation<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">11</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">13</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		vals<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> mergedObservation<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">11</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">12</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		neuron.<span style="color: #006633;">setDendrites</span><span style="color: #009900;">&#40;</span>vals<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// Realiza ativação do neurônio, afim de obter o sinal de saída</span>
		neuron.<span style="color: #006633;">activation</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// De acordo com o neurônio faz o Mario pular ou não</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>neuron.<span style="color: #006633;">getAxon</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">signToBoolean</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>isMarioAbleToJump<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				action<span style="color: #009900;">&#91;</span>Mario.<span style="color: #006633;">KEY_JUMP</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>	
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
			action<span style="color: #009900;">&#91;</span>Mario.<span style="color: #006633;">KEY_JUMP</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> action<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Cria os pontos para o treinamento</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setExamplesTraining<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		examplesTraining <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">6</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		examplesTraining<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		examplesTraining<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		examplesTraining<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">20</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		examplesTraining<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">3</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span>, <span style="color: #339933;">-</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		examplesTraining<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">4</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		examplesTraining<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Point</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">11</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Main</h2>
<p><strong>Main.java</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">ch.idsia.scenarios</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">ch.idsia.ai.agents.Agent</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">ch.idsia.ai.agents.controllers.NeuralNetworkAgent</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">ch.idsia.maibe.tasks.BasicTask</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">ch.idsia.mario.environments.Environment</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">ch.idsia.mario.environments.MarioEnvironment</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">ch.idsia.tools.CmdLineOptions</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Created by IntelliJ IDEA. User: Sergey Karakovskiy, sergey at idsia dot ch Date: Mar 17, 2010 Time: 8:28:00 AM
 * Package: ch.idsia.scenarios
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Main
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
    	<span style="color: #666666; font-style: italic;">// final String argsString = &quot;-vis on&quot;;</span>
    	<span style="color: #666666; font-style: italic;">// args = argsString.split(&quot;\\s&quot;);</span>
        <span style="color: #000000; font-weight: bold;">final</span> CmdLineOptions cmdLineOptions <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> CmdLineOptions<span style="color: #009900;">&#40;</span>args<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">Environment</span> environment <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MarioEnvironment<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// final Agent agent = new ForwardAgent();</span>
        <span style="color: #666666; font-style: italic;">// final Agent agent = cmdLineOptions.getAgent();</span>
        <span style="color: #000000; font-weight: bold;">final</span> Agent agent <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> NeuralNetworkAgent<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// final Agent a = AgentsPool.load(&quot;ch.idsia.controllers.agents.controllers.ForwardJumpingAgent&quot;);</span>
        <span style="color: #000000; font-weight: bold;">final</span> BasicTask basicTask <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> BasicTask<span style="color: #009900;">&#40;</span>environment, agent<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicTask.<span style="color: #006633;">reset</span><span style="color: #009900;">&#40;</span>cmdLineOptions<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        basicTask.<span style="color: #006633;">runOneEpisode</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;cmdLineOptions.getLevelLength() = &quot;</span> <span style="color: #339933;">+</span> cmdLineOptions.<span style="color: #006633;">getLevelLength</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>environment.<span style="color: #006633;">getEvaluationInfoAsString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">exit</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Vamos entender como as classes acima se juntam para implementar a rede neural, a classe <strong>NeuralNetworkAgent.java</strong> possui os exemplos de treinamento, esses exemplos foram captados quando eu estava realmente jogando, por isso que a saída é conhecida, é o que se espera que o Mario faça quando ele tiver obstáculos pela frente. Além dos exemplos essa classe define o comportamento inicial do Mario que é andar para direita, a classe também realiza o treinamento, e com posse dos pesos ela abre a tela do jogo e coloca o Mario para jogar sozinho com inteligência. No código incluído está para toda vez os pesos serem calculados, é possível passar pesos padrões para o neurônio, essa parte do código está comentada, se você descomentar já irá ver o Mario jogando com os melhores pesos que eu encontrei.</p>
<p>A classe <strong>Point.java</strong> descreve os pontos ou ponto de entrada, ela recebe a informação se existem obstáculos na posição 1 e na posição 2 e a saída que deve existir.</p>
<p>A classe <strong>Dendrite.java</strong> descreve um dendrito e o seu valor de entrada.</p>
<p>A classe <strong>Axon.java</strong> descreve o axônio do neurônio, o sinal de saída, que também é transformado em um valor booleano.</p>
<p>A classe <strong>Neuron.java</strong> por sua vez que realiza todo o trabalho, cálculo dos melhores pesos e o emprego da inteligência artificial. Poder conter vários dendritos (várias entradas), uma única saída, os pesos para cada entrada e a constante de aprendizado. Inicialmente os pesos são valores randômicos, ao entrar no treinamento, os melhores pesos tentam ser encontrados, não sempre isso acontece, vai depender da quantidade de exemplos de treinamento e a quantidade de épocas. As épocas são quantas vezes o algoritmo vai ser repetido para tentar encontrar os melhores pesos para a rede neural. A constante de aprendizado é usada para alterar os pesos e tentar achar o melhor peso, as referências bibliográficas afirmam que quanto menor a constante de aprendizado, mais vai demorar para encontrar os pesos, mas os pesos encontrados são melhores e mais úteis para o funcionamento da rede.</p>
<p>A classe <strong>Main.java</strong> que executa o jogo e coloca todas as classes para trabalhar afim de obter a rede neural.</p>
<p>É claro que para o Mario rodar, é necessário ter toda o código fonte do Mario, disponibilizado no endereço que eu mencionei no começo do texto. Os códigos apresentados são apenas um agente inteligente que foi embutido no jogo do Mario.</p>
<p>Eu não vou entrar em mais detalhes do algoritmo, com posse dessas informações e comentários você já deve ser capaz de entender tudo que está acontecendo.</p>
<p>O que eu escrevi nesse texto não representa a verdade absoluta, eu ainda estou estudando o assunto, por isso algumas coisas podem estar erradas ou podem ser feitas de uma forma muito melhor. Apenas quero ajudar e propagar o conhecimento.</p>
<p>O código fonte está disponível em: <a href="http://github.com/patrickespake/Mario-Neural-Network-Agent">http://github.com/patrickespake/Mario-Neural-Network-Agent</a></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/05/10/construcao-de-um-agente-inteligente-que-jogue-mario/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Redes Neurais</title>
		<link>http://blog.patrickespake.com/2010/04/23/redes-neurais/</link>
		<comments>http://blog.patrickespake.com/2010/04/23/redes-neurais/#comments</comments>
		<pubDate>Fri, 23 Apr 2010 23:30:12 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Algoritmo]]></category>
		<category><![CDATA[Inteligência Artificial]]></category>
		<category><![CDATA[Processing]]></category>
		<category><![CDATA[Rede Neural]]></category>
		<category><![CDATA[implementação]]></category>
		<category><![CDATA[multi-camada]]></category>
		<category><![CDATA[neurônio]]></category>
		<category><![CDATA[perceptron]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/2010/04/23/redes-neurais/</guid>
		<description><![CDATA[Esse artigo é uma tradução de: http://www.shiffman.net/teaching/nature/nn/ escrito por Daniel Shiffman. Exemplos Código de exemplo: neural_network.zip Biblioteca de rede neural (necessária para 2 dos exemplos): nn.zip perceptron simples rede neural multi-camada reconhecimento de padrões pixel Lendo The Computational Beauty of Nature, Gary William Flake, Chapter 22 — Neural Networks and Learning Um Perceptron Simples Começamos [...]]]></description>
			<content:encoded><![CDATA[<p>Esse artigo é uma tradução de: <a href="http://www.shiffman.net/teaching/nature/nn/">http://www.shiffman.net/teaching/nature/nn/</a> escrito por Daniel Shiffman.</p>
<h2>Exemplos</h2>
<p>Código de exemplo: <a href="http://lab.patrickespake.com/nn/neural_network.zip">neural_network.zip</a></p>
<p>Biblioteca de rede neural (necessária para 2 dos exemplos): <a href="http://lab.patrickespake.com/nn/nn.zip">nn.zip</a></p>
<p><a href="http://lab.patrickespake.com/nn/perceptron/"><img alt="perceptron exemplo" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/perceptron_exemplo-1.jpg" width="90" height="94" /></a></p>
<p><a href="http://lab.patrickespake.com/nn/perceptron/">perceptron simples</a></p>
<p><a href="http://lab.patrickespake.com/nn/xor/"><img alt="xor exemplo" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/xor_exemplo.jpg" width="90" height="94" /></a></p>
<p><a href="http://lab.patrickespake.com/nn/xor/">rede neural multi-camada</a></p>
<p><a href="http://lab.patrickespake.com/nn/numbers/"><img alt="number exemplo" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/number_exemplo.jpg" width="90" height="94" /></a></p>
<p><a href="http://lab.patrickespake.com/nn/numbers/">reconhecimento de padrões pixel</a></p>
<h2>Lendo</h2>
<ul>
<li>
<div>The Computational Beauty of Nature, Gary William Flake, Chapter 22 — Neural Networks and Learning</div>
</li>
</ul>
<h2>Um Perceptron Simples</h2>
<p>Começamos nossa discussão sobre Redes Neurais com um <a href="http://en.wikipedia.org/wiki/Perceptron">Perceptron</a> simples. Um Perceptron é um modelo computacional de um neurônio. É constituído por uma ou mais entradas, um processamento e uma única saída. Cada entrada recebe um peso e o processamento cria a saída via os seguintes passos:</p>
<ul>
<li>Para cada entrada, é multiplicado a entrada pelo seu peso;</li>
<li>Soma de todas as entradas vezes seus pesos, soma ponderada;</li>
<li>Computação da saída do Perceptron é baseada na soma passada para uma função de ativação.</li>
</ul>
<p>A função de ativação simples é o sinal da soma. Em outras palavras, se a soma for um número positivo, a saída é 1, se é negativo, a saída é -1. Aqui está um código que assume um array de entradas, e um array de pesos de entradas.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">// Soma todos os valores
float sum = 0;
int result = 0;
for (int i = 0; i &lt; inputs.length; i++) {
  sum += inputs[i]*weights[i];
}
if (sum &gt; 0) result = 1;
else result = -1;</pre></div></div>

<p><img alt="perceptron classificacao" align="left" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/perceptron_classificacao.jpg" width="240" height="180" /></p>
<p>Um Perceptron é normalmente utilizado para classificação. Por exemplo, digamos que um Perceptron tem 2 entradas. Usando uma função de sinal de ativação, a saída será -1 ou 1, ou seja, os dados de entrada são classificados de acordo com o sinal de saída. Ele pertence ao grupo A (-1) ou B(1).</p>
<p>Considere uma linha no espaço de 2 dimensões. Os pontos nesse espaço podem ser classificados levando em consideração um lado e outro da linha de separação. Embora este seja um exemplo bastante trivial (já que podemos determinar o lado em que situa-se um ponto, com alguma álgebra simples), um Perceptron podem ser treinados para aprender a reconhecer os pontos de um lado contra o outro.</p>
<p><a href="http://lab.patrickespake.com/nn/perceptron/">Nesse exemplo</a> , há duas entradas, a coordenada x do ponto e coordenada y. No entanto, para que o Perceptron funcione corretamente, é preciso também incorporar um &#8220;bias&#8221; de entrada. Um &#8220;bias&#8221; sempre tem o valor de 1. Porque um &#8220;bias&#8221; é necessário? Sem &#8220;bias&#8221;, se todas as entradas forem 0, a única saída possível sempre será um zero (porque a soma de um monte de zeros é só zero!). Portanto, a estrutura do nosso Perceptron é a seguinte:</p>
<p><img alt="perceptron bias" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/perceptron_bias.jpg" width="240" height="180" /></p>
<p>Com base na estrutura acima, podemos criar a classe para descrever o Perceptron. O Perceptron inclui um array de pesos de entrada, bem como uma constante de aprendizado (a constante de aprendizado será utilizada no algoritmo de treinamento descrito abaixo).</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">class Perceptron {
  float[] weights; // Array dos pesos de entrada
  float c; // Constante de aprendizado</pre></div></div>

<p>O construtor irá criar o array de pesos de entrada com base no número de entradas e define a constante de aprendizado.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">  <span style="color: #666666; font-style: italic;">// Perceptron é criado com n pesos e constante de aprendizado</span>
  Perceptron<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> n, <span style="color: #000066; font-weight: bold;">float</span> c_<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    weights <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">float</span><span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">// Inicia com pesos randômicos</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> weights.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      weights<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    c <span style="color: #339933;">=</span> c_<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></div></div>

<p>O algoritmo de adivinhação é exatamente o que nós desenvolvemos acima, a soma de todas as entradas multiplicados pelos seus pesos. No exemplo abaixo, as entradas que chegam com o argumento &#8220;vals&#8221; (algum array de pontos fluentes) para a função. O último elemento do array é portanto o &#8220;bias&#8221; e deve ter o valor 1.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">  <span style="color: #666666; font-style: italic;">// Adivinhar -1 ou 1 com base nos valores de entrada</span>
  <span style="color: #000066; font-weight: bold;">int</span> guess<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> vals<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Soma de todos os valores</span>
    <span style="color: #000066; font-weight: bold;">float</span> sum <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> weights.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      sum <span style="color: #339933;">+=</span> vals<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">*</span>weights<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #666666; font-style: italic;">// Resultado é um sinal de soma, -1 ou 1</span>
    <span style="color: #000066; font-weight: bold;">int</span> result <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>sum <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> result <span style="color: #339933;">=</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">return</span> result<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></div></div>

<p>A ponto de fazer tudo isso, claro, é ser capaz de treinar a rede para ser capaz de fazer a escolha certa. Isto é conseguido através da alimentação das entradas da rede com saídas corretas &#8220;conhecidas&#8221;, e ajustando os pesos de acordo com os erros de saída. O erro é calculado como segue:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// erro = saída desejada - saída adivinhada</span>
ERROR <span style="color: #339933;">=</span> DESIRED OUTPUT <span style="color: #339933;">-</span> GUESS OUTPUT</pre></div></div>

<p>Nesse exemplo simples, o erro somente pode ser um dos três valores: 0 (se desejado e adivinhado são iguais), 2 (se desejado = 1 e adivinhado = -1) e -2 (se desejado = -1 e adivinhado = 1). A seguinte fórmula é usada para determinar o quanto mudar os pesos. Note que, se o erro é igual a zero, os pesos não serão alterados desde que deltaweight seja igual a zero. Isso é como as coisas deveriam funcionar, pois se o erro é igual a zero, temos a resposta certa &#8212; não corrigi-lo se ele não está quebrado!</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">DELTAWEIGHT <span style="color: #339933;">=</span> LEARNINGCONSTANT <span style="color: #339933;">*</span> ERROR <span style="color: #339933;">*</span> INPUT
NEWWEIGHT <span style="color: #339933;">=</span> OLDWEIGHT <span style="color: #339933;">+</span> DELTAWEIGHT</pre></div></div>

<p>No código, isso se traduz em uma função de aprendizado:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">  <span style="color: #666666; font-style: italic;">// Função para aprendizado do Perceptron</span>
  <span style="color: #666666; font-style: italic;">// Pesos são ajustados com base na resposta de &quot;desejada&quot;</span>
  <span style="color: #000066; font-weight: bold;">void</span> train<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> vals, <span style="color: #000066; font-weight: bold;">int</span> desired<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Resultado de adivinhação</span>
    <span style="color: #000066; font-weight: bold;">int</span> result <span style="color: #339933;">=</span> guess<span style="color: #009900;">&#40;</span>vals<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">// Calcula o fator de mudança do peso com base no erro</span>
    <span style="color: #666666; font-style: italic;">// erro = saída esperada - saída adivinhada</span>
    <span style="color: #666666; font-style: italic;">// Observe que este só pode ser 0, -2, ou 2</span>
    <span style="color: #666666; font-style: italic;">// Multiplicar pela constante de aprendizado</span>
    <span style="color: #000066; font-weight: bold;">float</span> weightChange <span style="color: #339933;">=</span> c<span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span>desired <span style="color: #339933;">-</span> result<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">// Ajusta os pesos com base no weightChange * input</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> weights.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      weights<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">+=</span> weightChange <span style="color: #339933;">*</span> vals<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Para ter uma noção de como funciona a constante de aprendizado, baixe o <a href="http://lab.patrickespake.com/nn/perceptron/">exemplo de Perceptron</a> e altere o valor no construtor:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">ptron <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Perceptron<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">0.004</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>A maior constante fará com que o Perceptron aprenda mais rápido, mas pode ultrapassar o peso ideal. A baixa constante fará com que ele aprenda mais lentamente, mas ele provavelmente vai encontrar a melhor solução com mais precisão.</p>
<p>Agora que a classe Perceptron está construída, podemos treiná-lo para classificar os pontos do espaço, como descrito acima. Vamos escolher uma fórmula arbitrária de uma linha:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">y <span style="color: #339933;">=</span> 0.9x <span style="color: #339933;">-</span> <span style="color: #cc66cc;">0.2</span></pre></div></div>

<p>Nós podemos fazer isso em um função:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Função que descreve a linha</span>
<span style="color: #000066; font-weight: bold;">float</span> f<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> x<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">return</span> x<span style="color: #339933;">*</span><span style="color: #cc66cc;">0.9</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">0.2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E usá-lo para calcular um resultado conhecido. As entradas são x, y e 1 (bias) e o resultado conhecido é a variável de entrada.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">float</span> x <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">float</span> y <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">int</span> answer <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>y <span style="color: #339933;">&lt;</span> f<span style="color: #009900;">&#40;</span>x<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> answer <span style="color: #339933;">=</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span></pre></div></div>

<h2>Multi-Camadas de Rede Neural</h2>
<p>O Perceptron é bom para resolver problemas simples que têm uma solução linearmente separáveis. Em outras palavras, todos os pontos de saída 1 vão cair de um lado de uma linha no espaço 2D e todos os pontos de saída -1 vão cair do outro lado. Perceptrons, no entanto, não podem resolver problemas linearmente separáveis.</p>
<p>O exemplo mais clássico de um problema linearmente inseparáveis é o XOR. XOR é &#8220;exclusivo&#8221;, ou seja, se A ou B, mas não ambos A e B.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">AND
<span style="color: #339933;">----</span>
<span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">FALSE</span>
<span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">FALSE</span>
<span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">FALSE</span>
<span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">TRUE</span>
&nbsp;
OR
<span style="color: #339933;">----</span>
<span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">FALSE</span>
<span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">TRUE</span>
<span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">TRUE</span>
<span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">TRUE</span>
&nbsp;
XOR
<span style="color: #339933;">---</span>
<span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">FALSE</span>
<span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">TRUE</span>
<span style="color: #000066; font-weight: bold;">FALSE</span> <span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">TRUE</span>
<span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #000066; font-weight: bold;">TRUE</span>  <span style="color: #339933;">--&gt;</span> <span style="color: #000066; font-weight: bold;">FALSE</span></pre></div></div>

<p><img alt="perceptron linha xor" align="right" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/perceptron_linha_xor.jpg" width="100" height="75" />Conside os pontos (0,0), (1,0), (0,1) e (1,1) no espaço. Para XOR, não há como estabelecer uma única linha que separa os pontos verdadeiros: (1,0) e (0,1) a partir dos pontos falsos: (0,0) e (1,1). XOR é linearmente inseparáveis. Portanto, um Perceptron não pode ser treinado para desenvolver os pesos que irá produzir a saída correta (verdadeiro ou falso), dando duas entradas.</p>
<p>A fim de resolver XOR, nós temos que criar um Perceptron multi-camada com duas entradas, uma camada &#8220;escondida&#8221;, e uma saída. Esta camada oculta eleva-se para ter vários perceptrons para atacar o mesmo problema, ou seja, se &#8220;OU&#8221; é verdadeiro (perceptron #1) e &#8220;E&#8221; não é verdadeiro (perceptron #2), então a saída é XOR.</p>
<p><img alt="perceptron multi camada" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/perceptron_multi_camada.jpg" width="240" height="180" /></p>
<p>A questão agora torna-se o treinamento da rede multi-camadas para ter os pesos certos. Infelizmente, isso envolve um pouco de cálculo. Essa página vai oferecer apenas um breve panaroma da solução. Para uma explicação mais detalhada, leia o capítulo 22 em <a href="http://mitpress.mit.edu/books/FLAOH/cbnhtml/">The Computational Beauty of Nature</a>. Você pode também simplesmente <a href="http://www.google.com/search?hl=en&amp;hs=IEs&amp;client=firefox-a&amp;rls=org.mozilla:en-US:official&amp;sa=X&amp;oi=spell&amp;resnum=0&amp;ct=result&amp;cd=1&amp;q=multi-layered+neural+network+backpropagation&amp;spell=1">google multi-layered neural network backpropogation</a> .</p>
<h2>Back Propogation</h2>
<p>Uma solução para treinamento de uma rede neural multi-camada é conhecido como <a href="http://en.wikipedia.org/wiki/Backpropagation">backpropogation</a>. Certamente, existem outras opções para treinamento de uma rede neural. Por exemplo, um <a href="http://www.shiffman.net/teaching/the-nature-of-code/ga/">algoritmo genético</a> pode ser usado para pesquisar pesos ótimos!</p>
<p>Para gerar a saída da rede, as entradas multiplicadas pelos pesos são somados e alimentado para a frente através da rede. Isto é o que nós fazemos com o perceptron, só há uma camada adicional entre a entrada e a saída. O treinamento da rede envolve assumir o erro (desejado &#8211; adivinhado) e alimentá-lo para trás através da rede. Assim que o erro final informa ambos os pesos entre a camada escondida e a saída, bem como os pesos entre as entradas e a camada escondida.</p>
<p>Vamos primeiro olhar como nós alimentamos para a frente através da rede. Nossa rede neural será composta das seguintes classes:</p>
<ul>
<li>
<div align="left"><strong>Neuron</strong> &#8211; cada objeto neurônio consiste de uma lista de objetos Connection (ou seja, indicando o que outros Neurons estão conectados). Ele tem a função que calcula a sua saída com base em suas entradas multiplicado pelos pesos da conexão relevante. Ele também sabe se é um Neuron &#8220;bias&#8221; ou apenas um Neuron regular. O exemplo também tem subclasses InputNeuron, HiddenNeuron e OutputNeuron para qualquer funcionalidade específica para os neurônios;</div>
</li>
<li>
<div align="left"><strong>Connection</strong> &#8211; cada objeto Connection contém dois Neurons, o &#8220;de&#8221; Neuron e o &#8220;para&#8221; Neuron. Tem também uma variável do tipo double para o seu peso;</div>
</li>
<li>
<div align="left"><strong>Network</strong> &#8211; o objeto Network consiste de todos os Neurons. Um array de neurônios de entrada, neurônios escondidos, e um neurônio saída (embora isso possa, e deve, concebivelmente ser um array). Ele também terá funções que alimentam a rede para frente e treinam a rede para trás.</div>
</li>
</ul>
<p><img alt="sigmoid" align="right" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/sigmoid.jpg" width="150" height="167" />Assim, o primeiro passo para a alimentação para frente da rede é calcular a saída de todos os neurônios na camada escondida. Em um perceptron simples, a saída era o sinal da soma das entradas * pesos de conexão. Se essa soma foi positiva, a saída era +1, se fosse negativa, a saída era -1. O sinal da soma era nossa função de ativação.</p>
<p>Para que backpropogation funcione bem, vamos precisar de função de ativação <em>fancier</em>. Usaremos uma <a href="http://en.wikipedia.org/wiki/Sigmoid_function">função sigmóide</a>. Aqui está um <a href="http://lab.patrickespake.com/nn/sigmoid/">applet com os gráficos da função sigmóide</a> . Olhando para o gráfico, podemos ver que a função de ativação sigmóide nos diz muito mais sobre a nossa saída do que a função do sinal de ativação faz. Quando o neurônio dispara para perto do ponto 1/2 (meio do gráfico), a inclinação da curva da sigmóide é muito íngreme. Quando ele é acionado perto das bordas do exterior (os lados esquerdo ou direito da imagem à direita), a inclinação é de nível. O código da sigmóide é o seguinte:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Função sigmóide</span>
<span style="color: #000066; font-weight: bold;">float</span> f<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> x<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #cc66cc;">1.0</span> <span style="color: #339933;">/</span> <span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1.0</span> <span style="color: #339933;">+</span> exp<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span>x<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><img alt="dsigmoid" align="right" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/dsigmoid.jpg" width="150" height="167" />A inclinação da curva da sigmóide é o valor que queremos saber, uma vez que nos diz onde estamos na ativação continuum &#8211; perto do centro ou perto da borda? A inclinação é calculada pela <a href="http://en.wikipedia.org/wiki/Derivative">derivada</a> (a taxa de variação de uma função) da sigmóide. Este deve ser um conceito familiar para nós &#8211; <a href="http://www.shiffman.net/teaching/the-nature-of-code/vectors/">a taxa de variação (isto é, derivada) da localização é a velocidade, da velocidade é a aceleração</a> . A derivada da função sigmóide é <strong>f(x) * (1-f(x))</strong> e esse valor será usado no algoritmo de backpropogation para alterar os pesos.</p>
<p>Ok, de volta à alimentação para a frente! Agora que conhecemos que a função de ativação é a função sigmóide, podemos calcular a saída para qualquer neurônio dada como a soma de todos os valores de entrada * os pesos de conexão passados através da sigmóide. Note que nossos neurônios podem ter conexões entrando e saindo, mas para obter nossa saída, nós queremos apenas as conexões que entram! Além disso, se o neurônio é um neurônio bias, o cálculo não será necessário, pois a saída é sempre 1.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> connections.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003399;">Connection</span> c <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Connection</span><span style="color: #009900;">&#41;</span> connections.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  Neuron from <span style="color: #339933;">=</span> c.<span style="color: #006633;">getFrom</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  Neuron to <span style="color: #339933;">=</span> c.<span style="color: #006633;">getTo</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">// É neste contexto que se deslocam para a frente</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>to <span style="color: #339933;">==</span> <span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      sum <span style="color: #339933;">+=</span> from.<span style="color: #006633;">getOutput</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>c.<span style="color: #006633;">getWeight</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
output <span style="color: #339933;">=</span> f<span style="color: #009900;">&#40;</span>sum<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Agora que os neurônios sabem como calcular suas saídas, nós podemos pegar os valores de entrada e alimentar para frente. Primeiro, nós alimentamos nas entradas, então fazemos loop em todos os neurônios escondidos e calculamos suas saídas, e então nós calculamos a saída do do neurônio de saída em si! Aqui é um trecho de exemplo (na Network) classe:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">double</span> feedForward<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">double</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> inputVals<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// Primeiro colocamos os valores de entrada na rede</span>
  <span style="color: #666666; font-style: italic;">//System.out.println(&quot;\n\nFeeding input layer&quot;);</span>
  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> inputVals.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    input<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #006633;">input</span><span style="color: #009900;">&#40;</span>inputVals<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #666666; font-style: italic;">// Então calculamos a saída para a camada escondida</span>
  <span style="color: #666666; font-style: italic;">//System.out.println(&quot;\n\nFeeding hidden layer&quot;);</span>
  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> hidden.<span style="color: #006633;">length</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//System.out.println(&quot;\nNeuron &quot; + i);</span>
    hidden<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #006633;">calcOutput</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">//System.out.println(&quot;\n\nFeeding output layer&quot;);</span>
  output.<span style="color: #006633;">calcOutput</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">return</span> output.<span style="color: #006633;">getOutput</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Uma vez que temos a saída da rede neural, podemos comparar a saída para uma resposta conhecida (a partir do XOR) e ajustar os pesos de acordo.</p>
<p>Com o perceptron simples, foi calculado o erro como:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// erro = desejado - adivinhado</span>
ERROR <span style="color: #339933;">=</span> DESIRED <span style="color: #339933;">-</span> GUESS</pre></div></div>

<p>Vamos agora usar o fato que a a derivada da função sigmóide nós contou mais informações sobre o erro e o cálculo da seguinte maneira:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// erro = adivinhado*(1-adivinhado) * (desejado-adivinhado)</span>
ERROR <span style="color: #339933;">=</span> GUESS<span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">-</span>GUESS<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #009900;">&#40;</span>DESIRED<span style="color: #339933;">-</span>GUESS<span style="color: #009900;">&#41;</span></pre></div></div>

<p>Esse erro é aplicado aos pesos entre a saída e a camada escondida.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">DELTAWEIGHT <span style="color: #339933;">=</span> LEARNINGCONSTANT <span style="color: #339933;">*</span> ERROR <span style="color: #339933;">*</span> HIDDEN OUTPUT
NEWWEIGHT <span style="color: #339933;">=</span> OLDWEIGHT <span style="color: #339933;">+</span> DELTAWEIGHT</pre></div></div>

<p>O próximo passo é calcular o erro para a saída do neurônio escondido. Essa é a parte mais difícil, uma vez que nós não temos uma resposta conhecida! Sabemos apenas qual o resultado final que toda rede deve ser! A fórmula para o erro da camada escondida é, portanto, uma função de derivação da sua própria saída e que o erro global de toda a rede.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">HIDDENERROR <span style="color: #339933;">=</span> HIDDEN OUTPUT<span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">-</span>HIDDEN OUTPUT<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #009900;">&#40;</span>ERROR<span style="color: #339933;">*</span> WEIGHT TO FINALOUTPUT<span style="color: #009900;">&#41;</span></pre></div></div>

<p>Note que, se existe várias saídas nós somamos os erros multiplicando pelo pesos das saídas, mas com XOR, nós não temos que se preocupar com isso. Finalmente, ajustamos os pesos recebidos na camada escondida com HIDDENERROR.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">DELTAWEIGHT <span style="color: #339933;">=</span> LEARNINGCONSTANT <span style="color: #339933;">*</span> HIDDENERROR <span style="color: #339933;">*</span> INPUT NEURON
NEWWEIGHT <span style="color: #339933;">=</span> OLDWEIGHT <span style="color: #339933;">+</span> DELTAWEIGHT</pre></div></div>

<p>E é isso! A chave aqui é compreender que devemos primeiro calcular o erro de saída da rede inteira. E, em seguinda, usar esse erro para determinar quanto cada conexão ao longo do caminho de volta para o início contribui para esse erro, e ajustar os pesos de acordo.</p>
<p>Aqui está a função para executar todos estes cálculos:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">double</span> train<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">double</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> inputs, <span style="color: #000066; font-weight: bold;">double</span> answer<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">double</span> result <span style="color: #339933;">=</span> feedForward<span style="color: #009900;">&#40;</span>inputs<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000066; font-weight: bold;">double</span> deltaOutput <span style="color: #339933;">=</span> result<span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">-</span>result<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #009900;">&#40;</span>answer<span style="color: #339933;">-</span>result<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// Isso é fácil b/c só temos uma saída</span>
  <span style="color: #003399;">ArrayList</span> connections <span style="color: #339933;">=</span> output.<span style="color: #006633;">getConnections</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> connections.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">Connection</span> c <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Connection</span><span style="color: #009900;">&#41;</span> connections.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Neuron neuron <span style="color: #339933;">=</span> c.<span style="color: #006633;">getFrom</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">double</span> output <span style="color: #339933;">=</span> neuron.<span style="color: #006633;">getOutput</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">double</span> deltaWeight <span style="color: #339933;">=</span> output<span style="color: #339933;">*</span>deltaOutput<span style="color: #339933;">;</span>
    c.<span style="color: #006633;">adjustWeight</span><span style="color: #009900;">&#40;</span>LEARNING_CONSTANT<span style="color: #339933;">*</span>deltaWeight<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// Ajusta pesos escondidos</span>
  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> hidden.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    connections <span style="color: #339933;">=</span> hidden<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #006633;">getConnections</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">double</span> sum  <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> connections.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #003399;">Connection</span> c <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Connection</span><span style="color: #009900;">&#41;</span> connections.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>j<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// Primeiro soma todas as conexões para OUTPUTS*deltaOutput (só uma saída)</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>c.<span style="color: #006633;">getFrom</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> hidden<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                sum <span style="color: #339933;">+=</span> c.<span style="color: #006633;">getWeight</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>deltaOutput<span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #666666; font-style: italic;">// Então ajusta os pesos nos próximos</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> connections.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #003399;">Connection</span> c <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Connection</span><span style="color: #009900;">&#41;</span> connections.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>j<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>c.<span style="color: #006633;">getTo</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> hidden<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">double</span> output <span style="color: #339933;">=</span> hidden<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #006633;">getOutput</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">double</span> deltaHidden <span style="color: #339933;">=</span> output <span style="color: #339933;">*</span> <span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span> <span style="color: #339933;">-</span> output<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        deltaHidden <span style="color: #339933;">*=</span> sum<span style="color: #339933;">;</span>   <span style="color: #666666; font-style: italic;">// Será a soma para todas as saídas se mais de uma saída</span>
        Neuron neuron <span style="color: #339933;">=</span> c.<span style="color: #006633;">getFrom</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">double</span> deltaWeight <span style="color: #339933;">=</span> neuron.<span style="color: #006633;">getOutput</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">*</span>deltaHidden<span style="color: #339933;">;</span>
        c.<span style="color: #006633;">adjustWeight</span><span style="color: #009900;">&#40;</span>LEARNING_CONSTANT<span style="color: #339933;">*</span>deltaWeight<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">return</span> result<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/04/23/redes-neurais/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jogo Galaxis Farm será apresentando VI Seminario Jogos Eletrônicos, Educação e Comunicação</title>
		<link>http://blog.patrickespake.com/2010/04/21/jogo-galaxis-farm-sera-apresentando-vi-seminario-jogos-eletronicos-educacao-e-comunicacao/</link>
		<comments>http://blog.patrickespake.com/2010/04/21/jogo-galaxis-farm-sera-apresentando-vi-seminario-jogos-eletronicos-educacao-e-comunicacao/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 01:24:28 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flixel]]></category>
		<category><![CDATA[Game]]></category>
		<category><![CDATA[Inteligência Artificial]]></category>
		<category><![CDATA[Jogo]]></category>
		<category><![CDATA[PIBIC]]></category>
		<category><![CDATA[Projetos]]></category>
		<category><![CDATA[apresentação]]></category>
		<category><![CDATA[galaxis farm]]></category>
		<category><![CDATA[projeto]]></category>
		<category><![CDATA[tecpar]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/2010/04/21/jogo-galaxis-farm-sera-apresentando-vi-seminario-jogos-eletronicos-educacao-e-comunicacao/</guid>
		<description><![CDATA[Durante aproxidamente três meses eu estive trabalhando como programador do jogo Galaxis Farm, ele está disponível no endereço: http://www.galaxisfarm.com. Esse foi o meu primeiro grande jogo, essa consideração é porque diversas pessoas estiveram presentes no processo: Eu &#8211; Programação; Diego Cabral &#8211; Ilustrações e design de personagens; Bruno Campagnolo de Paula &#8211; Coordenação e game [...]]]></description>
			<content:encoded><![CDATA[<p align="center"><img alt="banner galaxisfarm" src="http://blog.patrickespake.com/wp-content/uploads/2010/04/banner_galaxisfarm-small.png" width="450" height="71" /></p>
<p>Durante aproxidamente três meses eu estive trabalhando como programador do jogo Galaxis Farm, ele está disponível no endereço: <a href="http://www.galaxisfarm.com">http://www.galaxisfarm.com</a>.</p>
<p>Esse foi o meu primeiro grande jogo, essa consideração é porque diversas pessoas estiveram presentes no processo:</p>
<ul>
<li>Eu &#8211; Programação;</li>
<li>Diego Cabral &#8211; Ilustrações e design de personagens;</li>
<li>Bruno Campagnolo de Paula &#8211; Coordenação e game design;</li>
<li>Roberta Zuge &#8211; Consultoria veterinária.</li>
</ul>
<p>Até o presente momento eu obtive um grande aprendizado em todo o processo de desenvolvimento, além dos fatores tecnológicos, os fatores científicos, de pesquisa, colaboração e concepção foram fortemente abordados.</p>
<p>Agora recebi a boa notícia que o jogo foi selecionado para participar da mostra de jogos eletrônicos que acontecerá no VI Seminário Jogos Eletrônicos, Educação e Comunicação &#8211; construindo novas trilhas, na Universidade do Estado da Bahia (UNEB). A apresentação do jogo será realizada no dia 06/05, com início às 12h e término às 12h20.</p>
<p>Mais informações: <a href="http://realidadesintetica.com/seminario/">http://realidadesintetica.com/seminario/</a></p>
<p>Parabéns a todos os envolvidos.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/04/21/jogo-galaxis-farm-sera-apresentando-vi-seminario-jogos-eletronicos-educacao-e-comunicacao/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
