<?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 Lorenzo Tinfena on Medium]]></title>
        <description><![CDATA[Stories by Lorenzo Tinfena on Medium]]></description>
        <link>https://medium.com/@lorenzotinfena?source=rss-c5ae380bf19f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2OKM11pWWLCHkHfR3UlUbg.png</url>
            <title>Stories by Lorenzo Tinfena on Medium</title>
            <link>https://medium.com/@lorenzotinfena?source=rss-c5ae380bf19f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:32:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lorenzotinfena/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[Lazy insertion in Hash array mapped trie]]></title>
            <link>https://lorenzotinfena.medium.com/lazy-insertion-in-hash-array-mapped-trie-5f65e12387ea?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f65e12387ea</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 14:25:50 GMT</pubDate>
            <atom:updated>2023-08-22T15:52:49.268Z</atom:updated>
            <content:encoded><![CDATA[<p>Instead of traverse and create node until reach a leaf node in the trie, you can simply just add the value in the first newly created node.</p><p>But for each node you should check if current node has the same hash, if yes append the value in that node, else continue.</p><p>This could be a good improvement for small amount of insertions.</p><p>Implementation: <a href="https://github.com/lorenzotinfena/goji/blob/main/collections/trie/hamt.go">https://github.com/lorenzotinfena/goji/blob/main/collections/trie/hamt.go</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f65e12387ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Formal golang implementation of Sqrt (Square Root) Decomposition]]></title>
            <link>https://lorenzotinfena.medium.com/formal-golang-implementation-of-sqrt-square-root-decomposition-448f248cd260?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/448f248cd260</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 23:54:43 GMT</pubDate>
            <atom:updated>2023-03-15T13:37:28.806Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/lorenzotinfena/goji">Here</a> you can find the an implementation on a simple sqrt decomposition algorithm, but do you need it? Here’s the formal condition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*gfkbsj6WnDCkEovg9MZTxA.png" /></figure><p>Then you can use it.</p><p>If UnionQ and query functions are Θ(1), then the complexity of the algoritm in average and worst case is Θ(Q*sqrt(N)) where Q is the number of queries.</p><h3>MO’s algorithm</h3><p>If UnionQ function is hard, but there exist an efficient function expandQ: Q, E -&gt; Q (I’ll skip the formality) then you can use MO’s algorithm with complexity in average and worst case as Θ((N+Q)*sqrt(N)).</p><p>In the same repo you can find an implementation on this too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=448f248cd260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backwards compatibility of programming languages suck]]></title>
            <link>https://lorenzotinfena.medium.com/backwards-compatibility-of-programming-languages-suck-3aa40816ec7f?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aa40816ec7f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[backwards-compatibility]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Fri, 18 Nov 2022 21:42:52 GMT</pubDate>
            <atom:updated>2022-11-18T21:42:52.476Z</atom:updated>
            <content:encoded><![CDATA[<p>Backwards compatibility in programming languages may not limit the addition of new features, but it does limit the simplicity of the language.</p><p>But is it really necessary?</p><p>If you write a program with a version of the language 1.1, and then it’s released a new version 1.2 which some things that aren’t backward compatibles, it doesn’t mean that you have to update your code, you can specify the latest version of the programming language.</p><p>What are the limitations of this approach for you?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aa40816ec7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop searching “what is a smart contract” and learn Solidity instead!]]></title>
            <link>https://lorenzotinfena.medium.com/stop-searching-what-is-a-smart-contract-and-learn-solidity-instead-d87cfc6980d4?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d87cfc6980d4</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Fri, 28 Oct 2022 11:04:28 GMT</pubDate>
            <atom:updated>2022-10-28T11:04:28.560Z</atom:updated>
            <content:encoded><![CDATA[<p>You know what is a token? An NFT? All of them are standards, and you can find those at <a href="https://eips.ethereum.org/erc">https://eips.ethereum.org/erc</a></p><p>Stop searching “smart contract what is” or “token vs crypro advanced tutorial” or“nft advanced tutorial”, just learn solidity and create a simple ERC-20 token to understand this world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d87cfc6980d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State of the art in software development tools]]></title>
            <link>https://lorenzotinfena.medium.com/state-of-the-art-in-software-development-tools-2baf0811b1bc?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2baf0811b1bc</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[stateoftheart]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 23:14:19 GMT</pubDate>
            <atom:updated>2022-10-19T23:14:19.407Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software development tools that I believe are the state of the art of their goal</h4><ul><li>Go (backend)</li><li>Flutter (frontend)</li><li>Solidity (smart contracts)</li><li>Ethereum virtual machine (blockchain runtime)</li><li>Grpc (API framework)</li><li>ALTS Application Layer Transport Security (Authentication system)</li><li>Container (software runtime protocol at os layer)</li><li>Docker (Container runtime)</li><li>Kubernetes (Container orchestration)</li><li>VSCode (IDE)</li><li>Remote container vscode extension</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2baf0811b1bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you’ll probably fail with flash loan arbitrage]]></title>
            <link>https://lorenzotinfena.medium.com/why-youll-probably-fail-with-flash-loan-arbitrage-771d4c487ed6?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/771d4c487ed6</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[arbitrage]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[flash-loan]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 23:53:40 GMT</pubDate>
            <atom:updated>2022-10-14T19:02:37.953Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Disclaimer: There may be errors in this article, I’m not an expert and take all of this with a grain of salt</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_duDQoJJGRf22mSI5IWrg.jpeg" /><figcaption>Image sources on Freepik, by wirestock and rawpixel.com</figcaption></figure><h3>There are 2 main reasons:</h3><ol><li><strong>The more aggregators of dex</strong> will be used (like <a href="https://www.0x.org/">0x</a>), t<strong>he less arbitrage opportunities</strong> can be found, because already aggregators look for the best price and somehow take advantage of it without actual arbitrage.</li><li>If flash loan fees are for example 0.05%, it means that with arbitrage you will hope to make a profit greater than this threshold, but arbitrage opportunities are more likely to be taken before they reach this threshold <strong>by people investing large amounts of money out of their own pockets</strong> (at least in markets with a lot of liquidity, although this may not currently be the case at the moment, especially if people swap tokens without dex aggregators). So either you can try to be extremely competitive by looking in lots of different markets, even with little liquidity, however obviously making less money. But then the flash loan would not even make much sense.</li></ol><p>I’m not an expert, if you have critism/comments please let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=771d4c487ed6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What you should know to not lose money with copy trading]]></title>
            <link>https://lorenzotinfena.medium.com/what-you-should-know-to-not-lose-money-with-copy-trading-885c02e06d52?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/885c02e06d52</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[copy-trading]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Thu, 01 Sep 2022 19:52:21 GMT</pubDate>
            <atom:updated>2022-09-01T20:20:18.603Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Disclaimer: There may be errors in this article, I’m not an expert and take all of this with a grain of salt</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Fl4lv5lHxgLd34BiXogYw.jpeg" /></figure><h4>The risks I would like to talk about are 2</h4><p><strong>The first concerns only crypto: </strong>In fact, as we know they are usually decentralized, in fact only we own our crypto, however some crypto copy trading platforms require you to deposit the crypto in their wallets, which will still be connected to your account, however this is a big risk, in fact the platform it could disappear at any time and no longer give you your crypto, or a technical problem may occur that no longer makes you have your crypto. Surely you have to be very careful, and maybe avoid these types of platforms. Some signs of reliability may be if the platform has been around for a long time, if it has a good community that supports it, if it has a good reputation on the internet, if it has many active users, and perhaps if it is open source.</p><p><strong>The second risk</strong> is much more deceptive, in fact when you are looking for new strategies / traders to “copy” maybe the platform will show you the ones that (even in the long term) are more profitable, without seeing those that have failed or because they are difficult to find on the platform. or because they were just canceled!<br>Maybe you can think: ok, I don’t care, so I choose the most profitable ones in the long term, the problem is that these too can fail at any moment and be replaced by new strategies that in the meantime have proved to be profitable than before. appeared among the best! If you follow a strategy / trader to “copy” to get out of it well you either have to know when to leave the strategy or if it is closed in a profitable way, but why close it if it is profitable? Mhm ….<br>The best thing is if the platform gives the possibility to see the closed strategies with their statistics, in order to see if among the closed ones how many were profitable or not in the end.<br>Without this data, you can seek feedback from the community, or compare how many strategies are currently losing money, or monitor the main strategies in the platform over a period of time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=885c02e06d52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Differenza tra salsa, passata, conserva, polpa, pomarola e sugo di pomodoro]]></title>
            <link>https://lorenzotinfena.medium.com/differenza-tra-salsa-passata-conserva-polpa-pomarola-e-sugo-di-pomodoro-7ae0ddf69d0f?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ae0ddf69d0f</guid>
            <category><![CDATA[pomodoro]]></category>
            <category><![CDATA[pomodori]]></category>
            <category><![CDATA[cucina]]></category>
            <category><![CDATA[cibo]]></category>
            <category><![CDATA[cooking]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Thu, 01 Sep 2022 13:28:45 GMT</pubDate>
            <atom:updated>2022-09-06T16:03:35.712Z</atom:updated>
            <content:encoded><![CDATA[<h4>Differenza tra “Salsa di pomodoro”, “Passata di pomodoro”, “Conserva di pomodoro”, “Polpa di pomodoro”, “Pomarola” e “Sugo di pomodoro”</h4><p><em>Disclaimer: queste sono le mie interpretazioni/pensieri insieme a una piccola ricerca, quindi possono essere considerate sbagliate e possono esserci differenze per ogni regione in italia o differenze dialettali.<br>Parlerò solo del prodotto finale, non del metodo, perchè quello può cambiare.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hT-JrYXJiZi7fc9eiOudDw.jpeg" /></figure><h3>Passata di pomodoro/salsa di pomodoro (passata di pomodoro/salsa di pomodoro)</h3><p>Si tratta di pomodori <strong>crudi </strong>(<strong>non cotti </strong>o <strong>cotti per poco tempo</strong>), sono “macinati”e vengono rimossi semi e pelle. (Con macinare intendo rendere omogeneo)<br>Si <strong>può </strong>aggiungere un po’ di sale e basilico.<br><strong>Può </strong>essere imbottigliato e sterilizzato</p><h3>Conserva di pomodoro</h3><p>È come il precedente, ma viene <strong>sempre </strong>imbottigliata e sterilizzata</p><h3>Polpa di pomodoro</h3><p>È come il primo, ma i pomodori sono a pezzetti (non macinati)</p><h3>Pomarola</h3><p>Prendete ogni possibile “versione” di pomodoro precedente, la cuocete e ottenete la pomarola (il metodo di preparazione può cambiare).<br>Si <strong>possono </strong>aggiungere altri ingredienti, come sale, basilico, cipolle, carote, sedano, ecc…<br><strong>Può </strong>essere imbottigliato e sterilizzato</p><h3>Sugo di pomodoro</h3><p>È come il precedente, ma è più generale perchè è più libero nella scelta di ulteriori ingredienti e perché <strong>puoi </strong>cuocere i pomodori direttamente, e poi <strong>puoi </strong>“macinarlo” e/o togliere semi e pelle.<br>Attenzione che per molti la Salsa di pomodoro è proprio questa.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ae0ddf69d0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tomato’s italian names madness - guide for non-italians (and italians)]]></title>
            <link>https://lorenzotinfena.medium.com/tomatos-italian-names-madness-guide-for-non-italians-and-italians-3995a0d0d09d?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3995a0d0d09d</guid>
            <category><![CDATA[recipe]]></category>
            <category><![CDATA[tomato-sauce]]></category>
            <category><![CDATA[food]]></category>
            <category><![CDATA[italian-food]]></category>
            <category><![CDATA[italy]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 12:27:06 GMT</pubDate>
            <atom:updated>2022-09-06T16:08:27.517Z</atom:updated>
            <content:encoded><![CDATA[<h4>Difference between “Salsa di pomodoro”, “<strong>Passata di pomodoro”, </strong>“Conserva di pomodoro”<strong>, </strong>“Polpa di pomodoro”, “Pomarola”<strong>, and “Sugo di pomodoro”</strong></h4><p><em>Disclaimer: These are my interpretations/thoughts along with a little research, so It can be considered wrong, and there can be differences for every region in italy or difference with translations.<br>I will talk only about the final product, not the method, becaude it can change.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hT-JrYXJiZi7fc9eiOudDw.jpeg" /></figure><h4>Do you know tomato sauce or tomato puree?</h4><p>Literally the first in italian is called <strong>salsa di pomodoro</strong> and the second <strong>passata di pomodoro </strong>but what about <strong>conserva di pomodoro</strong>, <strong>polpa di pomodoro, pomarola</strong>, or <strong>sugo di pomodoro</strong>!?</p><h3>Passata di pomodoro/salsa di pomodoro (tomato puree/tomato sauce)</h3><p>It’s <strong>raw (no cooked </strong>or <strong>cooked for a short time) </strong>ground tomatoes and without seeds and skin.<br><strong>Can </strong>be added some salt and basil.<br>It <strong>can </strong>be bottled and sterilized.<br>Be aware becaude someone refers to tomato puree to mean “concentrate of tomato” or concentrato di pomodoro, that is another thing.</p><h3>Conserva di pomodoro</h3><p>It’s like the previous one, but is <strong>always </strong>bottled and sterilized</p><h3>Polpa di pomodoro</h3><p>It’s like the first one, but the tomatoes are into small pieces (not ground)</p><h3>Pomarola</h3><p>You take every possible previous tomato “version”, you cook it and you obtain pomarola (method of preparation can change).<br><strong>Can </strong>be added other ingredients, like salt, basil, onions, carrots, celery, ecc…<br><strong>Can </strong>be bottled and sterilized</p><h3>Sugo di pomodoro</h3><p>It’s like the previous one, but is more general, because is more free to add other ingredients and becaude you <strong>can </strong>cook tomatoes directly, and then you <strong>can </strong>ground or/and remove seeds and skin.<br>Note that maybe in english you can refer to this with “tomato sauce”, and for many people also the term “Salsa di pomodoro” is just this... Yes, it’s a mess.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3995a0d0d09d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A formal Introduction to Deep Reinforcement Learning]]></title>
            <link>https://lorenzotinfena.medium.com/a-formal-introduction-to-deep-reinforcement-learning-db639d8c48b8?source=rss-c5ae380bf19f------2</link>
            <guid isPermaLink="false">https://medium.com/p/db639d8c48b8</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[deep-q-learning]]></category>
            <dc:creator><![CDATA[Lorenzo Tinfena]]></dc:creator>
            <pubDate>Tue, 10 May 2022 06:37:18 GMT</pubDate>
            <atom:updated>2023-03-14T11:00:57.730Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep Reinforcement Learning from scratch with Deep Q-learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dn0O47ySWVU7VT9j27BSsQ.jpeg" /></figure><p><strong>To understand this article very quickly</strong>, I suggest that you should be familiar with:</p><ul><li>Basic math</li><li>Basic matrix operations</li><li>Partial derivatives</li><li>Probability function</li></ul><p>In some parts, I will use a notation like <em>a_b</em> to denote a subscript in maths, like in LaTeX.</p><h3>1. Introduction</h3><h4>1.1 Purpose</h4><p>In this elaboration, I would like to explain how it is possible to build an artificial intelligence, understand when it produces errors or when it performs its actions correctly, and it is improved continuously. This is one of the most generalized forms of artificial intelligence currently for me. I also made a sample application: an inverse pendulum, which is simply an axis hung to a pivot, that must move either to the right or to the left so that it does not fall to the axis.<br>All of the algorithm implementations I used in the attached project (see the bottom) are written from scratch in Python.</p><figure><img alt="deep q learning pendulum inverse reinforcement learning deep reinforcement learning deep learning" src="https://cdn-images-1.medium.com/max/651/0*eSaqes_1EkPS5Xc8.png" /></figure><p>A process called “deep Q-learning” is the algorithm I used for this, but now, before we get to how this works, we have to start with the basics.<br>What are artificial intelligence and machine learning?<br>What is the concept of reinforcement learning?</p><h4>1.2 What is artificial intelligence?</h4><p><strong>Artificial intelligence, is </strong>the ability a machine has to reproduce biological intelligence. That is, the one we all know that humans, animals, and plants have.</p><p><strong>Generalizing</strong>, we can say that the intelligence (both artificial and biological) of an entity in an environment is its ability to choose the correct action to perform according to its state and its experience. The chosen action is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/0*cQJYhKFDbO8pxGRG.png" /></figure><p>Where <em>A</em> is the chosen action, <em>E</em> is the experience, and <em>S</em> is the state.</p><p>For example, for a human being to walk, he has to choose which muscle to move in a space (environment), based on their position (state), and on his experience (which regulates in a general way how to move).</p><h4>1.2.1 The relationship between general intelligence and the correctness of actions</h4><p>The intelligence of an entity is proportional to the correctness of the actions performed by the entity as its state and experience vary. Thus, just as correctness is subjective, so is intelligence.</p><h4>1.2.2 The criteria for the correctness of actions</h4><p>To create artificial intelligence that assists humans, the criteria of correctness will have to be subjective to the users.<br>For instance: Person <em>A</em> applauds and considers a robot that cleans the house once a week very intelligent.While Person <em>B</em> assumes the opposite because he would like the robot to clean the house 5 times a day.<br>Even though we can incorporate in the robot state the exact person whom it has to clean house. Thereby making the intelligence a little more objective. However, the latter can never be fully so.</p><h4>1.3 How is the experience of an entity formed?</h4><p>The experience and the state of the entity determines the actions that will be carried out. We can consider it as the strategy of the entity and it is divided into 2 broad types:</p><ul><li><strong>Static experience:</strong> This is only found in artificial entities and from a mathematical point of view, we can identify it as a “non-parametric function”.<br>For example, a program (artificial entity) that is given the route of a car, i.e. the space covered in kilometers, and the duration in hours (both of these form the state), and a non-parametric function (static experience) <em>f (space, duration) = space/duration </em>calculates the average speed (the action is the value of the average speed).</li><li><strong>Dynamic experience:</strong> This is in both the artificial and biological entities and from a mathematical point of view, we can identify it as a “parametric function”.<br>For example, a program (artificial entity) that given the surface of a house (state) must predict its price (this chosen action is the value itself). And it cannot use a function that is not parameterized, because many variables would affect the price.<br>These variables could be the location of the construction or the year of construction.<br>We could include these variables in the state together with the surface, but it would be difficult to write a function that efficiently calculates the price.<br>for this reason, we write a very generalized function parameterized according to dynamically determining variables, trying to maximize the accuracy (or intelligence) of the entity.</li></ul><h3>2 Reinforcement learning</h3><h4>2.1 General machine learning</h4><p>In an artificial entity with static experience, it is the task of classical programmers to determine the suitable static experience to maximize its accuracy.</p><p>Instead, when dealing with a dynamic experience, it is the artificial entity itself (at least in most cases) that modifies its own experience, and it is only in this case that the entity will be allowed to do so.<br>This means that it must be provided with a <strong>correctness criteria.</strong></p><p>The set of processes that govern the experience, and how it can change, is called <strong>machine learning.</strong></p><h4>2.1.1 Types of machine learning</h4><p>For an entity to modify its experience in a way that maximizes its accuracy, someone must provide it with a correctness criteria. So, how an entity modifies its <strong>experience given a correctness criteria </strong>determines the various types of machine learning.</p><ul><li><strong>Supervised learning</strong> (dynamic experience):<br>In supervised learning, the provided correctness criteria is a set of records called a <strong>dataset, or more specific training set</strong>. This is where each record contains a state and an action that is considered correct.<br>There are many models/algorithms in supervised learning, but the general idea is that the experience is constantly modified so that for each state, the action chosen is similar to the corresponding one in the dataset.</li><li><strong>Unsupervised learning </strong>(static experience):<br>In unsupervised learning, the experience that is, how it should work when it is tested, is determined from the beginning.<br>This means that it is static because the purpose of the models/algorithms of this type of machine learning is generally to collect insights or statistics regarding the data.<br>For example, a single state comprises a list of images, that must be classified by looking for the differences between them. (The list of predictions is the chosen action).</li><li><strong>Reinforcement learning (RL)</strong> (dynamic experience):<br>A very general method for providing the correctness criteria is simply saying how much correct the action chosen by the entity is, based on the state.<br>This value is called the <strong>reward.</strong> The experience here will be modified trying to maximize it. Giving a reward (mostly continuous, and not discreet) to the entity for every action that it carries out, is a workflow very generalized.<br>A valid example<strong> is we. </strong>That is, with our senses we understand our surroundings and take actions to increase or improve our happiness. (i.e. reward).<br>For each state, action, and random factor (only in certain environments), a reward is attached.</li></ul><h4>2.2 Basic workflow</h4><p><strong>To summarize</strong> this, providing scalar feedback (reward), for each couple state-action is a very simple and general correctness criteria.<br><strong>Now let’s better understand the basic workflow of an artificial reinforcement learning entity.</strong></p><figure><img alt="deep q learning pendulum inverse reinforcement learning deep reinforcement learning deep learning" src="https://cdn-images-1.medium.com/max/355/0*XpJo8AqftA_d-7X5.png" /></figure><p>The agent initially receives the first state <em>s </em>and then uses it together with its experience to perform an action <em>a.<br></em>Then, an interpreter (which in some cases corresponds to the environment itself), receives <em>s’</em> (next state), evaluates the choice of a (based on <em>s</em>, <em>s’ </em>and sometimes also based on a random factor that we will formalize later). The reward <em>r’</em> chosen by the interpreter is given to the agent along with <em>s’</em>.<br>Let’s see a small example in python of an agent that performs random actions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dbf0b72e8d61f05143b3afa88305cac/href">https://medium.com/media/8dbf0b72e8d61f05143b3afa88305cac/href</a></iframe><h4>2.3 Formalization</h4><p>before we begin, you need to understand these concepts well:</p><ul><li><strong>States</strong> are sometimes called <strong>observations</strong>.</li><li>All possible states belong to an <strong>observation space</strong>.</li><li>Like states, actions also belong to an <strong>action space</strong>.</li><li>Each space can be <strong>discrete</strong>, <strong>continuous</strong>, or a combination of other spaces. For example, a discrete space is defined as <em>[0, 1, … , n-1]</em>, where <em>n</em> is the number of discrete states, and a continuous space is a tensor of scalars with a minimum and a maximum value.</li></ul><p>To formalize a reinforcement learning workflow, it is viewed in form of a particular type of Markov chain named a Markov decision process (MDP).<br>MDP is a way to represent a discrete observation space (<em>S</em>) of an environment and its discrete action space (<em>A</em>).</p><p>An MDP is not part of the entity’s experience, it is simply a way to represent transitions in reinforcement learning. We are currently considering environments with discrete observation and action spaces and the equations derived from an MDP will also be used for continuous observation and action spaces, as we will see later.</p><h4>2.3.1 Types of MDP</h4><ul><li><strong>Fully observable MDP</strong>: In addition to <em>S</em> and <em>A</em>, a matrix <em>P</em> (also called <em>T</em> ) is included, this can be stochastic. Meaning that</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/0*AAuO0dQUv4zfF-h5.png" /></figure><p>is the probability of passing from state <em>s</em> to state <em>s’</em> having performed the action <em>a</em>; or deterministic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/0*m4YinByen4PRW_Nz.png" /></figure><p>It also has a matrix <em>R</em>, such that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*C38CdtxnU1N4HaSR.png" /></figure><p>is the reward obtained from the transition from state <em>s</em> to state <em>s’</em> having performed action <em>a</em>.</p><p>In some MDPs with the same <em>s</em>, <em>a</em>, and <em>s’</em>, different rewards can occur so, the matrix <em>R</em> can represent the average of such values.</p><p>Usually, <em>P</em> is expressed stochastically to generalize, and at most, you will have a deterministic-like probability distribution. This type of MDP respects the Markov property that says that transitions and rewards successive to a time <em>t </em>are independent of transitions with times before <em>t</em>. So, when we talk about MDPs in general, we refer to this type. <em>MDP = (S, A, P, R)</em></p><ul><li><strong>Partially observable MDP</strong>:<br>This does not have a probability matrix <em>P</em>, and a reward matrix <em>R</em>, because they are unknown so, one can only try to approximate them. This type of MDP may not respect the Markov property but in the next section, we will understand why.</li></ul><p>The <strong>dynamics of the environment </strong>are often characterized using a <strong>Fully Observable MDP, </strong>while the <strong>dynamics of the agent</strong> can be characterized using the same <strong>Fully observable MDP as its environment, or another Partially observable MDP</strong>. This will also be clarified in the next section.</p><h4>2.4 Model-based and model-free RL</h4><p>There are 2 types of reinforcement learning (both of them have different algorithms) called the <strong>model-based RL</strong> and <strong>model-free RL.</strong> They differ from what the agent knows about the environment, formally we can define the difference using the 2 types of MDP described above.</p><figure><img alt="model based model free reinforcement learning" src="https://cdn-images-1.medium.com/max/472/0*5dbIliQvAmSStA11.png" /></figure><ul><li><strong>Model-based RL:<br></strong>This type of reinforcement learning use a Fully observable MDP that describes both the dynamics of the agent and the environment so, the agent can predict all transitions.<br>We can find this type of RL in some videogames like “snake”, where every state of the environment (matrix) corresponds to the state of the agent (artificial), however, it is difficult to be applied in reality because for example a human, cannot know what happens in every part of the universe.</li><li><strong>Model-free RL:<br></strong>In the model-free RL, the dynamics of the agent are described by a Partially observable MDP, while the dynamics of its environment are described by a Fully observable MDP.<br>The agent, therefore, does not know initially the rewards (<em>R</em>) and <em>P. W</em>hat it can only do is try to predict them according to its possibilities which are determined by the relationship between its different MDPs.<br>In these two different MDPs, the states may not correspond and the Partially observable MDP does not always follow the Markov property.<br>For example, if one day a person performs an action that produces a butterfly effect on the other side of the world and then takes a stroke, he can no longer remember anything. The next day he may suffer the consequences of what he did. But if he had not performed that action that day, it would have affected the future differently thus, future transitions.</li></ul><h4>2.5 Policy</h4><p>Recalling that an agent when receiving a state, chooses which action to take based on experience, we now understand how this process occurs.<br>The strategy/experience of an agent in reinforcement learning is determined by a policy, that may be stochastic (<em>π : A × S → [0, 1]</em>) or deterministic (<em>π : S → A</em>), where S and A are the observation space and the action space of the a- people’s MDP.</p><p>The stochastic policy is generally defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*JFp0Uw6mv61wzied.png" /></figure><p>where <em>p</em> is the probability function</p><p>or (alternative notation) <em>π(a, s) = p(a|s)</em>. The probability given by the stochastic policy, given a state and an action, is the probability that that action is the optimal according to the agent. Deterministic policy instead deterministically chooses the best action given a state and is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/0*RpZSSq_3Sw-RkFQx.png" /></figure><p>The action chosen by the policy will then be carried out. To generalize, usually, in formulas stochastic policy is used.</p><h4>2.6 Policy evaluation</h4><p>Premise: In a series of infinite transitions, in time (<em>t</em>) we can define a variable called <strong>return</strong> (or more specifically <strong>discounted return</strong>), with the symbol <em>G</em> (we use also <em>R</em>, but it can create confusion with the reward matrix), defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/0*Yfa_ttC132uFDZRo.png" /></figure><p>If instead the current state is the last of the episode, <em>G</em> is worth 0, because it is useless to consider future rewards that will never be obtained. The return represents a sum of future rewards, where more weight is given to immediate rewards. The discount factor (gamma), such that <em>γ ∈ [0, 1]</em>, the smaller it is, the greater the immediate rewards affect the discounted return. Given this premise, we can define the optimal policy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*vQYNHxDkO96Wibjg.png" /></figure><p>as that deterministic policy which at time <em>t=0</em>, maximizes the expected value of the return <em>G</em> or, as that policy which if used, maximizes the average of all total rewards over a large number of episodes. Formally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*W7MecC3WN2LgaWdc.png" /></figure><p>with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/0*Sys7hhOsO7cMi4sl.png" /></figure><p>The dot is used only by convention. For example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/0*uygBL8LAwz08bGm0.png" /></figure><p>in the equation is the <strong>discrete probability distribution</strong> that <strong>each state is selected as first</strong>, another notation used is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/0*QZY2lGdr748vdqfD.png" /></figure><p>Another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/0*tX-DY-zjNtyfj6p_.png" /></figure><p>is the discrete probability distribution that each state is selected as next, given the current state and the chosen action.</p><p><strong>The formula may seem complicated</strong> and of course, it is, but let’s analyze it: <em>E(G)</em> does not refer to a series of transitions, but refers to possible transitions in the MDP of the agent, in fact, the expected value of the return is calculated with the discrete aleatory variables <em>s_0</em> , <em>a_t</em> and <em>s_t+1</em> .</p><p>The first is the first state of the return. It has a probability distribution given by the probability that <em>s_0</em> is the state of the first transition, we must be careful that <em>t=0</em> means the initial time of the return calculation, not the time of the episode.</p><p>Then there is the random variable <em>a_t</em> , which has a distribution obtained from the policy given the state always at the same time <em>t</em>. In addition, the last random variable is <em>s_t+1</em> , which has a probability distribution given by the probability that this state at time <em>t+1</em> was selected by the environment, given the state at time <em>t</em>, and the action taken <em>a_t</em>.</p><p><strong>In the case of a fully observable MDP</strong>, the algorithms/optimizers try to solve this equation, <strong>however in partially observable MDPs</strong>, since the probabilities of the transitions and the rewards are initially unknown, and since the optimal policy depends on the rewards, the optimal policy can change, since with time the prediction of the rewards varies, in other words, the optimal policy at time <em>t</em>, will not be the optimal policy at the time <em>t + 1</em>, we can distinguish the optimal policy according to the agent and the optimal policy according to the environment (the “really optimal” one). The goal is to bring the agent’s optimal policy closer to the environment’s optimal policy.</p><h4>2.6.1 Difference between on-policy and off-policy algorithms</h4><p>In the <strong>on-policy</strong> algorithms, the <strong>same policy of the evaluation is used in training</strong> but in the <strong>off-policy</strong> algorithms, it is <strong>only in the evaluation</strong> that the <strong>optimal policy</strong> will be used.<br>In the Q-learning section, we will see why.</p><p><strong>The optimal</strong> <strong>policy is always deterministic</strong>. But, a <strong>non-optimal</strong> <strong>policy can both be stochastic and deterministic</strong>, this concept will also be clarified in section 3.1</p><p>If something is unclear, I recommend that you continue to read the Q-learning, then you can come back later to read this section later.</p><p>There are many types of reinforcement learning algorithms with different approaches. For example, there are algorithms of type <strong>value optimization</strong> and <strong>policy optimization</strong>. We will not go into detail but to get an idea just look at the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/0*zTTDJYdH51LaFrLZ.png" /></figure><h4>2.7 State-value and action-value</h4><p>The state-value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/70/0*OsRohj5H4bCQ1hDH.png" /></figure><p>is a function that tells how good a state is, basically it is the expected return<br>following the policy π, starting from the state <em>s</em>, formally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/0*A4s8ddYMsgBmaGZt.png" /></figure><p>The action value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/0*2wLEiz9lNwQnItbd.png" /></figure><p>called also Q-value, is another function, and it plays a similar role to the state-value, but the first chosen action must also be specified.<br>The Q-value, then, is the expected return following the policy <em>π</em>, starting from a determined state and initially choosing a determined action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/0*ycrRLtp53S5mfMSu.png" /></figure><h4>2.8 Q-value evaluation and Bellman equation</h4><p>The Bellman equation succeeds in expressing the Q-value recursively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*gOf9cIE5pM1gZ7vV.png" /></figure><p>note that the symbol <em>‘</em> is used to denote the next action or state</p><p>Now, considering the optimal policy, (remember that if it is optimal it is deterministic), given a state, we obtain the action that maximizes the Q-value. So, we can say:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*yh4KmQJ6IqMH05Iz.png" /></figure><p>Now we can define the optimal Q-value (the one that follows the optimal policy), with the Bellman equation (in this case called the <strong>Bellman equation for optimality</strong>):</p><figure><img alt="bellman equation optimality reinforcement learning deep q learning" src="https://cdn-images-1.medium.com/max/663/0*rmIlpRtrZrU0zoS1.png" /></figure><p>This formula will take us into the next section to optimize the agent.</p><h3>3 Q-Learning</h3><p>Q-learning is a reinforcement learning algorithm that is model-free and is a value optimization type. the optimization is based on the Q-value and the Bellman equation. The limitations are that the observation and action space are discrete, and the policy is deterministic.</p><p>The agent has a two-dimensional table called Q-table, where each row corresponds to a state in the observation space and each column to an action in the action space.<br>This table has a corresponding Q-value for every state-action pair. From now on we will take for granted that it is the Q-value that follows the optimal policy. So the following convention will be valid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/0*J4A7v16Fa4f758h3.png" /></figure><p>As already mentioned, the optimal policy (which I remember is always deterministic), when given a state, chooses the action with the highest Q-value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/0*bAAW9y_KvFUIbxhQ.png" /></figure><p>If we can collect the right Q-values, we’ve got the optimal policy!<br>But how do we calculate the Q-values?<br>If we re-observe the Bellman equation for optimality (which uses the same policy), we will notice that in time <em>t</em>, <strong>if we know the Q-value at time <em>t-1</em>, we can approximate better the Q-value at the time <em>t</em></strong>.<br>I mentioned the word “approximate” for 3 reasons:<br>The rewards can vary even with the same <em>s</em>, <em>a</em>, and <em>s’.</em> So, if in the same transition I get a reward now, later if I repeat the same transition I could get another different, also <em>s’</em> may not be fixed if <em>P</em> is stochastic. Finally, the Q-value at time <em>t-1</em> is also approximated.</p><p>But if we continue in the episodes always updating the Q-values, for a time that tends to infinity, we can obtain the <strong>average (or expected) Q-value</strong>.<strong><br></strong>This means approximating the optimal policy according to the agent with that one according to the environment (or the <strong>really optimal one</strong>), which is exactly what we are looking for.<br>The update will happen in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*l9WoPehjR46QdGki.png" /></figure><p>Let’s understand this process better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/0*4Tyd-iuEsabbWpYI.png" /></figure><p>is the expected (or target) Q-value of <em>s</em> and <em>a</em>, while</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/58/0*C97FujdHCNd0cd32.png" /></figure><p>is the current one, we will calculate their difference and obtain an error, that we will add to the current Q-value, after multiplying it by an alpha factor, such that <em>a ∈]0, 1]</em>, called learning rate, if it is close to 1, the new Q-value is close to the target one. But if it is close to 0, the new Q-value is close to the current one.</p><p>The basic workflow of Q-learning is as follows:</p><figure><img alt="deep q learning reinforcement learning deep reinforcement learning deep learning" src="https://cdn-images-1.medium.com/max/373/0*9i2HkVpwkX_VACEJ.png" /></figure><h4>3.1 Exploration vs exploitation dilemma</h4><p>Imagine you are in a room with 2 doors and on one door, you know that behind it there will be 100 coins, but you do not know what may be behind the other door.<br>Maybe there may be more than 100 coins or less.<br>The question now is: do you try your luck or accept the first safe 100 coins?<br>Another example is every time a student goes to school he or she always travels the same road. Now should the student try the road that he or she does not know and perhaps discover that they can shorten or at worst lengthen the route?<br>Surely it is disadvantageous to try new roads every day. And if you take the risk, it may lengthen the route, and if you don’t take this risk, you will keep taking the best route that you know.<br>Yes, the solution might be to try new routes now and then. But <strong>how often</strong> should you try taking a new route that you don’t know of?</p><p>This is a big dilemma in reinforcement learning and it is based on the choice between <strong>exploration</strong> (exploring new ways) and <strong>exploitation</strong> (going in the best ways I already know). Because of this, it is <strong>not always the action chosen by the optimal policy, that will be carried out</strong>.</p><p>Having said this we can identify the real policy (previously called “not optimal”), which is the one that chooses the actions that will actually be performed. It relies on the optimal policy for the <strong>exploitation</strong> (although sometimes you can <strong>avoid the exploitation in training</strong>), and on a random factor (usually) for the <strong>exploration</strong>. In other words, given the action chosen by the optimal policy, we must understand that it might be the one to be carried out or not. To make this choice there are many algorithms called <strong>Bandit Algorithms</strong>, the most important are the following:</p><ul><li><strong>Epsilon-greedy</strong> ( ε-greedy): The epsilon is a constant value between 0 and 1 inclusive, it is the probability that a random action is performed, the pseudocode is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*I3i97-cPHo1hhHg3.png" /></figure><p>The choice of epsilon constant is based on how deterministic the MDP is. The more deterministic it is, the less it needs to be explored so, a small epsilon is fine.<br>In addition, the duration of the episodes is also affected: if they tend to finish quickly at the slightest wrong action so, it is best to prefer a low epsilon.</p><ul><li><strong>Softmax</strong>: This is a “Value Adaptive Epsilon algorithm” and it relies on Q-values to determine the probability of choosing actions. This algorithm chooses the action based on a probability distribution calculated from action returns. The higher the return, the higher the probability that his action is chosen. Each probability of the distribution is obtained from:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*3N7IAgkpSdQSQDfU.png" /></figure><p>The parameter <em>τ&gt;0</em>, if it is high, the difference in probability between actions with different returns is smaller, but if it is close to 0, a “greedy” choice is made, which is always choosing the best action.</p><ul><li><strong>Decay epsilon-greedy</strong> (based on ε-greedy): This algorithm, at each step, decreases the epsilon exponentially, as follows:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*UAkqGWjrcLd2ymk_.png" /></figure><p>where epsilon decay <em>∈ [0, 1]</em>.</p><figure><img alt="eploration vs exploitation trade-off dilemma reinforcement learning" src="https://cdn-images-1.medium.com/max/668/0*iVP3HBFLsDZ8XS4d.png" /></figure><h4>3.2 Example in python</h4><p>Now let’s take a look at a small example in python which we’ll go on to explain.<br>In the attached project there is a Python notebook called “q-learning-example.py”, divided into 2 parts. Let’s analyze the first one:</p><p>Let’s import the libraries we will use: <strong>numpy</strong> for various mathematical operations, <strong>gym</strong>, used to create environments with a common interface quickly and easily, and <strong>plotly</strong>, to show graphs.</p><p>The class Q-Agent is defined, where the environment is passed in its the constructor, and the Q-table with zeros is started.<br>The start episode function is defined, where, in a loop that lasts until when the episode is over.<br>It chooses the action with the real (not optimal) policy, with the epsilon-greedy algorithm. Now, the agent performs that action and gets the reward, the next state, and a boolean variable, which indicates whether the episode is over.<br>If it is over, the update does not take into account the Q-value of the next state, because it would not make sense to think of getting future rewards, if the episode is over.</p><p>After defining the agent, in this second part, we are going to execute a small example program. The discount factor used will be 0.99 and the learning rate 0.1.<br>Note that the value of epsilon in testing is equal to 0 so, that the real policy corresponds to the optimal one. The first graph shows the total reward trend in the various episodes, following the optimal policy and the real one.<br>Then the last graph shows the distribution of the total reward following the optimal policy.</p><p>The output of the script is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/0*rnLOy6zsx_jcAmsN.png" /></figure><p>mean total reward: 7.92, standard deviation total reward: 2.58</p><h4>3.3 Conclusion</h4><p>Q-learning is a very easy algorithm and the parameters (discount factor, learning rate, etc.) have a relatively good margin of error. The limitations are also seen especially as the complexity of the agent’s MDP increases.</p><h3>4 Deep Q-Learning</h3><p>A great limitation of Q-learning is the discrete observation space since the Q-values are obtained by accessing a matrix.<br>The solution adopted by the deep Q-learning is to place the Q-table with a function that approximates the Q-values, and this function is a neural network (called in this case <strong>Deep Q-Network</strong>, or DQN). When it is given a state, it approximates/predicts the Q-values of all possible actions. Deep Q-learning is therefore a deep reinforcement learning algorithm, which is a word derived from both reinforcement learning and deep learning.</p><figure><img alt="deep q learning reinforcement learning deep reinforcement learning deep learning" src="https://cdn-images-1.medium.com/max/716/0*eN9TUNaXWPc7td56.png" /></figure><p>The function that calculates the Q-values will follow the following convention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/0*9TSsNQqWGzqS2IGR.png" /></figure><p>where <em>W</em> are the parameters of the neural network.</p><h4>4.1 Neural Networks</h4><p>A neural network (or neural network, or even deep neural network) is a function approximator that takes inspiration from biological neural networks and it can be structured in many ways. Below we will see a simple example.</p><figure><img alt="neural network deep q-network q network deep q learning reinforcement learning deep reinforcement learning deep learning" src="https://cdn-images-1.medium.com/max/814/0*LpJ_oJdWfGRjAxAo.png" /></figure><p>Each neural network has an input layer that contains the inputs, hidden layers where the inputs are processed, and an output layer that contains the outputs of the neural network.<br>The parameters <strong><em>W</em> (or <em>θ</em> )</strong> are called <strong>weights</strong>, and together with the <strong>biases <em>B</em></strong>, are the ones that parameterize the prediction of the neural network. W is simply a three-dimensional matrix, where the first dimension identifies the layer, the second the next neuron, and the third the previous neuron.<br>Thinking about a linear function, <em>W</em> represents the angular coefficients and <em>B</em> is the known term.<br>The inputs of the neural network correspond to the <em>Z_1 </em>values while the outputs are the <em>A_L</em> values, where <em>L</em> is the number of total layers.<br>The <strong><em>Z</em></strong> and <strong><em>A</em></strong> values of each neuron also called <strong>input</strong> and <strong>output values</strong> (except those in the input layer), are calculated in the following way that I summarize in a diagram, with input a vector <em>x</em>:</p><figure><img alt="perceptron neuron neural network deep q-network q network deep q learning reinforcement learning deep reinforcement learning deep learning" src="https://cdn-images-1.medium.com/max/534/0*YqCh3yAFAYGvtbBT.png" /></figure><p>In general:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/0*tHHn8L3iZXf-mZIt.png" /></figure><p>where <em>σ</em> is a function called activation function which mainly has the task of preparing the input values for the next summation.<br>For example, it tries to avoid large values, although it also has other purposes that we will not go into. Many types of activation functions can vary for layers or even to individual neurons of a single layer. The most used activation functions are sigmoid, ReLU, leaky ReLU, linear function, etc.<br>In the cartpole project, I used leaky ReLU for hidden layers and linear function for the input and output layers.</p><figure><img alt="activation functions neural network deep q-network q network" src="https://cdn-images-1.medium.com/max/540/0*QYn58qHfHqajUXds.png" /></figure><p>How many neurons in the hidden layer must a neural network have? Or how many hidden layers must it have?</p><p>Both things vary from problem to problem, but we can say that to approximate complex functions we need more layers, even if there is a risk of overfitting the neural network. Regarding the number of neurons, there are some rules of thumb like the one that says that the right number is half the number of neurons in the input layer and half the number of neurons in the output layer, but in reality, we have to go by trial and error many times.</p><h4>4.2 Neural Network Optimization</h4><p><strong>Premise</strong>: From now on, we will consider the B bias as part of the W weight, so it is possible to think of an extra neuron for each layer (except the output layer), with the output value equal to 1 and connected only with the neurons of the next layer.</p><p>To optimize the neural network so that it correctly predicts all target Q-values based on a state, we compute the Q-values for each action, then via policy, we find the action to take.<br>After executing the action, through the Bellman equation we find the Q-value target and replace it with the Q-values already calculated in place of the chosen action. Finally, we optimize the neural network. The pseudocode is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*wEE3OZXzG417WxcQ.png" /></figure><p>For the real optimization of the neural network, we must identify a function to minimize. This is called <strong>cost function</strong> (or even loss function), is usually referred to with the letter <em>J</em> or <em>C</em>, which as parameters has an input vector <em>s</em>, and a vector of output target <em>q∗</em> . its purpose is to say <strong>how far apart are the prediction of the input from the target</strong>.<br>There are many types and the most common which I used is the MSE (<strong>mean square error</strong>) and which is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/0*zR4Slcpq4Au8GMRI.png" /></figure><p>Our goal is to minimize this function by varying <em>W</em>, thus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/0*-u9-LI98s4MGKuAC.png" /></figure><p>Note that to get the mean square error we should not divide everything by 2, but by the length of <em>A_l </em>, but since our goal is to minimize this function, the result will be the same and when we divide everything by 2, it will be easier to calculate the partial derivative that we will see below.<br>Now, to solve this optimization problem, we will use an algorithm called <strong>gradient descent</strong>.</p><p>The weights are initialized with random values (several distributions can be followed), and according to the partial derivatives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/0*sem0hTNuKdnpexzr.png" /></figure><p>of the cost function with respect to each weight (which corresponds to the error of that weight).</p><p>The algorithm varies the weights to minimize the cost function.<br>As an example: if the derivative is negative, it means that a value of the weight that’s greater will diminish the cost function.<br>The optimization happens therefore in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/0*2Z6QZYqC9ZNffzsf.png" /></figure><p>where <strong><em>α</em></strong> is the <strong>learning rate</strong>.<br>If <em>a</em> is too low the optimization is slow and if too high the weights will diverge.<br>So to find the right learning rate, it is better to start from a low one and gradually increase.</p><figure><img alt="gradient descent cost function neural network" src="https://cdn-images-1.medium.com/max/533/0*36l0G_hkeATJ-_hB.png" /></figure><p><strong>How do we compute the partial derivative for each weight?</strong><br>One efficient way is to use the <strong>backpropagation algorithm</strong>, which propagates the error in the neural network, from the output layer to the input layer, taking advantage of the chain rule which allows us to compute the derivative of composite functions. We will not go into detail on this algorithm.</p><p>In the next sections, we will see 3 optimizations that I implemented and used in the attached project, and then there will be an example in pseudocode.</p><h4>4.3 Gradient descent with momentum</h4><p>One of the risks of gradient descent is that it blocks the optimization at a local minimum.<br>Although there are many other more efficient alternative algorithms to this one for simplicity I used the “gradient descent with momentum”, which manages to avoid some local minima and speed up the optimization process.</p><p>It is based on updating each weight not according to its derivative but according to the weighted average of its derivatives calculated over time, giving more weight to the most recent ones (the “how much” more weight is adjusted by a parameter called <strong>momentum</strong>).</p><h4>4.4 Replay memory</h4><p>At each step, updating the weights of the neural network can vary the predictions of the network too quickly, and therefore worsen them because each update, given a state, will also influence the prediction of the Q-values of all the other states. A solution is to memorize the instructions to optimize the network (state, action, reward, done, and next state) in a memory called <strong>replay memory</strong> (or also experience replay), and also for some steps update the network by following some instructions randomly extracted from the replay memory (this number is called batch-size).<br>In general, updating the neural network with the “gradient descent with momentum” with mini-batches (a mini-batch is a series of instructions taken from the replay memory), is called “<strong>mini-batch gradient descent with momentum</strong>”.</p><p>One limitation of experience replay is giving equal importance to predictions that perhaps are secondary, with predictions that perhaps are essential for the agent to learn; a possible optimization is called “prioritized experience replay”, which we will not delve into.</p><h4>4.5 Target network</h4><p>To make the optimization more stable, it is necessary to use a <strong>target network</strong>, which is a neural network structurally identical to the main one, its difference is that in the update of a mini-batch, the prediction of the subsequent Q-values (from which the target Q-values are derived) is computed by the target network, and the weights are optimized only in the main neural network, and every few steps the weights of the target network are <strong>synchronized</strong> with those of the main neural network.</p><h4>4.6 Example of an agent in pseudocode</h4><p>Now let’s see an example of a pseudocode function of a DQN agent i.e, deep Q network and performing an episode.<br>The bandit algorithm used is epsilon decay, for the optimization is used the mini-batch gradient descent algorithm with momentum (the real backpropagation is done in the “train” function of the neural network).<br>All the complete code of the neural network is in the attached project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d35d025337c9e537876112f0c0800cec/href">https://medium.com/media/d35d025337c9e537876112f0c0800cec/href</a></iframe><h4>4.7 Application with cartpole</h4><p>In the attached application, I made a small project of deep Q-learning with the cartpole.<br>I used the following parameters:</p><ul><li>Replay memory max size = 10000</li><li>Batch size = 30</li><li>discount factor = 0.99</li><li>Learning rate = 0.0001</li><li>Number of steps to sync target network = 10</li><li>Epsilon decay = 0.99</li><li>Min epsilon = 0.01</li><li>Momentum = 0.4</li><li>For the neural network, I used 4 total layers, with 4, 50, 100, and 2 neurons respectively.</li><li>The activation function in the first neuron and the last one is linear, while for the hidden layers I used the leaky ReLU.</li><li>For the initialization of the weights, I used a uniform distribution with a minimum of -0.5 and a maximum of 0.5</li></ul><p>Out of 1000 total training episodes, I noticed that the agent got the most rewards around episode 320 so, I saved the weights of that episode to a file and used them to evaluate the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*pU9gUlVSn_2sIkwH.png" /></figure><p>You can notice that after about episode 320, the total reward starts to go down; this phenomenon is called “<strong>Catastrophic interference</strong>”, and it is a typical phenomenon of neural networks used in reinforcement learning, caused by the fact that new optimizations can worsen the ones previously done.<br>So after having inserted temporally advanced optimizations in the various episodes, the neural network may be no longer able to correctly predict during the first steps of the episodes.<br>This problem can be circumvented in offline learning (where training is separated from evaluation, very similar to off-policy learning) which is what I did but, it is serious in online learning (no difference between training and evaluation) which is the basis of a general artificial intelligence.</p><p>For the evaluation (so, the evaluation of the results), I obviously used the optimal policy, and below I calculated the distribution of the total rewards on a large number of episodes, where you can see not just a kind of approximate Gaussian but also a tendency to finish the episode between 475 and 500 total rewards. This also depends strongly on the environment.<br>however, note that the total reward never exceeds 500 because it is the maximum achievable in this environment after which the episode ends, the dashed green line is the average (388.6).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*rv8_0bVTB32pe9oI.png" /></figure><h4>4.8 Video result</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgmQn5_izEjM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgmQn5_izEjM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgmQn5_izEjM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/410b42713443c6463741e8a724ab87ec/href">https://medium.com/media/410b42713443c6463741e8a724ab87ec/href</a></iframe><h3>5 Deep distributed Q-learning</h3><p>Stanford’s “CME 323: Distributed Algorithms and Optimization” course in 2015 proposed a distributed Deep Q-learning algorithm <a href="https://stanford.edu/~rezab/classes/cme323/S15/projects/deep_Qlearning_report.pdf">here</a> based on the Downpour SGD algorithm which is an asynchronous variant of gradient descent. This algorithm defines a server, and workers, represented in the figure below:</p><figure><img alt="deep distributed q-learning deep q-learning q learning" src="https://cdn-images-1.medium.com/max/551/0*vr19YF-LDg77FPdI.png" /><figcaption>source <a href="https://stanford.edu/~rezab/classes/cme323/S15/projects/deep_Qlearning_report.pdf">here</a></figcaption></figure><p>where <em>p</em> are the weights.</p><h4>5.1 Workers</h4><p>Each worker works asynchronously and independently from the others and has the task of requesting to the server the most updated weights, maintaining a local target network that will generate data to insert into the replay memory, which is also maintained locally to calculate the gradients with mini-batches and to send them at the end of the mini-batch to the server.</p><h4>5.2 Server</h4><p>The server that maintains neural network weights locally is responsible for providing them to the workers when they require them and also updating the weights with the gradients they receive.</p><h4>5.3 Scalability</h4><p>Initially the scalability is horizontal, thereby adding workers that not only boost learning but also increase stability.</p><p>One of the risks is that the server may be too slow to respond to the workers.<br>A solution can be to increase the batch-size, and make the communication of gradients less frequent, or to scale the server vertically so, upgrade the hardware or increase the bandwidth.</p><p>Another risk is that, given the high frequency of weight updates in the server, workers may use an outdated model that slows down learning.<br>A solution may be to use optimizers called “adaptive learning rate methods”, such as RMSprop or AdaGrad.</p><h3>Attachment</h3><p><a href="https://github.com/lorenzotinfena/deep-q-learning-itt-final-project">GitHub - lorenzotinfena/deep-q-learning-itt-final-project</a></p><h3>Conclusion</h3><p>I did this article initially in Italian for a school project, then I translated it into English (with some help) with some slight corrections.</p><p>I’m not an expert and take all of this with a grain of salt. It’s just my consideration with my very little experience. For this reason, considerations, improvements, or criticisms are welcome in the comments.</p><h3>Sources</h3><ol><li><a href="http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture14.pdf">http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture14.pdf</a></li><li><a href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html">https://spinningup.openai.com/en/latest/spinningup/rl_intro.html</a></li><li><a href="https://en.wikipedia.org/wiki/Reinforcement_learning">https://en.wikipedia.org/wiki/Reinforcement_learning</a></li><li><a href="https://medium.com/@qempsil0914/zero-to-one-deep-q-learning-part1-basic-introduction-and-implementation-bb7602b55a2c">https://medium.com/@qempsil0914/zero-to-one-deep-q-learning-part1-basic-introduction-and-implementation-bb7602b55a2c</a></li><li><a href="https://towardsdatascience.com/reinforcement-learning-concept-on-cart-pole-with-dqn-799105ca670">https://towardsdatascience.com/reinforcement-learning-concept-on-cart-pole-with-dqn-799105ca670</a></li><li><a href="https://towardsdatascience.com/deep-q-network-dqn-ii-b6bf911b6b2c">https://towardsdatascience.com/deep-q-network-dqn-ii-b6bf911b6b2c</a></li><li><a href="https://towardsdatascience.com/a-beginners-guide-to-q-learning-c3e2a30a653c">https://towardsdatascience.com/a-beginners-guide-to-q-learning-c3e2a30a653c</a></li><li><a href="https://www.allaboutcircuits.com/technical-articles/how-many-hidden-layers-and-hidden-nodes-does-a-neural-network-need">https://www.allaboutcircuits.com/technical-articles/how-many-hidden-layers-and-hidden-nodes-does-a-neural-network-need</a></li><li><a href="https://medium.com/@shrutijadon/survey-on-activation-functions-for-deep-learning-9689331ba092">https://medium.com/@shrutijadon/survey-on-activation-functions-for-deep-learning-9689331ba092</a></li><li><a href="https://stanford.edu/~rezab/classes/cme323/S15/projects/deep_Qlearning_report.pdf">https://stanford.edu/~rezab/classes/cme323/S15/projects/deep_Qlearning_report.pdf</a></li><li><a href="https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/">https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/</a></li><li><a href="https://intellabs.github.io/coach/components/agents/index.html">https://intellabs.github.io/coach/components/agents/index.html</a></li><li>Mohit Sewak. Deep Reinforcement Learning: Frontiers of Artificial Intelligence. 2019.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db639d8c48b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>