<?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>Machine Learning | Brainxyz</title>
	<atom:link href="https://www.brainxyz.com/./machine-learning/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.brainxyz.com/./machine-learning/</link>
	<description>Machine Learning, Artificial Intelligence, Brain, Neuroscience, AI</description>
	<lastBuildDate>Tue, 10 Jan 2023 17:44:01 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.2</generator>

<image>
	<url>https://www.brainxyz.com/wp-content/uploads/2020/08/cropped-new_icon4-1.png</url>
	<title>Machine Learning | Brainxyz</title>
	<link>https://www.brainxyz.com/./machine-learning/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">181902284</site>	<item>
		<title>Artificial Life Simulation</title>
		<link>https://www.brainxyz.com/machine-learning/artificial-life/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=artificial-life</link>
					<comments>https://www.brainxyz.com/machine-learning/artificial-life/#respond</comments>
		
		<dc:creator><![CDATA[Brainxyz]]></dc:creator>
		<pubDate>Thu, 08 Sep 2022 23:08:04 +0000</pubDate>
				<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[artificial life]]></category>
		<category><![CDATA[cellular automata]]></category>
		<category><![CDATA[conway&#039;s game of life]]></category>
		<category><![CDATA[evolution]]></category>
		<category><![CDATA[fractals]]></category>
		<category><![CDATA[particle life]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://www.brainxyz.com/?p=2266</guid>

					<description><![CDATA[<p>Recently, I made an educational simulation project on what is known as Particle Life to showcase how complexity can arise from simplicity. Particle Life is like Conway’s game of life but in Conway&#8217;s game of life the effect of the particles are confined to their surrounding neighbors only while in these simulations particles have effects...</p>
<p>The post <a href="https://www.brainxyz.com/machine-learning/artificial-life/">Artificial Life Simulation</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
<p>The post <a href="https://www.brainxyz.com/machine-learning/artificial-life/">Artificial Life Simulation</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Recently, I made an educational simulation project on what is known as Particle Life to showcase how complexity can arise from simplicity. Particle Life is like Conway’s game of life but in Conway&#8217;s game of life the effect of the particles are confined to their surrounding neighbors only while in these simulations particles have effects on each other over longer distances. Also, the interactions rely on Newtonian like attraction/repulsion forces among the interacting particles.</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="573" src="https://www.brainxyz.com/wp-content/uploads/2022/09/big_pic-1024x573.jpg" alt="" class="wp-image-2267" srcset="https://www.brainxyz.com/wp-content/uploads/2022/09/big_pic-scaled.jpg 1024w, https://www.brainxyz.com/wp-content/uploads/2022/09/big_pic-scaled.jpg 300w, https://www.brainxyz.com/wp-content/uploads/2022/09/big_pic-scaled.jpg 768w, https://www.brainxyz.com/wp-content/uploads/2022/09/big_pic-scaled.jpg 1536w, https://www.brainxyz.com/wp-content/uploads/2022/09/big_pic-scaled.jpg 2048w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>A diverse set of self-organizing patterns. All emerged from four particle types interacting with each other.</figcaption></figure>



<p></p>



<p>In our case, four particle types (green, red, white, yellow) are interacting with each other. Each has a different attraction and repulsion property toward the other particle types. They start randomly and with time they aggregate together and move around giving rise to some interesting formations and behaviors. This produces some interesting self-organizing patterns where it looks life-like cells eating, chasing, or merging with each other.</p>



<p>I modified the algorithm to make it much simpler removing collision detection and distance squaring which has improved the performance and allowed testing thousands of particles in real-time. I also added the ability to explore various parameters in real-time. This has allowed me to discover some never-seen before patterns to emerge from some very simple rules. This simulation changed my mind that, after all, life like patterns are not so difficult to emerge especially during the early earth days where the primordial soup was filled with the necessary ingredients.</p>



<p>One thing to be noted is, the simulation here involved unidirectional attraction and repulsion too. This asymmetry, which doesn&#8217;t exist at the atomic level, leads to some interesting chasing behavior. However, one can easily imagine the emergence of the chasing behavior from symmetrical forces if we simulate a very large number of particles in a much larger space. For example, we might have a large protein that has more negative ions on one side than the other or we can imagine a closed space with a negatively charged membrane, a positive particle will move towards the membrane and might be followed by a negative charge imitating chasing. We, as a local observer, might model the chasing with asymmetrical force without the need to model the membrane. This is good news, because it means we can model complex biochemical reactions to some degree of accuracy with much less computational resources. </p>



<p>Complex patterns emerging from simple relations is an interesting topic but as a Neuroscientist, I am interested in the reversal process where our brain tries to untangle the complexities and re-model the relationships among its neuronal connections. Our brains ability to model these relations is what allows us to imagine and predict.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="916" height="594" src="https://www.brainxyz.com/wp-content/uploads/2022/09/brain_rversal.jpg" alt="" class="wp-image-2278" srcset="https://www.brainxyz.com/wp-content/uploads/2022/09/brain_rversal.jpg 916w, https://www.brainxyz.com/wp-content/uploads/2022/09/brain_rversal.jpg 300w, https://www.brainxyz.com/wp-content/uploads/2022/09/brain_rversal.jpg 768w" sizes="(max-width: 916px) 100vw, 916px" /><figcaption>Human brain is able to model the relations among its neuronal connections</figcaption></figure>



<p></p>



<p>Simulation demos and a walk-through tutorial is available in this video:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="How to Simulate Artificial Life" width="720" height="405" src="https://www.youtube.com/embed/0Kx4Y9TVMGg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You can find the project source code on GitHub: https://github.com/hunar4321/particle-life</p>



<p>You can also play with a live online demo here: https://hunar4321.github.io/particle-life/particle_life.html</p>



<p>The JavaScript code is as simple as this:</p>



<pre class="wp-block-code"><code>&lt;canvas id="life" width="500" height="500"&gt;&lt;/canvas&gt;
&lt;script&gt;
  //Hunar Ahmad @ brainxyz
  m = document.getElementById("life").getContext("2d");
  draw = (x, y, c, s) =&gt; {
    m.fillStyle = c;
    m.fillRect(x, y, s, s);
  };
  atoms = &#91;];
  atom = (x, y, c) =&gt; {
    return { x: x, y: y, vx: 0, vy: 0, color: c };
  };
  random = () =&gt; {
    return Math.random() * 400 + 50;
  };
  create = (number, color) =&gt; {
    group = &#91;];
    for (let i = 0; i &lt; number; i++) {
      group.push(atom(random(), random(), color));
      atoms.push(group&#91;i]);
    }
    return group;
  };
  rule = (atoms1, atoms2, g) =&gt; {
    for (let i = 0; i &lt; atoms1.length; i++) {
      fx = 0;
      fy = 0;
      for (let j = 0; j &lt; atoms2.length; j++) {
        a = atoms1&#91;i];
        b = atoms2&#91;j];
        dx = a.x - b.x;
        dy = a.y - b.y;
        d = Math.sqrt(dx * dx + dy * dy);
        if (d &gt; 0 &amp;&amp; d &lt; 80) {
          F = (g * 1) / d;
          fx += F * dx;
          fy += F * dy;
        }
      }
      a.vx = (a.vx + fx) * 0.5;
      a.vy = (a.vy + fy) * 0.5;
      a.x += a.vx;
      a.y += a.vy;
      if (a.x &lt;= 0 || a.x &gt;= 500) { a.vx *= -1; }
      if (a.y &lt;= 0 || a.y &gt;= 500) { a.vy *= -1; }
    }
  };
  yellow = create(200, "yellow");
  red = create(200, "red");
  green = create(200, "green");
  update = () =&gt; {
    rule(green, green, -0.32);
    rule(green, red, -0.17);
    rule(green, yellow, 0.34);
    rule(red, red, -0.1);
    rule(red, green, -0.34);
    rule(yellow, yellow, 0.15);
    rule(yellow, green, -0.2);
    m.clearRect(0, 0, 500, 500);
    draw(0, 0, "black", 500);
    for (i = 0; i &lt; atoms.length; i++) {
      draw(atoms&#91;i].x, atoms&#91;i].y, atoms&#91;i].color, 5);
    }
    requestAnimationFrame(update);
  };
  update();
&lt;/script&gt;</code></pre>



<p>This project was inspired by Jeffery Ventrella&#8217;s Clusters <a href="https://www.youtube.com/redirect?event=video_description&amp;redir_token=QUFFLUhqbm1mcTlaOHZ3c2lLMDYyQjBfcElqejk3cEtyQXxBQ3Jtc0tsUzVQQ3pKeWMxUGpYQlNnajkyZ0xSNzBkQ2o4R3d3aGE3ZXo5YjM5YzhjbGh2N0lqMW5oUkpRWHl0SDlMaFlFc0sxcW14b01YbFk1QUQ0bXVlb1ZFcEExaUEwYXZqZ3otc3BjNmVxcGlwdmFTWmh3MA&amp;q=http%3A%2F%2Fwww.ventrella.com%2FClusters%2F&amp;v=0Kx4Y9TVMGg" target="_blank" rel="noreferrer noopener">http://www.ventrella.com/Clusters/</a>. I don&#8217;t have access to Ventrella&#8217;s code but I guess the main difference of this project with the other particle life projects is that I didn&#8217;t implement collision detection and this made simulating thousands of particles possible in real-time. </p>



<p>Also, I added GUI controls to change the parameters in real-time this allows easy fine-tuning &amp; exploration, hence, I was able to find some never-seen-before patterns emerge form some extremely simple models of relations. The code here is probably an order of magnitude simpler than any other Artificial Life codes out there because I started this code solely as an educational material for non-programmers and general audience to prove the point that complexity can arise from simplicity.</p>



<p>Another famous of example of complexity arising from simplicity is the Mendelbrot set:</p>



<figure class="wp-block-embed is-provider-youtube wp-block-embed-youtube"><div class="wp-block-embed__wrapper">
<iframe title="How to Create a Universe with Notepad" width="720" height="405" src="https://www.youtube.com/embed/mzizK6ms-gY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Related topics: <a href="https://www.youtube.com/hashtag/artificial">#artificial</a> <a href="https://www.youtube.com/hashtag/game">#game</a> <a href="https://www.youtube.com/hashtag/simulator">#simulator</a>, Particle Life Simulation, Primordial Soup &#8211; Evolution, Conway&#8217;s game of life, Cellular automata, Fractals, Self organizing patterns, Mandelbrot, JavaScript programming.</p>The post <a href="https://www.brainxyz.com/machine-learning/artificial-life/">Artificial Life Simulation</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.<p>The post <a href="https://www.brainxyz.com/machine-learning/artificial-life/">Artificial Life Simulation</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.brainxyz.com/machine-learning/artificial-life/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2266</post-id>	</item>
		<item>
		<title>Simulation: Life as a Survival Optimization Problem</title>
		<link>https://www.brainxyz.com/machine-learning/maxima/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maxima</link>
					<comments>https://www.brainxyz.com/machine-learning/maxima/#respond</comments>
		
		<dc:creator><![CDATA[Brainxyz]]></dc:creator>
		<pubDate>Sat, 25 Sep 2021 19:22:49 +0000</pubDate>
				<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[evolution]]></category>
		<category><![CDATA[genetic algorithm]]></category>
		<category><![CDATA[local maxima]]></category>
		<guid isPermaLink="false">https://www.brainxyz.com/?p=2210</guid>

					<description><![CDATA[<p>As someone who came to the Machine Learning world from a Medical background, I couldn&#8217;t help not relating being stuck at a Local Maximum to other life situations. So I have decided to make a simulation project that helps to visualize this problem from a biological and also a political perspective where liberals and conservatives...</p>
<p>The post <a href="https://www.brainxyz.com/machine-learning/maxima/">Simulation: Life as a Survival Optimization Problem</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
<p>The post <a href="https://www.brainxyz.com/machine-learning/maxima/">Simulation: Life as a Survival Optimization Problem</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As someone who came to the Machine Learning world from a Medical background, I couldn&#8217;t help not relating <strong>being stuck at a Local Maximum</strong> to other life situations. So I have decided to make a simulation project that helps to visualize this problem from a biological and also a political perspective where liberals and conservatives compete to reach the global maximum (Links at the end).<br></p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><img decoding="async" src="https://www.brainxyz.com/wp-content/uploads/2021/09/game_extinction1.gif" alt="" class="wp-image-2212" width="701" height="395"/><figcaption>Increasing External Threats Gradually to aid reaching Global Maximum</figcaption></figure></div>



<p>The geographical representation is a very nice way to visualize and relate the topics. For instance, internal struggle and Existential threats can be seen as means to help in reaching the Global Maximum. Also, sexual reproduction can be seen as a way to share information between two Local Maxima which can help in reducing the search space.</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://www.brainxyz.com/wp-content/uploads/2021/09/life_before_after-1024x576.png" alt="" class="wp-image-2214" width="702" height="394" srcset="https://www.brainxyz.com/wp-content/uploads/2021/09/life_before_after.png 1024w, https://www.brainxyz.com/wp-content/uploads/2021/09/life_before_after.png 300w, https://www.brainxyz.com/wp-content/uploads/2021/09/life_before_after.png 768w, https://www.brainxyz.com/wp-content/uploads/2021/09/life_before_after.png 1536w, https://www.brainxyz.com/wp-content/uploads/2021/09/life_before_after.png 1920w" sizes="(max-width: 702px) 100vw, 702px" /></figure></div>



<p class="has-text-align-left">One can even relate this problem to politics! For instance, you can think of a Conservative as someone with a small step changing-rate while a Liberal as someone with a large step adaptation-rate. Political systems like Anarchy can be seen as a situation where no one sticks to any Local Maxima whereas fascism can be seen as everyone sticks to a single Local Maximum.</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://www.brainxyz.com/wp-content/uploads/2021/09/lib_v_cons.gif" alt="" class="wp-image-2211" width="712" height="402"/><figcaption>Liberal vs. Conservative (Simulation)</figcaption></figure></div>



<p>We know that DNA based life replicates and reproduces exponentially but because of resource limitations it will hit a ceiling and due to the internal struggle it optimizes itself for surviving better, hence, the survival of the fittest is becoming the objective of life.</p>



<p><strong>An illustrative video description of the simulations is here:</strong></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Life Is Complicated by Local Maxima (Simulation)" width="720" height="405" src="https://www.youtube.com/embed/1p11-oggW1E?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>The purpose of this simulation is not to present the state-of-the-art algorithms but to bridge and link the terms that are used in the Machine Learning world and the ones that are used in the biological and the political world by making these toy simulations and easily digestible videos to both parties. I believe the Machine learning world can give so much to the other fields because life in essence is a survival optimization problem where everything is complicated by being stuck at a Local Maximum.</p>



<p><strong>Here you can play with the simulation:</strong> https://simmer.io/@hunar/reaching-global-maxima</p>



<p><strong>Simulation Code:</strong> <a href="https://github.com/hunar4321/Reaching-global-maximum" rel="noreferrer noopener" target="_blank">https://github.com/hunar4321/Reaching-global-maximum</a></p>



<p><strong>Important Note:</strong><br>Some experts say that Local Maxima doesn&#8217;t matter in very high dimensional landscapes. This is true if the convergence speed doesn&#8217;t matter and also if all dimensions have equal weights. However, we know that is not the case, convergence speed always matters in a competitive world like ours as all Life forms are in a tough race for survival. Also, not all dimensions have the same impactful weight. Many dimensions can be ignored or they are already pruned or not accessible, therefore, the actual number of the plausible dimensions is much less than the available dimensions.</p>



<p><strong>Related topics: </strong></p>



<p>Other related Algorithms: Neat algorithm, Hill Climbing, Particle swarm optimization&#8230;,etc. </p>



<p>Other Optimization techniques that uses Calculus: Gradient Descent, Adam, Recursive Least Squares…, etc. </p>



<p>Other related terms: Local minimum &amp; Global minimum (when minimizing the error) </p>



<p>Deep Learning techniques are good to avoid being stuck at local maximum as they use many layers and lots of data. </p>



<p>Other learning methods: Hebbian Learning, Winner takes it all (WTA), …etc. We at Brainxyz use: Predictive Hebbian Unified Neurons (PHUN)</p>The post <a href="https://www.brainxyz.com/machine-learning/maxima/">Simulation: Life as a Survival Optimization Problem</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.<p>The post <a href="https://www.brainxyz.com/machine-learning/maxima/">Simulation: Life as a Survival Optimization Problem</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.brainxyz.com/machine-learning/maxima/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2210</post-id>	</item>
		<item>
		<title>Artificial Neural Networks &#124; Interpolation vs. Extrapolation</title>
		<link>https://www.brainxyz.com/machine-learning/ann/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ann</link>
					<comments>https://www.brainxyz.com/machine-learning/ann/#comments</comments>
		
		<dc:creator><![CDATA[Brainxyz]]></dc:creator>
		<pubDate>Mon, 07 Sep 2020 22:03:59 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[deep learning]]></category>
		<category><![CDATA[GPT-3]]></category>
		<category><![CDATA[neural network]]></category>
		<guid isPermaLink="false">https://www.brainxyz.com/?p=1579</guid>

					<description><![CDATA[<p>Artificial Neural Networks (ANNs) are powerful inference tools. They can be trained to fit complex functions and then used to predict new (unseen) data outside their training set. Fitting the training data is relatively easy for ANNs because of their Universal Approximation capability. However, that does not mean ANNs can learn the rules as we...</p>
<p>The post <a href="https://www.brainxyz.com/machine-learning/ann/">Artificial Neural Networks | Interpolation vs. Extrapolation</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
<p>The post <a href="https://www.brainxyz.com/machine-learning/ann/">Artificial Neural Networks | Interpolation vs. Extrapolation</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Artificial Neural Networks (ANNs) are powerful inference tools. They can be trained to fit complex functions and then used to predict new (unseen) data outside their training set. Fitting the training data is relatively easy for ANNs because of their <a href="https://en.wikipedia.org/wiki/Universal_approximation_theorem" target="_blank" rel="noreferrer noopener nofollow">Universal Approximation</a> capability. However, that does not mean ANNs can learn the rules as we humans do. Here we aim to show how well a trained ANN, which fits its training data accurately, can generalize to new and unseen data. We categorize the unseen data into two types:</p>



<ol class="wp-block-list"><li>Data points within the training range (that can be interpolated). </li><li>Data points outside the training range (that can be extrapolated). </li></ol>



<p></p>



<p>Take this example: <strong>|</strong> 1-&gt;1 <strong>|</strong> 2-&gt;4 <strong>|</strong> 3-&gt;<strong>?</strong> <strong>|</strong> 4-&gt;16 <strong>|</strong> 5-&gt;25 <strong>|</strong> 6-&gt;<strong>?</strong> <strong>|</strong> &#8230;</p>



<p>If we ask a human to predict 3-&gt;? and 6-&gt;? from the sequence above, most humans can answer correctly once they discover the rule that fits the set, in this example: <strong>y = X<sup>2</sup></strong>. The process of predicting 3-&gt;9 is called interpolation while the process of predicting 6-&gt;36 is called extrapolation. In this specific example, the distinction between interpolation and extrapolation is not important for humans because as humans find the power rule, they can apply it for any other number in the sequence. Even if we jump to 100-&gt;?, the answer is straight forward (100<sup>2</sup>). Nevertheless, the distinction between interpolation and extrapolation is quite important for ANNs and this sheds some insight into the difference between learning in humans versus learning in ANNs.</p>



<p>Here we demonstrate this difference by implementing a simple yet powerful ANN architecture with a single hidden layer and demonstrate its generalization capability for various parameter settings. We randomly assign and freeze the weights in the first layer and only train the weights in the final layer using a closed-form solution. This method is popularized under the name <a rel="noreferrer noopener nofollow" href="https://en.wikipedia.org/wiki/Extreme_learning_machine" target="_blank">Extreme Learning Machine (ELM)</a> and has some controversial origins. From our experience, this method trains quickly and gives very accurate results for low dimensional datasets that have shallow structures. We use Matlab to showcase the demonstration because its syntax is similar to algebra and we can implement the ANN from scratch in just a few lines of code. First, we start from the hello world of Machine Learning which is training ANN to solve the XOR problem. Below is the complete Matlab code:</p>



<pre class="wp-block-code"><code>X = &#91; 0, 0; 1, 1; 0, 1; 1, 0 ];          % Xor data
y = &#91; 0, 0, 1, 1 ];                      % targets

input = 2; neurons = 5;                  % parameters.
Wx = randn(input, neurons)*0.01;         % input-hidden weights (range ~ -0.01 to 0.01)
z = tanh(X * Wx);                        % 1st-Layer forward activation (tanh)
Wo = y * pinv(z');                       % Training output weights (closed form solution)
predictions = tanh(X * Wx) * Wo';        % Feedforward propagation | inference

disp(predictions)                        % display the predicted data </code></pre>



<p>Believe it or not, the above is all you need to construct and train a single hidden layer ANN (no external libraries are needed). You can achieve comparable conciseness with python+numpy ( <a rel="noreferrer noopener" href="https://github.com/hunar4321/Simple_ANN/blob/master/ELM.py" target="_blank">https://github.com/hunar4321/Simple_ANN/blob/master/ELM.py</a> ). If you run this code in your IDE, it will output very close predictions to the targets i.e [0, 0, 1, 1]. What is more, the same lines of code can be used to approximate any function given you have enough neurons in the hidden layer. Though it should be noted that for very large inputs the inverse operation of the closed-form solution is computationally expensive. And in the case of very noisy datasets, over-fitting is the usual enemy.</p>



<p>Coming back to our quest which was to examine the ability of such trained networks to interpolate and extrapolate the unseen data, the XOR example is not useful for our quest because all the input data is used for training. A better example is to use these networks to solve the power rule: <strong>y = X<sup>2</sup></strong> (our first example). Following is the complete Matlab code for our next example:</p>



<pre class="wp-block-code"><code>step = 2;                          % step size i.e the gap between the training sequence

X = &#91;2:step:100]';                 % training data (even numbers) % 2, 4, 6,...
y = X.^2;                          % train targets

inp = 1; neurons = 100; 
Wx = randn(inp, neurons)*0.01;
z = tanh(X * Wx);
Wo = y' * pinv(z');
yhat = tanh(X * Wx) * Wo';

Xt = &#91;1:step:121]';               % testing data (odd numbers) % 1, 3, 5,...
yt = Xt.^2;                       % test targets

prediction = tanh(Xt * Wx) * Wo'; % inference

% visualizations
figure; hold on; plot(X, y,'og'); plot(X, yhat, '*r'); hold off; 
legend('target', 'prediction'); title('y = X^2')
figure; hold on; plot(Xt, yt,'og'); plot(Xt, prediction, '*r'); hold off; 
legend('target', 'prediction'); title('y = X^2')
xticks = 1:10:121;
set(gca,'XTick',xticks)</code></pre>



<p>The inputs for training are even numbers from 0 to 100 and their squares are the target outputs. As you can see from Figure 1, the network learned to fit and approximate the training data very well. </p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<div class="wp-block-media-text is-stacked-on-mobile is-vertically-aligned-center" style="grid-template-columns:55% auto"><figure class="wp-block-media-text__media"><img loading="lazy" decoding="async" width="560" height="420" src="https://www.brainxyz.com/wp-content/uploads/2020/09/training.png" alt="" class="wp-image-1658" srcset="https://www.brainxyz.com/wp-content/uploads/2020/09/training.png 560w, https://www.brainxyz.com/wp-content/uploads/2020/09/training.png 300w" sizes="(max-width: 560px) 100vw, 560px" /></figure><div class="wp-block-media-text__content">
<p class="has-text-align-center"></p>



<figure class="wp-block-table"><table><tbody><tr><td class="has-text-align-center" data-align="center">Input</td><td class="has-text-align-center" data-align="center">Prediction</td><td class="has-text-align-center" data-align="center">Target</td></tr><tr><td class="has-text-align-center" data-align="center">10</td><td class="has-text-align-center" data-align="center">99.23210</td><td class="has-text-align-center" data-align="center">100</td></tr><tr><td class="has-text-align-center" data-align="center">12</td><td class="has-text-align-center" data-align="center">144.1864</td><td class="has-text-align-center" data-align="center">144</td></tr><tr><td class="has-text-align-center" data-align="center">14</td><td class="has-text-align-center" data-align="center">196.7875</td><td class="has-text-align-center" data-align="center">196</td></tr><tr><td class="has-text-align-center" data-align="center">16</td><td class="has-text-align-center" data-align="center">256.7168</td><td class="has-text-align-center" data-align="center">256</td></tr><tr><td class="has-text-align-center" data-align="center">18</td><td class="has-text-align-center" data-align="center">324.1782</td><td class="has-text-align-center" data-align="center">324</td></tr></tbody></table><figcaption>Table 1: Few examples of training inference</figcaption></figure>
</div></div>



<p class="has-text-align-left">Figure 1: Fitting y = X<sup>2</sup> | training-set</p>
</div></div>



<p>We tested the same network, after training on the even numbers, to predict the unseen odd numbers from 1 to 121. Figure 2 shows the network&#8217;s ability to generalize to the unseen data. As you can note, ANN can predict the odd numbers that are within the training range very well, but cannot extrapolate beyond the training range i.e. When it reaches 101 it starts to give wrong predictions.</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<div class="wp-block-media-text is-stacked-on-mobile is-vertically-aligned-center" style="grid-template-columns:54% auto"><figure class="wp-block-media-text__media"><img loading="lazy" decoding="async" width="560" height="420" src="https://www.brainxyz.com/wp-content/uploads/2020/09/testing.png" alt="" class="wp-image-1659" srcset="https://www.brainxyz.com/wp-content/uploads/2020/09/testing.png 560w, https://www.brainxyz.com/wp-content/uploads/2020/09/testing.png 300w" sizes="(max-width: 560px) 100vw, 560px" /></figure><div class="wp-block-media-text__content">
<p class="has-text-align-center"></p>



<figure class="wp-block-table"><table><tbody><tr><td class="has-text-align-center" data-align="center"><strong>Input</strong></td><td class="has-text-align-center" data-align="center"><strong>Prediction</strong></td><td class="has-text-align-center" data-align="center"><strong>Target</strong></td></tr><tr><td class="has-text-align-center" data-align="center">11</td><td class="has-text-align-center" data-align="center">120.7115</td><td class="has-text-align-center" data-align="center">121</td></tr><tr><td class="has-text-align-center" data-align="center">13</td><td class="has-text-align-center" data-align="center">169.5647</td><td class="has-text-align-center" data-align="center">169</td></tr><tr><td class="has-text-align-center" data-align="center">15</td><td class="has-text-align-center" data-align="center">225.8335</td><td class="has-text-align-center" data-align="center">225</td></tr><tr><td class="has-text-align-center" data-align="center">17</td><td class="has-text-align-center" data-align="center">289.4791</td><td class="has-text-align-center" data-align="center">289</td></tr><tr><td class="has-text-align-center" data-align="center">19</td><td class="has-text-align-center" data-align="center">360.8756</td><td class="has-text-align-center" data-align="center">361</td></tr></tbody></table><figcaption>Table 2: Few examples of testing inference</figcaption></figure>
</div></div>



<p class="has-text-align-left">Figure 2: Fitting y = X<sup>2</sup> | test-set</p>
</div></div>



<p>If we increase the number of the hidden neurons from 100 to 10000 we can see a steady improvement in ANN&#8217;s ability to predict the unseen odd numbers.</p>



<figure class="wp-block-gallery columns-3 is-cropped wp-block-gallery-1 is-layout-flex wp-block-gallery-is-layout-flex"><ul class="blocks-gallery-grid"><li class="blocks-gallery-item"><figure><img loading="lazy" decoding="async" width="560" height="420" src="https://www.brainxyz.com/wp-content/uploads/2020/09/1000N.png" alt="" data-id="1664" data-full-url="https://www.brainxyz.com/wp-content/uploads/2020/09/1000N.png" data-link="https://www.brainxyz.com/?attachment_id=1664" class="wp-image-1664" srcset="https://www.brainxyz.com/wp-content/uploads/2020/09/1000N.png 560w, https://www.brainxyz.com/wp-content/uploads/2020/09/1000N.png 300w" sizes="(max-width: 560px) 100vw, 560px" /><figcaption class="blocks-gallery-item__caption">neurons = 1000</figcaption></figure></li><li class="blocks-gallery-item"><figure><img loading="lazy" decoding="async" width="560" height="420" src="https://www.brainxyz.com/wp-content/uploads/2020/09/10000N.png" alt="" data-id="1663" data-full-url="https://www.brainxyz.com/wp-content/uploads/2020/09/10000N.png" data-link="https://www.brainxyz.com/?attachment_id=1663" class="wp-image-1663" srcset="https://www.brainxyz.com/wp-content/uploads/2020/09/10000N.png 560w, https://www.brainxyz.com/wp-content/uploads/2020/09/10000N.png 300w" sizes="(max-width: 560px) 100vw, 560px" /><figcaption class="blocks-gallery-item__caption">neurons = 10,000</figcaption></figure></li><li class="blocks-gallery-item"><figure><img loading="lazy" decoding="async" width="560" height="420" src="https://www.brainxyz.com/wp-content/uploads/2020/09/100000N.png" alt="" data-id="1662" data-full-url="https://www.brainxyz.com/wp-content/uploads/2020/09/100000N.png" data-link="https://www.brainxyz.com/?attachment_id=1662" class="wp-image-1662" srcset="https://www.brainxyz.com/wp-content/uploads/2020/09/100000N.png 560w, https://www.brainxyz.com/wp-content/uploads/2020/09/100000N.png 300w" sizes="(max-width: 560px) 100vw, 560px" /><figcaption class="blocks-gallery-item__caption">neurons = 100,000</figcaption></figure></li></ul><figcaption class="blocks-gallery-caption">Figure 3: shows the effect of increasing the size of the hidden layer on ANN&#8217;s interpolation and extrapolation capabilities</figcaption></figure>



<p>Although increasing the number of hidden neurons improves the ANN&#8217;s capability for both interpolation and extrapolation, the network still fails to extrapolate values that are far from the training range. This suggests that &#8216;power rule&#8217; cannot be modeled by ANN no matter how much is the size of our hidden layer. This is understandable because the weighted summation of the inputs (i.e the dot product) cannot model the multiplication process among the inputs, it can only approximate it for a specific range. </p>



<p>It is also worth noting that the interpolation ability of ANNs remains very good, even if we increase the step size (i.e the gap) between the training set numbers (Figure 4).</p>



<figure class="wp-block-gallery columns-3 is-cropped wp-block-gallery-2 is-layout-flex wp-block-gallery-is-layout-flex"><ul class="blocks-gallery-grid"><li class="blocks-gallery-item"><figure><img loading="lazy" decoding="async" width="560" height="420" src="https://www.brainxyz.com/wp-content/uploads/2020/09/gap4.png" alt="" data-id="1674" data-full-url="https://www.brainxyz.com/wp-content/uploads/2020/09/gap4.png" data-link="https://www.brainxyz.com/?attachment_id=1674" class="wp-image-1674" srcset="https://www.brainxyz.com/wp-content/uploads/2020/09/gap4.png 560w, https://www.brainxyz.com/wp-content/uploads/2020/09/gap4.png 300w" sizes="(max-width: 560px) 100vw, 560px" /><figcaption class="blocks-gallery-item__caption">step = 4</figcaption></figure></li><li class="blocks-gallery-item"><figure><img loading="lazy" decoding="async" width="560" height="420" src="https://www.brainxyz.com/wp-content/uploads/2020/09/gap8.png" alt="" data-id="1673" data-full-url="https://www.brainxyz.com/wp-content/uploads/2020/09/gap8.png" data-link="https://www.brainxyz.com/?attachment_id=1673" class="wp-image-1673" srcset="https://www.brainxyz.com/wp-content/uploads/2020/09/gap8.png 560w, https://www.brainxyz.com/wp-content/uploads/2020/09/gap8.png 300w" sizes="(max-width: 560px) 100vw, 560px" /><figcaption class="blocks-gallery-item__caption">step = 8</figcaption></figure></li><li class="blocks-gallery-item"><figure><img loading="lazy" decoding="async" width="560" height="420" src="https://www.brainxyz.com/wp-content/uploads/2020/09/gap12.png" alt="" data-id="1672" data-full-url="https://www.brainxyz.com/wp-content/uploads/2020/09/gap12.png" data-link="https://www.brainxyz.com/?attachment_id=1672" class="wp-image-1672" srcset="https://www.brainxyz.com/wp-content/uploads/2020/09/gap12.png 560w, https://www.brainxyz.com/wp-content/uploads/2020/09/gap12.png 300w" sizes="(max-width: 560px) 100vw, 560px" /><figcaption class="blocks-gallery-item__caption">step = 12</figcaption></figure></li></ul><figcaption class="blocks-gallery-caption">Figure 4: shows the effect of increasing the size of the step (gap) in-between the training data on ANN&#8217;s interpolation capability</figcaption></figure>



<h6 class="wp-block-heading"><strong>We can draw the following conclusions from our results above:</strong></h6>



<ul class="wp-block-list"><li>ANNs can fit the training set of our non-linear function, <strong>y = X<sup>2</sup></strong>, very well. </li><li>ANNs can fit the testing set of the function above provided that the test data are within the range of the training set, i.e ANNs are good at interpolation.</li><li>ANNs can interpolate the unseen data well even if the gaps between the training data are big.</li><li>ANNs are bad at fitting the test data that are far outside the range of the training set.</li><li>Increasing the number of neurons in the hidden layer improves both interpolation and extrapolation capabilities of the ANNs, however, the power rule cannot be modeled no matter how large the hidden layer is. The power rule can only be approximated within the specific range.</li></ul>



<p></p>



<p>The last point is an important distinction between how ANNs learn to generalize and how we humans learn to generalize. However, the way we present the data to the ANNs might be important. For example, in deep learning, the data are usually presented as one-hot encoding which treats the samples as discrete categories instead of continuous values. Some new deep learning architectures like Transformers (e.g GPT-3) are shown to produce coherent text and generate compelling answers to questions suggesting there might be some rule learning capabilities. To our knowledge, GPT-3 was also bad at learning &#8216;multiplication&#8217; (<a rel="noreferrer noopener nofollow" href="https://arxiv.org/abs/2005.14165" target="_blank">GPT-3 paper / Figure 3.10</a>), but good at learning &#8216;addition&#8217; and this sort of behavior resembles very much the behavior of a typical feed-forward ANN such as the one we showed in our example.</p>



<p>Another interesting factor about ANNs is that even though we increased the number of neurons beyond the number of the samples, our network did not suffer from the bad effects of over-fitting. Over-fitting is usually problematic when we have a non-representative training dataset. This usually happens when there is a lot of variance in the data due to the external noise. By external noise, we mean the non-interesting variance that is not part of the data structure itself. People who work with time-series signals that have a low signal to noise ratio (SNR), e.g. EGG and fMRI, usually prefer to use simpler Machine Learning methods such as SVMs and Ridge Regression because over-parameterized ANNs are usually driven toward fitting the external noise instead of the signal (Which is a very bad side effect of over-fitting).</p>



<p>In contrast, in the deep learning world, over-parameterized ANNs seems to be the norm, especially for those working in vision and NLP fields because their training datasets are usually large, representative, and clean. Since the training datasets in those fields are large and include a wide range of structural variation (i.e training datasets are representative of testing datasets), it is no surprise that deep learning networks like CNNs, GANs, and Transformers are capable of learning to classify and generate new variations of interpolate-able unseen data. This is similar to our example where the ANN was able to successfully predict the unseen odd numbers that were within the range of the training set. </p>



<p>In conclusion, we attribute the success of ANNs in vision and NLP fields to their good interpolation capability, especially when they are fed with large and representative training datasets. We also argue that rule learning and extrapolation beyond the training range are ANNs&#8217; weak points.</p>



<p>At Brainxyz, our focus is on learning algorithms that are capable to learn and generalize in a controllable manner. We also aim for biological plausibility and efficiency. In the future articles, we will test and compare PHUN, our in-progress novel ML algorithm, with ANNs and other ML types. Please stay tuned with us. </p>



<h6 class="wp-block-heading"><strong>Abbreviations:</strong></h6>



<ul class="wp-block-list"><li>ML: Machine Learning</li><li>ANNs: Artificial Neural Networks</li><li>CNN: Convolution al Neural Networks</li><li>SVMs: Support Vector Machine</li><li>GANs: Generative Adversarial Networks</li><li>GPT-3: Generative Pre-Training</li><li>NLP: Natural Language Processing</li><li>PHUN: Predictive Hebbian Unified Neurons.</li><li>fMRI: Functional Magnetic Resonance</li><li>EEG: ElectroEncephaloGram</li></ul>



<p></p>The post <a href="https://www.brainxyz.com/machine-learning/ann/">Artificial Neural Networks | Interpolation vs. Extrapolation</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.<p>The post <a href="https://www.brainxyz.com/machine-learning/ann/">Artificial Neural Networks | Interpolation vs. Extrapolation</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.brainxyz.com/machine-learning/ann/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1579</post-id>	</item>
		<item>
		<title>Genetic Algorithm vs. Stochastic Gradient Descent</title>
		<link>https://www.brainxyz.com/machine-learning/genetic-algorthim/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=genetic-algorthim</link>
					<comments>https://www.brainxyz.com/machine-learning/genetic-algorthim/#respond</comments>
		
		<dc:creator><![CDATA[Brainxyz]]></dc:creator>
		<pubDate>Tue, 01 Sep 2020 21:48:56 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[backpropagation]]></category>
		<category><![CDATA[genetic algorithm]]></category>
		<category><![CDATA[gradient descent]]></category>
		<category><![CDATA[neural network]]></category>
		<guid isPermaLink="false">https://www.brainxyz.com/?p=1401</guid>

					<description><![CDATA[<p>Genetic Algorithm (GA) and Stochastic Gradient Descent (SGD) are well-known optimization methods and are used for learning in Neural Networks. There are various implementations of GA, however, most of them (e.g. Neat) are not directly comparable to SGD because these GA methods use point/localized mutations in their connections/weights. Geoffrey Hinton, in one of his videos...</p>
<p>The post <a href="https://www.brainxyz.com/machine-learning/genetic-algorthim/">Genetic Algorithm vs. Stochastic Gradient Descent</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
<p>The post <a href="https://www.brainxyz.com/machine-learning/genetic-algorthim/">Genetic Algorithm vs. Stochastic Gradient Descent</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p></p>



<p>Genetic Algorithm (GA) and Stochastic Gradient Descent (SGD) are well-known optimization methods and are used for learning in Neural Networks. There are various implementations of GA, however, most of them (e.g. Neat) are not directly comparable to SGD because these GA methods use point/localized mutations in their connections/weights. Geoffrey Hinton, in one of his videos (Lecture 3.4), mentioned that GA randomly perturbs one weight at a time. This makes GA very inefficient compared to backpropagation. In this article, we show that GA can learn efficiently if we mutate all the weights simultaneously provided that we choose a suitable mutation rate (similar to SGD which requires a suitable learning rate to work properly). </p>



<p>We cannot fairly compare learning methods that use localized mutations to SGD because in SGD all the weights within each layer are updated simultaneously making it more efficient. Also, a fair comparison between GA and SGD should use identical Neural Network architectures where the only difference is in the optimization step. Hence, we present a conceptually simple GA implementation that is closely comparable with SGD. In this implementation, instead of making a point or a localized mutation, we mutate all the network weights at once by adding a small random value to each weight. To implement this method, all you need to do is to follow these simple steps:</p>



<ol class="wp-block-list">
<li>Implement a feed-forward Neural Network (just like you do for an SGD based Neural Network).</li>



<li>In the weight update step, mutate all the weights by adding a small random value to each weight.</li>



<li>Do feed-forward propagation twice, one with the mutated weights (child weights) and another with the original weights (parent weights).</li>



<li>Compare the performance of the parent weights to the child weights and keep the better ones for the next generation cycle.</li>



<li>Repeat steps from 2 to 4 until you reach convergence.</li>
</ol>



<p></p>



<p>Complete python implementation of the above algorithm is less than a page long. You can find it at the end of this article which is a complete example that solves the XOR problem. This implementation is not canonical GA as it does not feature terms like chromosomes, crossover,&#8230;etc. However, conceptually, it is very truthful to the evolutionary principles and strips GA down to its bare minimum.</p>



<p>The following images are comparisons between GA and SGD. We chose a function that has an interesting error map with a narrow groove toward the global minimum to showcase a more interesting comparison. As you can see (Figure1-A), GA follows the path toward the global minimum like a drunken man and that is because GA is a stochastic method. What makes GA capable to reach the target is the selection method which we described in point 4 above. The selected (good) mutations are shown in Figure1-B. In contrast, SGD based optimization follows a strict rule. It steps toward the steepest descent even if the step is not in the direction of the global minimum. This, in some cases, makes learning slow or even unstable if we do not choose the learning rate carefully (Figure 2).</p>



<figure class="wp-block-gallery has-nested-images columns-default is-cropped wp-block-gallery-3 is-layout-flex wp-block-gallery-is-layout-flex">
<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1000" height="1000" data-id="1458" src="https://www.brainxyz.com/wp-content/uploads/2020/08/ga1.png" alt="" class="wp-image-1458" srcset="https://www.brainxyz.com/wp-content/uploads/2020/08/ga1.png 1000w, https://www.brainxyz.com/wp-content/uploads/2020/08/ga1.png 300w, https://www.brainxyz.com/wp-content/uploads/2020/08/ga1.png 150w, https://www.brainxyz.com/wp-content/uploads/2020/08/ga1.png 768w" sizes="(max-width: 1000px) 100vw, 1000px" /><figcaption class="wp-element-caption">A) GA &#8211; All mutations are shown</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1000" height="1000" data-id="1404" src="https://www.brainxyz.com/wp-content/uploads/2020/08/ga2.png" alt="" class="wp-image-1404" srcset="https://www.brainxyz.com/wp-content/uploads/2020/08/ga2.png 1000w, https://www.brainxyz.com/wp-content/uploads/2020/08/ga2.png 300w, https://www.brainxyz.com/wp-content/uploads/2020/08/ga2.png 150w, https://www.brainxyz.com/wp-content/uploads/2020/08/ga2.png 768w" sizes="(max-width: 1000px) 100vw, 1000px" /><figcaption class="wp-element-caption">B) GA &#8211; Only good mutations are shown</figcaption></figure>
<figcaption class="blocks-gallery-caption wp-element-caption">Figure 1: Shows the steps of GA toward the global error minimum (deep blue area)</figcaption></figure>



<figure class="wp-block-gallery has-nested-images columns-default is-cropped wp-block-gallery-4 is-layout-flex wp-block-gallery-is-layout-flex">
<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1000" height="1000" data-id="1459" src="https://www.brainxyz.com/wp-content/uploads/2020/08/sgd_small.png" alt="" class="wp-image-1459" srcset="https://www.brainxyz.com/wp-content/uploads/2020/08/sgd_small.png 1000w, https://www.brainxyz.com/wp-content/uploads/2020/08/sgd_small.png 300w, https://www.brainxyz.com/wp-content/uploads/2020/08/sgd_small.png 150w, https://www.brainxyz.com/wp-content/uploads/2020/08/sgd_small.png 768w" sizes="(max-width: 1000px) 100vw, 1000px" /><figcaption class="wp-element-caption">A) SGD &#8211; learning rate: 0.001</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1000" height="1000" data-id="1406" src="https://www.brainxyz.com/wp-content/uploads/2020/08/sgd.png" alt="" class="wp-image-1406" srcset="https://www.brainxyz.com/wp-content/uploads/2020/08/sgd.png 1000w, https://www.brainxyz.com/wp-content/uploads/2020/08/sgd.png 300w, https://www.brainxyz.com/wp-content/uploads/2020/08/sgd.png 150w, https://www.brainxyz.com/wp-content/uploads/2020/08/sgd.png 768w" sizes="(max-width: 1000px) 100vw, 1000px" /><figcaption class="wp-element-caption">B) SGD &#8211; learning rate 0.003</figcaption></figure>
<figcaption class="blocks-gallery-caption wp-element-caption">Figure 2: Shows SGD steps toward the global minimum and its sensitivity to the learning rate which makes SGD flows a zigzag path. In this, case learning rates more than 0.005 fails to converge (diverge instead)</figcaption></figure>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<p>In general, GA based methods can reach the minima in a similar amount of steps to that of a naive SGD given that we choose a suitable mutation rate. </p>



<p>Another interesting point about the GA method we presented here is its simplicity and generality. In fact, the above method can be used for reinforcement learning with minimal modification, unlike SGD based methods where reinforcement learning requires conceptually different learning strategies and different implementations to make them work. Here we used GA to balance the Open AI&#8217;s gym Cartpole in 60 generations (Figure 3). All we did this time, differently, is to select the winning parent/child network at the end of each episode. The complete code implementation can be found at the end of this article. Please note that these GA methods are sensitive to the initial weights, some initialization converges faster than others and some initialization even fails to converge (this is true for SGD based learning too).</p>
</div></div>



<p></p>



<figure class="wp-block-gallery has-nested-images columns-default is-cropped wp-block-gallery-5 is-layout-flex wp-block-gallery-is-layout-flex">
<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="600" height="400" data-id="1462" src="https://www.brainxyz.com/wp-content/uploads/2020/08/after-learning-1.gif" alt="" class="wp-image-1462"/></figure>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="640" height="476" data-id="1463" src="https://www.brainxyz.com/wp-content/uploads/2020/08/GA_performance2.png" alt="" class="wp-image-1463" srcset="https://www.brainxyz.com/wp-content/uploads/2020/08/GA_performance2.png 640w, https://www.brainxyz.com/wp-content/uploads/2020/08/GA_performance2.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>
<figcaption class="blocks-gallery-caption wp-element-caption">Figure 3: Open AI&#8217;s gym Cartpole balanced by a GA trained Neural Network. </figcaption></figure>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<p></p>
</div></div>



<h6 class="wp-block-heading">Advantages of GA:</h6>



<ul class="wp-block-list">
<li>In a single iteration, the GA method described here needs two feed-forward propagations while the SGD method needs a feed-forward + a feed-backward propagation which is computationally more demanding.</li>



<li>Although we admit that a carefully optimized SGD method can reach the minima with fewer iterations, GA is a more parallelize-able method. Both GA and SGD are embarrassingly parallel in terms of matrix multiplications within each layer. However, with GA you can breed more than one child in parallel and select the best one. This can ultimately make GA reach the minima faster than SGD given that you have enough computational power to breed a massive number of children in parallel. </li>



<li>GA is a general-purpose learning method. It can be used for reinforcement learning, supervised learning, and feedback learning, all with minimal modification in its implementation.</li>



<li>The weight update rule we presented here is so simple making this method easy to implement in very complex network architectures that have feedback and sideway connections among its neurons.</li>



<li>GA can work with non-differentiable functions while SGD cannot.</li>
</ul>



<p></p>
</div></div>



<h6 class="wp-block-heading">Disadvantages of GA:</h6>



<ul class="wp-block-list">
<li>GA based methods generally require more iterations to reach the minima compared to well-optimized SGD based methods.</li>



<li>If the mutation rate is high, learning becomes unpredictable and noisy. If the mutation rate is low, learning becomes slow and can stick in local minima.</li>



<li>Bad performance for high dimensional and complex data patterns (this needs further investigation especially with CNN architecture which we have not investigated here).</li>



<li>GA is a population-based learning, therefore, we cannot take inspirations from this method to find more about the learning method used by our brains.</li>
</ul>



<p></p>



<p>At Brainxyz, our main focus is not GA neither SGD because these methods are iterative in nature and are not suitable for real-time learning. We are currently working on Predictive Hebbian Unified Neurons (PHUN) which is a real-time learning algorithm. In the future, we will put more comparisons between various learning algorithms including PHUN, so please stay tuned with us.</p>



<p>Finally for those interested, here is a complete python code for solving the Xor problem using the GA method described in this article. The code only uses numpy library and its just a few lines of code! Conceptually, It cannot get any simpler than this. </p>



<pre class="wp-block-code"><code>import numpy as np
import matplotlib.pyplot as plt

## net structure and initialization (single layer neural network)
inp = 2; hidden = 5; out = 1;
mutation_rate = 0.03
w1 = np.random.uniform(-1,1, (inp, hidden))
w2 = np.random.uniform(-1,1, (hidden, out))

def feedforward(X, w1, w2):
    # feed forward propagation here it uses tanh as activation (can be sigmoid).
    z = np.tanh(X @ w1)
    yh = z @ w2
    return yh

def mutate(w, mutation_rate):
    # mutate the weights by adding small random values to them
    dw = np.random.uniform(-1,1, (w.shape)) * mutation_rate
    m_w = w + dw
    return m_w
       
def train(X, y, w1, w2, iterations):
    errs = &#91;]
    for i in range(iterations):
        
        m_w1 = mutate(w1, mutation_rate) #mutate input-hidden weights
        m_w2 = mutate(w2, mutation_rate) #mutate hidden-output weights
        
        yh1 = feedforward(X,   w1,   w2); #parent network
        yh2 = feedforward(X, m_w1, m_w2); #child network (mutated weights)
        
        err_parent = np.sum(np.abs(y - yh1.ravel())); #evaluate parent
        err_child =  np.sum(np.abs(y - yh2.ravel())); #evaluate child 
        
        if(err_child &lt; err_parent): # select better
            w1 = m_w1;
            w2 = m_w2;   
            
        errs.append(err_child)        
    return errs, w1, w2

## usage example: XOR data
X=np.asarray(&#91;&#91;0,0],&#91;1,1],&#91;0,1],&#91;1,0]]);
y=np.asarray(&#91;0,0,1,1]);

iterations = 1000 
errs, m_w1, m_w2 = train(X, y, w1, w2, iterations)

## check the results  
yhat = feedforward(X, m_w1, m_w2) 
print('actual:', y)
print('prediction:', yhat.ravel())      
plt.figure(1)
plt.plot(errs)
plt.title('errors')</code></pre>



<div class="wp-block-media-text has-media-on-the-right is-stacked-on-mobile is-vertically-aligned-center" style="grid-template-columns:auto 52%"><div class="wp-block-media-text__content">
<p><strong>Code output:</strong></p>



<p>actual: [0 0 1 1]<br>prediction: [0. 0.0023 1.0048 1.0047]</p>
</div><figure class="wp-block-media-text__media"><img loading="lazy" decoding="async" width="640" height="476" src="https://www.brainxyz.com/wp-content/uploads/2020/09/Figure_2.png" alt="" class="wp-image-1508 size-full" srcset="https://www.brainxyz.com/wp-content/uploads/2020/09/Figure_2.png 640w, https://www.brainxyz.com/wp-content/uploads/2020/09/Figure_2.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure></div>



<p>In the GitHub link below, you can find a more sophisticated implementation of the above code using object oriented programming principles. We also implemented additional flexibility for adding more layers and neurons to solve both Cartpole and XOR problems. <a rel="noreferrer noopener" href="https://github.com/hunar4321/Genetic_Algorithm" target="_blank">https://github.com/hunar4321/Genetic_Algorithm</a></p>



<h6 class="wp-block-heading"><strong>Edit (follow up):</strong></h6>



<ul class="wp-block-list">
<li>This is not a &#8220;State of Art&#8221; implementation of GA. It is a toy example showcasing a specific comparison between the bare minimum versions of GA and SGD. Many scientists including deep learning pioneers like Yoshua Bengio encourage using toy examples because they can give valuable insights.</li>



<li>SGD based methods benefit greatly from momentum and adaptive learning. However, theoretically, GA based methods can enjoy these additions too, e.g. using momentum to accelerate toward good mutations.</li>
</ul>



<p></p>



<p>I also briefly explained this algorithm in the video below at 21:50 timestamp:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="What Is Intelligence?" width="720" height="405" src="https://www.youtube.com/embed/HiXUNNbPDH4?start=1309&#038;feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div></figure>



<p></p>The post <a href="https://www.brainxyz.com/machine-learning/genetic-algorthim/">Genetic Algorithm vs. Stochastic Gradient Descent</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.<p>The post <a href="https://www.brainxyz.com/machine-learning/genetic-algorthim/">Genetic Algorithm vs. Stochastic Gradient Descent</a> appeared first on <a href="https://www.brainxyz.com">Brainxyz</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.brainxyz.com/machine-learning/genetic-algorthim/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1401</post-id>	</item>
	</channel>
</rss>
