<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexander Kovalenko on Medium]]></title>
        <description><![CDATA[Stories by Alexander Kovalenko on Medium]]></description>
        <link>https://medium.com/@kovalenko.alx?source=rss-81af05500d58------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*jeJHDQ6tzL--3G9Sk5Xn_Q.jpeg</url>
            <title>Stories by Alexander Kovalenko on Medium</title>
            <link>https://medium.com/@kovalenko.alx?source=rss-81af05500d58------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:06:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kovalenko.alx/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is the connection between a World Model, Schrödinger’s Cat, and Neural Network?]]></title>
            <link>https://pub.towardsai.net/what-is-the-connection-between-a-world-model-schr%C3%B6dingers-cat-and-neural-network-a94b25d1d8c5?source=rss-81af05500d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/a94b25d1d8c5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[schrodinger]]></category>
            <category><![CDATA[pinn]]></category>
            <category><![CDATA[differential-equations]]></category>
            <dc:creator><![CDATA[Alexander Kovalenko]]></dc:creator>
            <pubDate>Sun, 04 Sep 2022 12:13:54 GMT</pubDate>
            <atom:updated>2023-01-15T16:51:00.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Is the Connection Between a World Model, Schrödinger’s Cat, and Neural Networks?</h3><h4>Using Physics-Informed Neural Network (PINN) to solve famous Schrödinger Equation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzzgELHEq0WLB8G2W3P-fw.jpeg" /><figcaption><a href="https://cdn.pixabay.com/photo/2018/12/09/09/29/physics-3864569_1280.jpg">source</a></figcaption></figure><p>For centuries, curious minds have been trying to crack the structure of the world around us. Most would agree that any branch of science follows the same goal — trying to map a function to the observations. This function, which somehow explains the world model by an approximation, can be either continuous or discrete and is meant to find a correspondence between the input and output sets.</p><p>The search for a function that describes the world model can be tricky without any prior knowledge. However, we know that the world around us is complex and dynamic. Complex models can be represented by <a href="https://www.wolframphysics.org/visual-summary/dark/">simple rules</a>, so there might be a walkaround. 😅 Nevertheless, as things tend to evolve in time and space, the dynamic aspect of the ever-changing world can’t be simply ignored.</p><blockquote>“Something can only ever be explained by taking something else for granted”</blockquote><blockquote>Richard Feynmann</blockquote><p>Dynamics can be described through a derivative that measures the sensitivity of the function output with respect to changes in the input. At the same time, the relation between the function and its derivative is defined in a form of a <a href="https://en.wikipedia.org/wiki/Differential_equation">differential equation</a>. Therefore, it’s a no-brainer that many phenomena in physics, <a href="http://www.civil.uwaterloo.ca/xie/Graphics/XIE_Differential%20Equations%20for%20Engineers_excerpt.pdf">engineering</a>, <a href="https://u.math.biu.ac.il/~shnider/Course_Notes/ODE-economics-chap1.pdf">economics</a>, <a href="https://www.cambridge.org/cz/academic/subjects/mathematics/mathematical-modelling-and-methods/modeling-differential-equations-biology-2nd-edition?format=AR&amp;isbn=9781316040355">biology</a>, <a href="https://europepmc.org/article/med/28329860">psychology</a>, and whatnot can be successfully modeled by using differential equations of any type. Differential equations can be used to calculate the movement or flow of electricity or heat, the motion of an object, or even to check the growth of diseases. Needless to say, the whole <a href="https://en.wikipedia.org/wiki/Backpropagation">backpropagation algorithm</a> can be seen as a differential equation, where the partial derivatives of the error are calculated with respect to weights, using the chain rule.</p><p>On the one hand, we have an unknown function; on the other hand, its derivative represents the rate of change. The differential equation defines the relationship between the two.</p><p>Even though many of you probably know Erwin Schrödinger by his thought experiment often called “<a href="https://en.wikipedia.org/wiki/Schr%C3%B6dinger&#39;s_cat">Schrödinger’s Cat</a>”, he is foremost known to be one of the godfathers in the field of quantum theory. Schrödinger postulated the equation (which is now called the <a href="https://en.wikipedia.org/wiki/Schr%C3%B6dinger_equation">Schrödinger equation</a>) that governs the <a href="https://en.wikipedia.org/wiki/Wave_function">wave function</a> of a quantum-mechanical system or describes where the quantum particle is.</p><blockquote>One can even set up quite ridiculous cases. A cat is penned up in a steel chamber, along with the following device (which must be secured against direct interference by the cat): in a Geiger counter, there is a tiny bit of radioactive substance, so small, that perhaps in the course of the hour one of the atoms decays, but also, with equal probability, perhaps none; if it happens, the counter tube discharges and through a relay releases a hammer that shatters a small flask of hydrocyanic acid. If one has left this entire system to itself for an hour, one would say that the cat still lives if meanwhile, no atom has decayed. The first atomic decay would have poisoned it. The psi-function of the entire system would express this by having in it the living and dead cat (pardon the expression) mixed or smeared out in equal parts.</blockquote><blockquote>Schrödinger, E. Die gegenwärtige Situation in der Quantenmechanik. Naturwissenschaften 23, 807–812 (1935).</blockquote><p>“Schrödinger equation” is one of the fundamental landmarks in understanding quantum physics and building a clearer picture of the world model. And guess what? This equation is a <strong>linear partial differential equation</strong> as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*Xf8oC-tAfEjeah3sqDok5w.png" /></figure><p>Where Ψ is an unknown wave function we want to find. Before we begin, I have to tell you that there is an uncountable number of particular cases of the Schrödinger equation though many of them are prohibitively complex, and thus they can’t be solved analytically for most atoms. Therefore, let’s now concentrate on one of the simplest cases, which is “The Schrödinger equation’s” solution for “<a href="https://en.wikipedia.org/wiki/Particle_in_a_box"><strong>particle-in-a-box</strong></a>”, which is a nice demonstration of the differences between classical and quantum systems.</p><p>Imagine, our particle is trapped between two infinite potential barriers (this case is sometimes called an <strong>infinite potential well</strong>). The particle is free to move in between the walls, though. Since this is a very restricted case, in fact, a hypothetical toy example, there are ways to simplify our initial expression, resulting in a time-independent Schrödinger equation for a single particle in the box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*kcFplbloRFt-44b6faPXVQ.png" /></figure><p>How do we do that? See the amazing video below explaining how to derive a particular case for a particle-in-a-box and solve it analytically:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLBB39u8dNw0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLBB39u8dNw0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLBB39u8dNw0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/90bd9efea55824d990548577551b70a3/href">https://medium.com/media/90bd9efea55824d990548577551b70a3/href</a></iframe><p>Nevertheless, we ended up with a second-order differential equation. The Ψ function describes the behavior of the particle. Position, momentum, and energy may be derived from the Ψ. If you’ve already watched the video, you already know how to solve it. However, if you haven’t, it might seem that the equation above does not look so complicated. So what is the problem?!</p><p>If we take a closer look, then all we know is that the Ψ(0) = 0, Ψ(a) = 0, and the second derivative of Ψ plus Ψ itself is also zero! However, we know that Ψ is not zero in the interval (0, a).</p><h4>ಠ益ಠ</h4><p>Ok, let’s pull all the knowledge we have, except the equation itself, together:</p><ul><li>Ψ is a function;</li><li>Ψ(0) = 0</li><li>Ψ(a) = 0</li></ul><p>Since Ψ is a function, and we are data scientists, we can leverage the <a href="https://link.springer.com/article/10.1007/BF02551274">universal approximation theorem</a>, which roughly states the following:</p><p><em>Once the number of neurons is sufficient, the feedforward neural network with a non-polynomial activation function can approximate any well-behaved function to any accuracy.</em></p><p>This theorem is valid for both multi- and single-hidden layer neural networks, and basically for any of the modern activation functions (ReLU, GeLU, Sigmoid, Tanh, etc.). Seems like exactly what we need!</p><p>No… Wait… What about the data?!</p><p>Well, we have none. However, there is a way out, called <a href="https://www.brown.edu/research/projects/crunch/sites/brown.edu.research.projects.crunch/files/uploads/Nature-REviews_GK.pdf">Physics Informed Neural Networks</a>, or PINNs. PINNs attracted particular attention recently, mainly due to their ability to model and forecast the dynamics of multiphysics and multiscale real-world systems. Another interesting property of PINNs is that if we are fitting data that should obey some physical law, and we are aware of this law, we can simply add this dependence to the loss function, which makes our machine learning model respect the physical law, i.e. to be physics informed.</p><p>In general, regarding PINNs, we can define three ways we could efficiently train the model:</p><ul><li>lots of data and no physics (what we are all familiar with)</li><li>little data and some physics</li><li>no data and all the physics we have</li></ul><p><strong><em>NB:</em></strong><em> For the sake of simplicity, we are going to omit all the constants in the equation. We’ll assume that k=1, and our quantum well is from 0 to a=10.</em></p><p>Our case is exactly the third one. We have the physical law to follow, but no data. Let’s define the boundary conditions simply as the function that returns zero:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/882499db40fb05d9939bda1c3f641a2d/href">https://medium.com/media/882499db40fb05d9939bda1c3f641a2d/href</a></iframe><p>And since the equation above has no residuals, i.e. all the Ψ containing terms are on the left part, we can define a function for our Schrödinger equation. Simply, it is going to be something that tends to be zero.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0da5fffa5c462ae3e4c9088d060431d9/href">https://medium.com/media/0da5fffa5c462ae3e4c9088d060431d9/href</a></iframe><p>Then, as discussed above, a multilayer perception with non-polynomial nonlinearity should be a good option to approximate our wave function Ψ. Here we used <a href="https://arxiv.org/abs/1606.08415">Gaussian Error Linear Unit</a> nonlinearity as it was found empirically to work slightly better than Sigmoid and Tanh, while ReLU showed the worst performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d3e6d1a68b12bcf122e84c11a972967/href">https://medium.com/media/0d3e6d1a68b12bcf122e84c11a972967/href</a></iframe><p>Consequently, we have to make our model respect Schrödinger’s equation, meaning to be physics informed. This can be achieved by defining the loss function that includes the discrepancy of the whole differential equation and the discrepancy at boundaries:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/138992f8485931f0fc3728fb9049b15a/href">https://medium.com/media/138992f8485931f0fc3728fb9049b15a/href</a></iframe><p>Note that we can calculate the gradients (or simply the derivative of Ψ function psi_x) by using <a href="https://pytorch.org/docs/stable/generated/torch.autograd.grad.html">torch.autograd.grad()</a>, an automatic differentiation function that computes and returns the sum of gradients of outputs with respect to the inputs. To compute the second derivative psi_xx, simply apply grad() function twice.</p><p>Therefore, we can pass boundaries at the walls of the box and data points within the box to calculate the overall loss and then backpropagate the error to update the weights.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/961731a48ca05767935c89f2cebcc351/href">https://medium.com/media/961731a48ca05767935c89f2cebcc351/href</a></iframe><p>After a few thousand iterations, we can take a look at the result. As shown below, the output of our function resembles <a href="https://en.wikipedia.org/wiki/Particle_in_a_box#/media/File:InfiniteSquareWellAnimation.gif">the solution</a> for the particle-in-a-box case. Since we know that the solution for the Schrödinger equation is in fact a family of solutions, the output may vary upon stochastic initialization of weights and training parameters. The complete code can be found <a href="https://github.com/kovalenko-alx/NeuralSchrodinger/blob/main/NeuralSchrodinger.ipynb">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*4WX_l0hLPLi3u8sh3-IqkA.png" /><figcaption>PINN output after 4500 iterations</figcaption></figure><p>Of course, there are many more sophisticated implementations showing how to solve the Schrödinger equation using deep neural networks[<a href="https://www.nature.com/articles/s41598-022-06442-x">1</a>, <a href="https://www.sciencedirect.com/science/article/pii/S0021999119306345">2</a>, <a href="https://lup.lub.lu.se/luur/download?func=downloadFile&amp;recordOId=9059610&amp;fileOId=9059611">3</a>]. On the other hand, this blog post demonstrates a simple and understandable introduction to physics-informed machine learning and gives an idea of when and why we’d like to “inform” our model. The reason I chose Schrödinger’s equation is simple — since the equation itself and boundary conditions are quite restrictive and non very informative (as you remember, zeros were everywhere). The gradient descent algorithm, was able to find a nonzero solution, even though it was not penalized.</p><p>Finally, we can answer the question stated in the blog post title: “What is the connection between a World Model, Schrödinger’s Cat, and Neural Network?”. As we know, many dynamic processes describing the world model can be modeled using differential equations. On the other hand, even very complicated differential equations can be solved with physics-informed neural networks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a94b25d1d8c5" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/what-is-the-connection-between-a-world-model-schr%C3%B6dingers-cat-and-neural-network-a94b25d1d8c5">What is the connection between a World Model, Schrödinger’s Cat, and Neural Network?</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What if Charles Darwin Built a Neural Network?]]></title>
            <link>https://pub.towardsai.net/what-if-charles-darwin-built-a-neural-network-e1d0cadf032e?source=rss-81af05500d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1d0cadf032e</guid>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[evolution]]></category>
            <category><![CDATA[backpropagation]]></category>
            <dc:creator><![CDATA[Alexander Kovalenko]]></dc:creator>
            <pubDate>Thu, 02 Jun 2022 14:29:17 GMT</pubDate>
            <atom:updated>2023-01-16T14:36:25.976Z</atom:updated>
            <content:encoded><![CDATA[<h4>An alternative way to “train” a neural network with evolution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QHGZ8pf6wJ9TfUH_" /><figcaption>Photo by <a href="https://unsplash.com/@moreno303?utm_source=medium&amp;utm_medium=referral">Misael Moreno</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>At the moment, <a href="https://en.wikipedia.org/wiki/Backpropagation">backpropagation</a> is nearly the only way for neural network training. It computes the gradient of the loss function with respect to the weights of the network and consequently updates the weights by backpropagating the error across the network layers using the chain rule.</p><p>Recently, the community has been trying to go beyond backpropagation, as maestro Geoffrey Hinton himself, who popularized the algorithm in the &#39;80s, is now <em>“</em>deeply suspicious<em>” </em>about <a href="https://www.iro.umontreal.ca/~vincentp/ift3395/lectures/backprop_old.pdf">it</a>. His view now is <em>“</em><a href="https://www.axios.com/ai-pioneer-advocates-starting-over-2485537027.html">throw it all away and start again</a><em>”</em>. There are many reasons behind his suspicion. The main one is that our brain does not backpropagate things, as there is no labeled data. We rather label things by ourselves, which this is a completely different story. Many brilliant works have been published at <a href="https://beyondbackprop.github.io/">NeurIPS</a> featuring diverse algorithms, some of which are rather sophisticated. However, we are here not for some hardcore algorithm that looks like an ancient spell to summon the devil but for something simpler. Much simpler. Instead of training our model, we are going to evolve it, just like mother nature did.</p><p>Now, it is time for Charles Darwin to come into the picture. Darwin defined evolution as “descent with modification”. Sounds almost like “gradient descent”, right? 😅 Natural selection, which is a key point of evolution, means that species evolve over time, give rise to new species, and share a common ancestor. In simple words, the <em>most adapted </em>fraction of the population <em>survives</em> and produces the slightly altered (i.e., <em>mutated</em>) offspring. Then, this process repeats over and over for a long time… How long? For example, in the case of the planet Earth, it took 4.543 billion years. This concept is well-adapted in computer science and is called a genetic or <a href="https://en.wikipedia.org/wiki/Evolutionary_algorithm">evolutionary algorithm</a>.</p><p>Given a large population, starting at random, evolution can emerge with surprisingly good results. Likewise, “<a href="https://en.wikipedia.org/wiki/Infinite_monkey_theorem">The infinite monkey theorem</a>”, states that a monkey, given an infinite amount of time, will almost surely type some meaningful text, say, William Shakespeare’s Hamlet.</p><blockquote>“Let us suppose that a million monkeys have been trained to type at random, and that these typing monkeys work hard for ten hours a day with a million typewriters of various types. After a year, results of their work would contain exact copies of the books of all kinds and languages held in the richest libraries of the world”</blockquote><blockquote>Émile Borel, 1913, Journal de Physique</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R1wTnNT_Qmwt_roW" /><figcaption>Photo by <a href="https://unsplash.com/@syedabsarahmad?utm_source=medium&amp;utm_medium=referral">Syed Ahmad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How do we extrapolate this idea to neural network training? Just imagine that we started with a bunch of random nets. They can vary in terms of <a href="https://arxiv.org/pdf/1810.03522.pdf">architecture</a>, weight, or any other parameters. Then we have to check how they do the job, choose a small chunk that performs the best, and do some small modifications (which is called “<a href="https://en.wikipedia.org/wiki/Mutation_(genetic_algorithm)">mutation</a>”) to their parameters. Since we are talking about backpropagation alternatives, here, the goal will be to find the best weights and biases for the neural network without a “traditional” way to train it.</p><p>No backpropagation, no gradient descent - no problems!</p><p>First, let’s make our lives easier by creating a neural net utilizing the PyTorch library. For simplicity, we’ll take a feed-forward neural network with a single hidden layer and <em>evolve</em> it for a simple task - handwritten digits recognition, which we all know as the <a href="http://yann.lecun.com/exdb/mnist/">MNIST</a> dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/634c6a17e9d539e8970bae1a015852e3/href">https://medium.com/media/634c6a17e9d539e8970bae1a015852e3/href</a></iframe><p>Now, to make the model work, we have to initialize weights and biases, thus let’s create a function that takes a model and trainable parameters and puts them all together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f65c2d0d62d9086bfd6b486db5bce85/href">https://medium.com/media/4f65c2d0d62d9086bfd6b486db5bce85/href</a></iframe><p>Then, we need the so-called <a href="https://en.wikipedia.org/wiki/Fitness_function#:~:text=A%20fitness%20function%20is%20a,simulations%20towards%20optimal%20design%20solutions.">fitness function</a>, which according to good old Wikipedia, is:</p><blockquote>a particular type of <a href="https://en.wikipedia.org/wiki/Objective_function">objective function</a> that is used to summarise, as a single <a href="https://en.wikipedia.org/wiki/Figure_of_merit">figure of merit</a>, how close a given design solution is to achieving the set aims.</blockquote><p>At first, let’s use the standard PyTorch test function without mini-batches, as we don’t need them anymore:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7347899570eb03ab933711725074f4e9/href">https://medium.com/media/7347899570eb03ab933711725074f4e9/href</a></iframe><p>Therefore, it is the so-called fitness function that we have to maximize. As it returns the accuracy, maximizing fitness function sounds like a plan!</p><p>To test the model, we, however, need some input which would be a population of random neural network parameters. Therefore, first, we need to create the population by simply generating many pseudorandom normally distributed tensors of a certain shape, with a little normalization tweak meant to avoid very large parameters, which is simply multiplying the weights and biases by 0.1.</p><p>Let’s do it as a list of Python tuples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd52df76a0ad6e89687d677b7da70c12/href">https://medium.com/media/cd52df76a0ad6e89687d677b7da70c12/href</a></iframe><p>Here, every tuple contains the following:</p><ul><li>weights of the hidden layer</li><li>weights of the output layer</li><li>biases of the hidden layer</li><li>biases of the output layer</li></ul><p>Now, once we have 100 different solutions, we can feed them to the model, evaluate them, and choose a bunch (let’s say 10) of the best ones. Then we <em>mutate</em> the solutions a bit, which was mentioned above as mutation, and create a new generation, which is simply <em>N</em> new solutions randomly picked from the top of the previous generation and slightly <em>mutated.</em></p><p>However, here we use a little change to the original implementation of the algorithm. First, as we started with a small population of 100, let us allow the population to grow with every generation by some number. This is just a trick for faster convergence and better results over time.</p><p>The second trick is that, once in a while (say 20% of all the cases), we allow random initialization from scratch. Thus, even though we pick the top 10 solutions to create a new generation, there is still a chance for Albert Einstein to be born! Consequently, if they are there, those Einsteins can be picked and further mutated to create a new and better generation. The overall code cycle looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b657bc4275db908977399688b0362b7/href">https://medium.com/media/7b657bc4275db908977399688b0362b7/href</a></iframe><p>To sum up, our slightly improved evolutionary algorithm does the following:</p><ul><li>randomly generates 100 sets of parameters for a given neural network architecture</li><li>picks the best 10 of them</li><li>randomly<em> slightly</em> mutates the top 10 and creates a new, slightly larger than a previous, population, with a 20% chance of completely random initialization</li><li>repeats until it takes over the world!</li></ul><p>And… voila! Our DarwinNet is ready! When it runs for 200 generations, it gives over 25% accuracy for the MNIST dataset on the test set. Not the best performance, however, a random guess would give 10% accuracy, so it is clearly doing something, as you can see in the figure below. The complete code can be found <a href="https://github.com/kovalenko-alx/DarwinNet">here</a>. As mentioned above, adding a 20% chance of random initialization helps to improve the performance drastically, which corresponds to the characteristic “steps” on the plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*ORms8z9AzpYPM-ItC1sDRA.png" /></figure><p>This post demonstrates how a genetic algorithm can be used to “train” the model on one of the benchmark datasets. Bear in mind that the code was written between office sword fights and coffee; there are no big ambitions here. Nevertheless, there are dozens of ways how to attain higher performance by different weight initialization, changing mutation rate, number of parents for each generation, number of generations, etc. Moreover, we can use our prior comprehension of neural networks and inject expert knowledge, i.e., pick the initial weights of the model using <a href="https://arxiv.org/pdf/1502.01852.pdf">Kaiming initialization</a>. This probably won’t help, but you’ve got the point, right? 😃</p><p>Of course, the idea of training neural networks using an evolutionary algorithm is not new. There are at least two papers by <a href="https://www.ijcai.org/Proceedings/89-1/Papers/122.pdf">D. J. Montana &amp; L. Davis</a> and <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=140281&amp;tag=1">S. J. Marshall &amp; R. F. Harrison</a> from the last century sharing this idea, where they show genetic algorithm superiority over the backdrop. However, whatever happened happened. Nowadays, backpropagation-related attributes are fine-tuned to do their best, thus, their performance is dominant over genetic algorithms and other non-backprop rival methods eg. <a href="https://link.springer.com/referenceworkentry/10.1007%2F978-1-4614-7320-6_672-1">Hebbian learning</a> or <a href="https://papers.nips.cc/paper/2003/file/f8b932c70d0b2e6bf071729a4fa68dfc-Paper.pdf">perturbation learning</a>.</p><p>Another issue with the present implementation: it takes time… Well, maybe if it ran for over 4 billion years, the result would be better. 🙃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1d0cadf032e" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/what-if-charles-darwin-built-a-neural-network-e1d0cadf032e">What if Charles Darwin Built a Neural Network?</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bias-Variance Decomposition IRL]]></title>
            <link>https://medium.com/@kovalenko.alx/bias-variance-decomposition-irl-333f1c13adf8?source=rss-81af05500d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/333f1c13adf8</guid>
            <category><![CDATA[bias-variance-tradeoff]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <dc:creator><![CDATA[Alexander Kovalenko]]></dc:creator>
            <pubDate>Fri, 06 Mar 2020 14:03:10 GMT</pubDate>
            <atom:updated>2020-08-06T17:30:05.509Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bias-Variance Decomposition Made Simple</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNxP0j6XuniN54vsnFkbeQ.jpeg" /><figcaption><a href="https://www.1zoom.me/en/wallpaper/486787/z2533.6/1920x1080">https://www.1zoom.me/en/wallpaper/486787/z2533.6/1920x1080</a></figcaption></figure><p>Well, I believe that most of you, who was once interested in bias-variance trade-off or bias-variance decomposition have may already come across some of the famous ‘overfitting-underfitting’ curves or ‘high-bias low-variance’ etc. targets. If no — just google it… There is nothing wrong with these images, however, they just give a general understanding of the problem without much practical experience.</p><blockquote>“The future depends on some graduate student who is deeply suspicious of everything I have said”</blockquote><blockquote>Geoffrey Hinton</blockquote><p>To be in the picture:</p><ul><li>variance is how the obtained results are different from each other, which simply means dispersion around the mean output value</li><li>bias is how the network performance is ‘biased’, i.e. how the output is shifted from the true values</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BXMmOdy0CTReDnmS.jpeg" /><figcaption><a href="https://miro.medium.com/max/1075/1*10t9S7xvWE5Z3NEZrmHG2w.jpeg">https://miro.medium.com/max/1075/1*10t9S7xvWE5Z3NEZrmHG2w.jpeg</a></figcaption></figure><p>A cool thing that the output of each individual network in the ensemble can be observed separately, thus a weighted ensemble average can be denoted as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*zO15osDQ4wwM88i2" /></figure><p>Note that I use a fancy term “weighted”, however, often ensembles are just</p><p>The ambiguity on input x of a single member of the ensemble is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/0*PJj0VJKT9wM4Nb_N" /></figure><p>Thus the ambiguity of the ensemble can be defined by summing the weighted ambiguities of the ensemble members:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*GlZ0jXUpeXFO_Ldg" /></figure><p>Interestingly, the ensemble ambiguity is nothing less than the variance of the weighted ensemble around the weighed mean, and it measures the disagreement among the networks on input <em>x —</em> simply how the predictions of each individual network in the ensemble <strong>vary from each other</strong>.</p><p>It is worth mentioning, that the variance of the ensemble output is not dependent on the true value, which means that the <strong>variance is a fully unsupervised parameter</strong>.</p><p>Now, let’s take a look at the general error of the neural network. The quadratic error can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/0*JPeRVE5wsWs3lR_U" /></figure><p>Logically, by taking the mean quadratic error across the ensemble outputs we obtain the total error of the ensemble:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/0*qJh-7uNbGyCNlRpB" /></figure><p>In a human language, this means how far is the ensemble mean prediction from the true value.</p><p>Note that even if our ensemble consists of several neural networks with identical architecture due to random weight initialization the resulting performance may vary. Passing non-linear function to the loss function across the layers of the neural network will result in a highly non-convex loss landscape. During the training, optimization is likely to fall into various local minima.</p><p>Thus our equation defining <strong>total error</strong> decomposed into bias and variance components would finally look like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*H8qUNQWovr1AkU5f" /></figure><p>Where the right part of the equation is a total error (becomes capital <em>E</em> after integration) and the left part consists of the weighted average of the generalization errors of the individual networks which -<em> </em><strong>bias</strong> (first term) of the ensemble and the second is the weighted average of the ambiguities or <strong>variance</strong> (second term).</p><p>The beauty of this equation is that it separates the generalization error into a term that depends on the generalization error of the individual networks and another term that contains all correlations between the networks.</p><p>Moreover, as seen above the correlation term can be estimated entirely from unlabelled data, i. e., no knowledge is required of the real function to be approximated.</p><p>From this equation, one can immediately see that the generalization error of the ensemble is always smaller than the (weighted) average of the ensemble errors. Why so? Simply because of the ambiguity being a squared difference between a network prediction and ensemble average that is always positive (unless you managed to get complex numbers, hehe).</p><p>Additionally, if you try to use some math and unwrap the equation above, you’ll get a good old mean squared error (MSE)of the ensemble average. Nice, huh?</p><p>Ok, now you know some math, but how to implement it in the real model? Well, let’s take a look at the code! Since Keras library is now a part of Tensorflow 2.0 we all have a nice excuse to use a high-level library with no remorse.</p><p>Say we have an ensemble consisting of 3 neural networks, so the outputs of each individual net are denoted as x1, x2 and x3 respectively, and the weighted average is y_pred. Thus, for equally weighted ensemble bias would look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a25e99f839ce7e1f1431bdc0088aa365/href">https://medium.com/media/a25e99f839ce7e1f1431bdc0088aa365/href</a></iframe><p>Then we can define variance in the same manner :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c714e4834ff6cd64ada16c438255dcda/href">https://medium.com/media/c714e4834ff6cd64ada16c438255dcda/href</a></iframe><p>Now, you can simply pass your custom metrics to the metrics list, alongside with the default &#39;acc&#39; as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03d011fdb2b9e413f1bcfd8f3de22bc2/href">https://medium.com/media/03d011fdb2b9e413f1bcfd8f3de22bc2/href</a></iframe><p>Now we know, why ensembles ‘always’ perform better than individual neural networks. Moreover, ensembles are usually more robust, they give a better generalization about the data, quite easy to implement and many more other cool stuff about ensembles. So, why don’t you just try to build one and see how it performs in terms of bias-variance decomposition?</p><p>This will allow us to observe the bias and variance of the ensemble output independently during the training. What to do with it? Well, there are ways how to control it, however, it is a totally different story…</p><p><strong>Literature:</strong></p><ul><li>P. Domingos, P. “A unified bias-variance decomposition“ In Proceedings of 17th International Conference on Machine Learning, 2000, pp. 231–238.</li><li>L. K. Hansen and P. Salamon, “Neural network ensembles,” in IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 12, 10, 1990, pp. 993–1001.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=333f1c13adf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fun with Fourier]]></title>
            <link>https://medium.com/@kovalenko.alx/fun-with-fourier-591662576a77?source=rss-81af05500d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/591662576a77</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alexander Kovalenko]]></dc:creator>
            <pubDate>Mon, 08 Jul 2019 13:24:25 GMT</pubDate>
            <atom:updated>2020-01-16T16:59:58.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W51_AW9aR-i3WCB7JL_pKQ.png" /><figcaption><a href="https://news.cnrs.fr/sites/default/files/styles/visuel_principal/public/assets/images/3159891_72dpi.jpg">Source</a></figcaption></figure><p>Hello, my arithmophobic friends! Well, maybe I am wrong and you are able to share my affinity in math, however, as for my experience, many IT guys are trying to avoid any raw math experience, recalling their boring math lectures at universities. However, could it be, that the issue is not in the math itself? Perhaps math curriculum just shouldn’t be considered as an obstacle to overcome? I might be wrong again, and maybe you, my friends, experienced a joyful and fascinating math course during your school time. Well, either your course was indeed truly amazing or you’re just a genius who is able to enjoy the things we, normal people, are struggling with, or maybe even both. Nevertheless, most math courses are quite… to say the least, not-so-breath-taking. At least, in my case, studying in the post-Soviet outdated insulate educational system that was quite true.</p><blockquote>“Do not worry about your difficulties in Mathematics. I can assure you mine are still greater.”</blockquote><blockquote>Albert Einstein</blockquote><p>With this in mind, it inspired me to scribble a few lines about something extremely useful and widely applied, but unfortunately widely overlooked. Yes, I am talking about Fourier transform!</p><p>Usually, the Fourier transform is represented as a transform of a meaningless sinusoid to a peak, which is even more meaningless. In some cases, a bunch of overlapped sinusoids becomes a bunch of peaks. Well yes, it has a lot of meaning for a signal processing, to split the signal into the discrete frequencies of different amplitudes, for instance. However, the Fourier transform can be applied everywhere, where there is a pattern or simply put it can be applied to check if there is any pattern. On the other hand, “finding a pattern” is something, which you, as a data scientist are trying to do, right? Hmmm… this starts to get quite intriguing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*ty5BWllt33P7hN54" /></figure><p>Fourier transform is widely used not only in signal (radio, acoustic, etc.) processing but also in image analysis eg. edge detection, image filtering, image reconstruction, and image compression. One example: Fourier transform of transmission electron microscopy images helps to check the crystallinity of the samples. Crystallinity — means periodicity, periodicity — means pattern. Fourier transform of your data can expand accessible information about the analyzed sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*c_EMs_APnDrS56-z" /></figure><h3>The Math Behind</h3><p>Mainly, the Fourier transform is represented as an indefinite integral:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/0*oQUvjmLw8s2t43xw" /></figure><p>For understanding the logic behind the origin of this integral watch an awesome video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FspUNpyF58BY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DspUNpyF58BY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FspUNpyF58BY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9997c0d0e1f921d8c3f2a0e2cca4fcb4/href">https://medium.com/media/9997c0d0e1f921d8c3f2a0e2cca4fcb4/href</a></iframe><p>However, indefinite integral presumes indefinite continuous data, which kinda do not exist in the digital world. For this purpose, the classical Fourier transform algorithm can be expressed as a Discrete Fourier transform (DFT), which converts a finite sequence of equally-spaced samples of a function into a same-length sequence of equally-spaced samples of the discrete-time Fourier transform:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/0*KO2sUEJiojReJvKo" /></figure><p>However in a race for the low complexity and algorithm efficiency most likely you would deal with Fast Fourier Transform (FFT) which is a fancy way to speed up the algorithm computation by re-expressing the discrete Fourier transform (DFT) of an arbitrary composite size N = N1N2 in terms of N1 smaller DFTs of sizes N2, recursively, to reduce the computation time from O(N2) to O(N log N):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/0*9EEALD256cXpRixh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*rs8FGYfc7WJZ_XC7" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*B3Bhk7-EEhMv7nhD" /></figure><p>For more information on FFT with some code examples in Python, I highly recommend the blog post below:</p><p><a href="https://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/">Understanding the FFT Algorithm | Pythonic Perambulations</a></p><h3>Release the Kernel!</h3><p>In Immanuel Kant’s words, “Experience without theory is blind, but theory without experience is mere intellectual play”, thus when we are able to see, let’s stop playing and code something. To make the point without many complications let’s take a small sound dataset, first 10 classed from ESC-50, for instance. Why sound? Just because we know that this is a bunch of sinusoidal waves stacked together, what can be more appropriate for our Fun with Fourier?!</p><p>The raw waveform signal looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/0*WerWZwh99JTSJvDJ" /></figure><p>Now we can feed it to a 1D CNN, to see what we can get:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e36c323ec20a092af8d150e5e54792d/href">https://medium.com/media/6e36c323ec20a092af8d150e5e54792d/href</a></iframe><p>After training the neural network for 100 epochs we are able to reach about 70% accuracy. Not bad! But what happens if we apply FFT to the signal and then feed it to the CNN.</p><p>The most simple way is to use the built-in function <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html">numpy.fft.fft</a> in the Numpy library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*CLJqdyjFC9rK-Kcb" /></figure><p>However, in this case, we have to duplicate the whole dataset, which is rather small in our case, however, it doesn’t have to always be true. So, in this case, it would be better to use the <a href="https://keras.io/layers/core/">Lambda</a> function inside a CNN model. Luckily Keras has its own FFT layers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4724223f3887f1923f1b2a54276504be/href">https://medium.com/media/4724223f3887f1923f1b2a54276504be/href</a></iframe><p>Built-in FFT, with Fortran in the backend, earns its name as it is really fast, let’s say in an order of microseconds, therefore, FFT computing time can be neglected in comparison with epoch time. Thus we can train CNN without any additional costs. As a result, after 100 epochs using the same test-train split dataset, it was possible to reach 71.7%. Doesn’t seem like much, but when you consider that a single line of code can help you to win a Kaggle competition, it doesn’t seem so insignificant anymore.</p><p>Even though the above-mentioned approach gave us some improvement in accuracy, there are few moments to be addressed. First of all, our dataset is quite “unifrequent”, thus the classes differ by frequency and the frequency range within the class is quite narrow and a frequency range of different classes can differ drastically. Therefore, our CNN can recognize the classes, from the perspective of the frequencies, with almost similar accuracy when the net is fed with raw waveform data. Perhaps we would expect better improvement in the accuracy in case if additionally to high-intensity “unifrequent” signal there would be a low-intensity noise, which would disturb the waveform data, but could be nicely distinguished after Fourier Transform. However, applying FFT over the entire signal is kinda odd… As far as the frequency of a real-world audio signal may change over time, we would lose the frequency-time contours of the signal. For this reason, usually, the signal needs to be split the signal into short-time frames with a certain overlap, and then, each of the frames has to be Fourier transformed and consequently, all the transformed frames have to be stacked together… Does someone want to do it manually?! Even using some library?! Naaaah…. We’re here to train a model, not to cut audio files!</p><p>Short-time audio frame? Sounds like a convolutional filter, right?! In this case, filter size would be the size of a frame and the stride would be the overlap between the frames. So, we can simply introduce our FFT layer in the intermediate layers of CNN and see what happens:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f897f71910a52395bbb029c5a761c842/href">https://medium.com/media/f897f71910a52395bbb029c5a761c842/href</a></iframe><p>In this case, we could reach the accuracy of about 77.5%, which sounds much better now. As mentioned above, implementing the Fourier transform for the intermediate layers allowed us to adjust trainable (!) kernels in a more efficient way, and in the end, we got more than 10% of relative accuracy increase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=591662576a77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>