<?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 Marios Skevofylakas on Medium]]></title>
        <description><![CDATA[Stories by Marios Skevofylakas on Medium]]></description>
        <link>https://medium.com/@m.skevofylakas?source=rss-373b45aa7a7b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jzLd9x1Zirw3EZq8SRMi5A.jpeg</url>
            <title>Stories by Marios Skevofylakas on Medium</title>
            <link>https://medium.com/@m.skevofylakas?source=rss-373b45aa7a7b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:01:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@m.skevofylakas/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[Quantum random walks in Q#]]></title>
            <link>https://medium.com/lseg-developer-community/quantum-random-walks-in-q-aa66f9465728?source=rss-373b45aa7a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa66f9465728</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[refinitiv]]></category>
            <dc:creator><![CDATA[Marios Skevofylakas]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 06:51:44 GMT</pubDate>
            <atom:updated>2023-04-20T06:51:44.190Z</atom:updated>
            <content:encoded><![CDATA[<p>This article presents a quantum circuit implemented in Q# simulating a random walk in an effort to showcase this new way of thinking in the world of quantum computing. A random walk is a stochastic process resulting in a path, within a domain space, constructed from a succession of random steps following certain constraints. The most trivial of examples is the random walk within the integer space Z. This walk starts from an integer in Z and taking a number of steps, with a specific step size, and following a probability distribution, ends up in another integer in Z.</p><p><em>To learn more about how to setup the environment needed for this example please refer to our article: </em><a href="https://developers.refinitiv.com/en/article-catalog/article/microsoft-quantum---implementing-quantum-discrete-fourier-transf.html"><em>Microsoft.Quantum — Implementing Quantum Fourier Neural Networks in Q# and Tensorflow</em></a><em>.</em></p><h3>The classical approach</h3><p>How would we write a random walk in a classical computer? It is really a trivial problem, here’s a python function solving it:</p><pre>def random_walk(initial_value, steps, probabilities=[0.5, 0.5]):<br>  walk = [initial_value]<br>  random_walk_probabilities= np.random.random(steps - 1)<br>  random_walk= [-1] * (steps - 1)<br><br>  for ix, probability in enumerate(random_walk_probabilities):<br>    if probability &gt; 0.5:<br>       random_walk[ix] = 1<br>    walk.append(walk[-1] + random_walk[ix])<br><br>  return walk</pre><p>Let’s visualise this and talk a little more about probabilities during the walk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*P-VDu_joQWvpSONQJX-hag.png" /></figure><p>I have highlighted two possible walk paths, we can construct a joint probability of all the steps in a path. For example in the orange path:</p><p><em>P(t3|x=3) = P(t1=+1)*P(t2=+1)*P(t3=+1)= 0.5 * 0.5 * 0.5 = 0.125.</em></p><p>If we were to encode the walk in a bit string, we could write something like orange_walk=111 with 1 being an up-step and 0 a down-step.</p><p>Using the beforementioned function, lets create a thousand random walks starting from 0 and taking 12, 1-sized steps, with a 50% up or down probability:</p><pre>initial_value = 0 <br>steps = 12<br>epochs = range(1000)<br><br>random_walk_endpoints = []<br>for shot in epochs:<br>  random_walk_endpoints.append(random_walk(initial_value,steps)[-1])</pre><p>If we plot the resulting collection of 1000 random walks we get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*KFmohSomWhnyIVc6bG-lbQ.png" /></figure><h3>Quantum structures</h3><p>To understand the quantum approach we need to first briefly touch on some of the basic structures of quantum computers, like the qubit, the equivalent of the classical bit.</p><p>Any qubit, when measured, will collapse into one of two classical states, 0 or 1, exactly as we are used to in classical computing. However, by definition a qubit is a linear combination of its basis states |0&gt; or |1&gt;. This means that a qubit can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*DBpeUcO4rudohUqRVltufA.png" /></figure><p>If we were to expand this a bit further, we would write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*rsBNlS3PyWe_Fk4CaltaCQ.png" /></figure><p>Where θ and φ can be seen in the following schematic. The probability of a qubit collapsing to either 0 or 1 is dependent on θ measuring the distance of |Ψ&gt; from |0&gt; or |1&gt;. While φ does not affect the final collapsed value of the qubit, it is a very important parameter used in many algorithms to achieve what is called phase kickback and amplification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*Ds-x2ehJN_o-KXeeRguDlQ.png" /></figure><h3>The Quantum circuit</h3><p>Superposition is a very important attribute of Quantum computing, that and entanglement. When a qubit is brought in superposition, it can store information about more than one state. This is part of the advantage of quantum computing.</p><p>Moving forward, lets consider a four steps quantum walk. To implement the quantum circuit in Q# we would write:</p><pre>operation QuantumRegisterRandomWalk() : Unit {<br>        use qubits = Qubit[4];<br>        within {<br>            for index in 0 .. Length(qubits) - 1 {<br>                H(qubits[index]);<br>            }<br>        } apply {<br>            DumpMachine();<br>        }<br> }</pre><p>We visualise the quantum circuit in Jupyter notebook using the magic command <em>%trace QuantumRegisterRandomWalk</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*MgJ2-mB3uPwD_g62Yzl9wA.png" /></figure><p>Using the magic command <em>%debug QuantumRegisterRandomWalk</em>, we can see that all paths are inherently covered in this four qubit quantum circuit and by definition the probability constraints of the classical walk are met due to the default superposition behaviour. All states have the same probability of collapse. This means that the problem of the random walk is solved just by circuit design. Simulating the circuit we get the classical result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUdMYOLs21HUFWxMLK18Ng.png" /></figure><p>We can see that they follow the same behaviour as the classical approach with all walk paths having the same probability to materialise.</p><h3>Conclusions</h3><p>In this article, we implement a quantum circuit in Q# to tackle a classical mathematical problem, that of the random walk.</p><p>The scientific community of quantum computing has made significant progress this last few years, and the roadmap ahead is expected to lead us from Noise Intermediate Scale Quantum (NISQ) devices to error corrected devices and a universal quantum computer bringing significant value through unprecedented computational capabilities to many disciplines in the industry.</p><p>If you would like to explore more complex Quantum use cases please read our relevant articles on Quantum computing on our <a href="https://developers.refinitiv.com/en">Developer Portal</a>!</p><h3>References</h3><p>SOURCE CODE</p><ul><li><a href="https://github.com/Refinitiv-API-Samples.html"><strong>Explore all Refinitiv API Samples on GitHub</strong></a></li></ul><p>RELATED APIS</p><ul><li><a href="https://developers.refinitiv.com/en/api-catalog"><strong>Explore all APIs</strong></a></li></ul><p>RELATED ARTICLES</p><ul><li><a href="https://developers.refinitiv.com/en/article-catalog/article/microsoft-quantum---implementing-quantum-discrete-fourier-transf.html"><em>Microsoft.Quantum — Implementing Quantum Fourier Neural Networks in Q# and Tensorflow</em></a></li><li><a href="https://developers.refinitiv.com/en/article-catalog/article/tensorflow-variational-quantum-neural-networks-in-finance">TensorFlow Variational Quantum Neural Networks in Finance</a></li><li><a href="https://developers.refinitiv.com/en/article-catalog/article/option-pricing-using-qiskit-and-eikon-data-api">Options pricing using Qiskit and Eikon data API</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa66f9465728" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/quantum-random-walks-in-q-aa66f9465728">Quantum random walks in Q#</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A random walk in Quantum computing]]></title>
            <link>https://medium.com/lseg-developer-community/a-random-walk-in-quantum-computing-32c77a610d5b?source=rss-373b45aa7a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/32c77a610d5b</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[quantum]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <dc:creator><![CDATA[Marios Skevofylakas]]></dc:creator>
            <pubDate>Sat, 26 Jun 2021 06:49:22 GMT</pubDate>
            <atom:updated>2021-06-26T06:49:22.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*YkAwK1IL-QCzuJNmxW5pZA.png" /></figure><p>In mathematics, a random walk is a stochastic process resulting in a path, within a domain space, constructed from a succession of random steps following certain constraints. The most trivial of examples is the random walk within the integer space Z. This walk starts from an integer in Z and taking a number of steps, with a specific step size, and following a probability distribution, ends up in another integer in Z. This article presents a simplistic quantum circuit simulating a random walk in an effort to understand this new way of thinking in the world of quantum computing.</p><h3><strong><em>The classical approach</em></strong></h3><p>How would we write a random walk in a classical computer? It is really a trivial problem, here’s a python function solving it:</p><pre>def random_walk(initial_value, steps, probabilities=[0.5, 0.5]):<br>  walk = [initial_value]</pre><pre>  random_walk_probabilities= np.random.random(steps — 1)<br>  random_walk= [-1] * (steps — 1)<br>  for ix, probability in enumerate(random_walk_probabilities):<br>    if probability &gt; 0.5:<br>       random_walk[ix] = 1<br>    walk.append(walk[-1] + random_walk[ix])</pre><pre>  return walk</pre><p>The function takes three parameters:</p><ul><li>The initialization integer point of the walk</li><li>Steps is the number of steps that we are doing within Z during the walk</li><li>Probabilities initialised so that the walk takes an upwards step (+1) or a downwards step (-1) with equal probability.</li></ul><p>Let’s visualise this and also talk a little more about probabilities during the walk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*P-VDu_joQWvpSONQJX-hag.png" /></figure><p>I have highlighted two possible walk paths, we can construct a joint probability of all the steps in a path. For example in the orange path:</p><p><em>P(t3|x=3) = P(t1=+1)*P(t2=+1)*P(t3=+1)= 0.5 * 0.5 * 0.5 = 0.125.</em></p><p>You will find that this path probability stays the same for all possible three steps paths. If we were to encode the two walks in a bit string, we could write something like orange_walk=111 while green_walk = 001 with 1 being an up-step and 0 a down-step.</p><p>Using the beforementioned function, lets create a thousand random walks starting from 0 and taking 12, 1-sized steps, with a 50% up or down probability:</p><pre>initial_value = 0 <br>steps = 12<br>epochs = range(1000)</pre><pre>random_walk_endpoints = []<br>for shot in epochs:<br>  random_walk_endpoints.append(random_walk(initial_value,steps)[-1])</pre><p>If we plot the resulting collection of 1000 random walks we get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*KFmohSomWhnyIVc6bG-lbQ.png" /></figure><p>As for the distribution of the walk, we can plot a boxplot that will quickly reveal expected value, quantiles and outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*oeuYxRQ6OS4HxxtlnOq_rw.png" /></figure><h3>The Quantum approach</h3><p>To understand the quantum approach we need to first briefly touch on some of the basic characteristics of quantum computers, like the qubits and their ability to stay in superposition states.</p><p>Any qubit, when measured, will collapse into one of two classical states, 0 or 1, exactly as we are used to in classical computing. However, by definition a qubit is a linear combination of its basis states, and by convention one of the popular basis being |0&gt; or |1&gt;. This means that a qubit can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*DBpeUcO4rudohUqRVltufA.png" /></figure><p>If we were to expand this a bit further, we would write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*rsBNlS3PyWe_Fk4CaltaCQ.png" /></figure><p>Where θ and φ can be seen in the following schematic. The probability of a qubit collapsing to either 0 or 1 is very much dependent of θ effectively measuring the distance of |Ψ&gt; from |0&gt; or |1&gt;. On the other hand, the parameter φ does not affect the final collapsed value of the qubit. However it is a very important parameter in the quantum computing space used in many algorithms to achieve what is called phase kickback and amplification. We refer to φ as the phase of the qubit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*Ds-x2ehJN_o-KXeeRguDlQ.png" /></figure><p>Furthermore, by definition a² + b² = 1 ιin the earlier qubit representation, which means that a² and b² are the probabilities of the qubit collapsing into one of the two basis states |0&gt; or |1&gt; respectively.</p><h3>The Quantum circuit</h3><p>Let’s start with the simplest of quantum circuits, a single qubit. I am using Qiskit to write this prototype. The circuit would pretty much look quite empty so I’m also adding a measurement. Any measurement in quantum computing results in a collapse of state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*DnHmkMEgQULewhVDkMn5Zw.png" /></figure><p>So if we print the Bloch-sphere for this qubit we would see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*UtEDFW8M-6Ho6_5mnHvFzg.png" /></figure><p>All qubits are by default initialised to the |0&gt; state as a result any measurement of this qubit will output a 0 classical result with 100% probability.</p><p>Superposition is a very important attribute of Quantum computing, that and entanglement. Effectively, when a qubit is brought in superposition, it can store information about more than one state. This is part of the advantage of quantum computing. With a classical bit we can store two possible values but only one at a time. With a qubit we can store information for both 0 and 1 at the same time. As a result, e.g. 4 qubits can simultaneously store information about 16 states, whereas 4 bits again can only store one out of the possible 16 values.</p><p>Let’s put that qubit in superposition. The Hadamard gate is the main gate for the task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*3zGV_2cuSZijQGARJisyog.png" /></figure><p>How does the Bloch-sphere look now? The qubit state vector has now moved to its |+&gt; state on the x axis. As mentioned before, the probability of collapse to a classical 1 or 0 is the distance the vector has to travel to get to |0&gt; or |1&gt;. There is now a 0.5 probability of measuring 0 or 1. We say that the qubit is now both 0 and 1 with 50% probability. This new way of thinking borrows its basis from Quantum mechanics and experiments like the double slit experiment where it is proven that a photon is both particle and wave at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*WMwRcxX3iHtQ8caMYAc6CA.png" /></figure><p>Moving forward, lets consider a four steps quantum walk. To express it in a quantum circuit we could use something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*CjI1ruUYlXGYuISy1Olc_g.png" /></figure><p>Looking at the state Q sphere we can see that all paths are covered inherently in this four qubit quantum circuit and by definition the probability constraints of the classical walk are met due to the default superposition behaviour. All states have the same probability of collapse, 12.5%. This means that the problem of the random walk is solved by circuit design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*8HPbAIQGjoA_plt2aETviw.png" /></figure><p><strong><em>Running the circuit in a quantum computer</em></strong></p><p>The full 12 steps quantum walk circuit looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*BNOHWReGFeO69pz_Pxp9ZA.png" /></figure><p>We can now execute the random walk circuit on a real Quantum computer on IBMQ. As this is a stochastic experiment, just by measuring the circuit we will collapse it every time in a unique 12 steps walk. Using the IBMQ Qiskit provider we can connect to IBM Quantum and execute the circuit in the appropriate hardware. Device ibmq_melbourne_16, a 15 qubits quantum computer on IBMQ is able to facilitate this 12 qubits circuit.</p><p>The results returned by ibmq_melbourne_16 contain the random walk paths and their corresponding frequency:</p><pre>{&#39;110001100100&#39;: 2, &#39;110001110000&#39;: 2, &#39;110001110010&#39;: 1, &#39;110001110011&#39;: 1, &#39;110001110111&#39;: 1, &#39;110010001001&#39;: 1, &#39;110010001010&#39;: 2...}</pre><p>Having collected the results, through the classical registers connected to our quantum registers, we can finalise the analysis. Here’s the plot of estimated random walks and the boxplot distributions and we can see that they follow the same behaviour as the classical approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*3C9Vx-vioBJZuhA1oUdenA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*E0SdF0t4sUbz09xmvPe3WQ.png" /></figure><h3>Conclusions</h3><p>This article is an early attempt to explore the world of quantum computing using a baseline circuit to tackle a classical mathematical problem, that of the random walk. The quantum circuit implemented was kept simple in an effort to focus more on the very important concept of superposition. Next articles will take a deeper dive in the structural components of the technology and there is quite a bit to touch on from base structures and pulses to simulations, error correction mechanisms and algorithms. The scientific community of quantum computing has made significant progress this last few years, and the roadmap ahead, while perhaps somewhat long, is expected to lead us from Noise Intermediate Scale Quantum (NISQ) devices to the final goal of error corrected devices and hence a universal quantum computer bringing significant value through unprecedented computational power to many disciplines in the industry.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32c77a610d5b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/a-random-walk-in-quantum-computing-32c77a610d5b">A random walk in Quantum computing</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence in music]]></title>
            <link>https://medium.com/@m.skevofylakas/artificial-intelligence-in-music-d7ec7872ee59?source=rss-373b45aa7a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7ec7872ee59</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Marios Skevofylakas]]></dc:creator>
            <pubDate>Tue, 25 May 2021 04:57:32 GMT</pubDate>
            <atom:updated>2021-05-26T03:16:08.601Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*KucUYa_tCJBMjFefAkBiMg.png" /></figure><p>Western music comprises of 12 distinct pitches. That is its entire active vocabulary, 12 notes from A to G, counting sharps or flats, whichever way you see it. From this limited vocabulary, humanity has expressed its creativity through time and has seen the creation of masterpieces from great composers such as Ludwig van Beethoven, Wolfgang Amadeus Mozart, Antonio Vivaldi, Frederic Chopin and so many more. In all honesty, there is quite a bit more to making music than the vocabulary itself. One would need to envision a rhythm for her vocabulary and decorations revealing the way the musical score should be expressed on an instrument. Most importantly, one should be able to piece the puzzle together in melody and harmony. The product of all this is more often than not, a result of emotional and intellectual prowess expressed through knowledge and finesse.</p><p>Artificial intelligence (AI) on the other hand is a different form of art, a technological art that has now matured and is used across industries. This is a result of the efforts of many years of hard work from researchers, applied scientists and practitioners across the globe. Recent developments in Deep learning have introduced neural networks and processes that mimic the way humans learn through experience. Would it therefore be possible for an AI system to learn from existing music and generate new musical pieces ? This is the purpose of this study, to explore the likelihood of using an AI structure to generate music. To accomplish that we turn our attention to Recurrent Neural Networks (RNNs).</p><h4>Training grounds</h4><p>In my mind, music is the perfect training ground for AI for a simple reason, there is no noise in the data! How could it be otherwise? It would not be music! Therefore, since the data is already optimised, all that is left, is digitise and encode it to an AI friendly format. Luckily on that side we have two very powerful tools at hand, Musical Instrument Digital Interface (MIDI) files and Music 21.</p><p>MIDI files contain instructions that a personal computer can turn into sound, either by a software interface, or by forwarding them to the appropriate hardware. Entire musical scores or even symphonies can be encoded in a MIDI file.</p><p>Music21 made by cuthbertLab MIT, is a wonderful python module that can read and analyse MIDI files. It can provide an astounding breadth of information on many technical aspects of a musical score. By analysing a MIDI file using Music21, one can discover anything from the type of the instrument the score was designed for, to time signatures, pitch, rhythm, notation, curation and a lot more.</p><h4>Recurrent Neural Networks</h4><p>Recurrent Neural Networks (RNNs) were first introduced in the 1980s in their early form, the Hopfield network. The Long Short Term Memory (LSTM) and its variations, are types of RNNs able to analyse datasets holding sequential data. The usual underlying thinking is that the expected behaviour of a system is dependent on its previous behaviour in time. The LSTM is able to store the previous states of the system in memory and blend them with the current state to analyse and predict future behaviour. One of the important characteristics of the LSTM is that it addresses a key problem often encountered in RNNs, their inability to analyse very long complex sequences. This is the well known problem of the vanishing or exploding gradients and it emerges when derivatives during training become ever so small or large, harming the neural network’s learning efficacy. The problem was first addressed in 1994 through the LSTM and later with the Gated Recurrent Unit (GRU). I will not go into details about the various architectures and functionality or training processes of LSTM networks as there is enough bibliography out there for the curious mind. As a birds-eye view, the next graph shows the concept of an RNN. Essentially, a memory layer is formulated by choosing a part of the output and feeding it back again as input to the neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*k4KgHyrh4M0CbmY7MCjBxg.png" /><figcaption>Schematic 1. The Recurrent Neural Network</figcaption></figure><p>Should one unravel the looping structure of the RNN, she’ll discover a more familiar sequential neural network structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhiHWgVAE7Yi0uD6zE38Wg.png" /><figcaption>Schematic 2. Unravelling the RNN into sequential layers</figcaption></figure><p>In the core of the traditional RNN lies a typical Artificial Neural Network (ANN) layer applying some kind of function, like e.g. the hyperbolic tangent, to the sum of its inputs that may or may not excite its neurons. The LSTM however is a bit more complex. Aside the usual neuron there exist several more structures around it, the gates, that can optionally add or remove information during the learning process. Here is a schematic of an LSTM cell and its various components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DeavAJnOJQ1cs4n8pXHGw.png" /><figcaption>Schematic 3. One of the popular architectural designs of the Long Short Term Memory cell</figcaption></figure><p>Amongst the various modules of the architecture we can see:</p><ul><li><em>The Forget Gate,</em> generating a 0 or 1 for every input in C(t) discarding any non useful information.</li><li><em>The Learn Gate</em>, comprising of a sigmoid and a hyperbolic tangent layer which combines short-term memory with current inputs to decide what new information will be stored in the cell’s state.</li><li><em>The Remember Gate, </em>which is essentially responsible for the new output. It combines long-term memory and short-term memory.</li><li><em>The Use Gate</em> where long-term, short-term memory and current input are combined to produce the output.</li></ul><p>Combine many LSTM cells in a sequence and you have a recurrent Deep learning structure looking like the one we show in schematic 2. There exist many different LSTM architectures such as ones that add peepholes to the gates or couple gate layers between them but this study suffices to the original architecture.</p><h4>LSTM-friendly MIDI scores</h4><p>In this study, a data engineering module was implemented that can analyse the piano parts of several MIDI files from some of my favourite classical composers.</p><p>Let’s first explore the output we can produce from Music21, there is the possibility to extract verbal information about a music score. Here’s an extract from the data and feature engineering part of the study. Information can be sequentially stored as we see bellow:</p><pre>...<br>F in octave 4 Quarter Note<br>F in octave 4 Quarter Note<br>Quarter Triplet (2/3 QL) Rest<br>Quarter Triplet (2/3 QL) Rest<br>E in octave 4 Quarter Note<br>E in octave 4 Quarter Note<br>Quarter Triplet (2/3 QL) Rest<br>Quarter Triplet (2/3 QL) Rest<br>D in octave 2 Eighth Triplet (1/3 QL) Note<br>D in octave 4 Half tied to 16th (2 1/4 total QL) Note<br>D in octave 2 Eighth Triplet (1/3 QL) Note<br>D in octave 4 Half tied to 16th (2 1/4 total QL) Note<br>D in octave 2 Eighth Triplet (1/3 QL) Note<br>16th Triplet (1/6 QL) Rest<br>16th Triplet (1/6 QL) Rest<br>16th Triplet (1/6 QL) Rest<br>...</pre><p>Further analysing the score with Music21, we can start engineering interesting streams that we can then transform to LSTM tensor inputs. Here’s a notes stream discovered in the MIDI files, we can see the pitch as well as its octave:</p><p>[‘C#4’, ‘F#4’, ‘F#4’, ‘G#4’, ‘G#4’, ‘A4’, ‘A4’, ‘C#4’, ‘F#4’, ‘F#4’, …]</p><p>Here is another stream with the corresponding beat durations:</p><p>[‘4/3’, ‘1/3’, ‘1/3’, ‘1/3’, ‘1/3’, ‘1/3’, ‘1/3’, ‘4/3’, ‘1/3’, ‘1/3’, …]</p><p>Everything else regarding the score is provided on the metadata e.g. this happens to be a 4/4 time signature score.</p><p>There’s many approaches to building the DNN structure, one could be merging the two streams together to consolidate information. Another one could be to build and sync two different structures for each stream and sync their outputs. The methodology on the feature engineering, guiding the rest of the structure, is pretty much personal preference and intuition. Here’s the result of the merge, there is quite a bit of information here on every beat, duration, note and octave.</p><p>[‘4/3_C#4’, ‘1/3_F#4’, ‘1/3_F#4’, ‘1/3_G#4’, ‘1/3_G#4’, ‘1/3_A4’, ‘1/3_A4’, ‘4/3_C#4’, ‘1/3_F#4’, ‘1/3_F#4’, …]</p><p>There is a bit more into making this stream LSTM training-ready but I will not go into the details as everyone follows her own methodology.</p><h4>The results</h4><p>After several cycles of optimisations and training, the results can be characterised pleasing to the ear. The system was written to learn on the data and then pick a random small part of a MIDI file as the “inspirational part” for the AI. This inspirational part, a few notes, is used as a seed to initialise the LSTM and enable it to finish the phrase. More specifically, eight beats or 2 bars on a 4/4 time signature were used as the inspiration seed and the AI would write another 12 bars after that. Here is a sample of three generated phrases, you can hear that there is a certain melody to them, some interesting variations as well as meaningful repetitions, occasionally you will also hear that odd note.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F553621447%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F553621447&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1143846310_295x166&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="486" height="360" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfd4837feb2accc933e489c17e372e36/href">https://medium.com/media/dfd4837feb2accc933e489c17e372e36/href</a></iframe><p>There is quite a bit that can be done to improve this AI structure from variations in architecture to enhanced feature engineering that will allow it to further explore the wealth of information provided from Music21. The initial results however are quite promising and suggest that indeed there can be music in Artificial Intelligence and perhaps the other way around too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7ec7872ee59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stochastic connections in Neural Networks using Tensorflow]]></title>
            <link>https://medium.com/@m.skevofylakas/stochastic-connections-in-neural-networks-using-tensorflow-44abd7e74d6e?source=rss-373b45aa7a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/44abd7e74d6e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Marios Skevofylakas]]></dc:creator>
            <pubDate>Sat, 01 May 2021 14:18:45 GMT</pubDate>
            <atom:updated>2021-05-01T14:18:45.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*JdF-DAqcrZ65AH_oze1SGg.jpeg" /></figure><p>This article revisits a research that started as an idea a couple of years ago, on one of my favourite subjects, Artificial Intelligence. Back then I developed some initial designs, and wrote the first lines of code to start implementing it. Lately, I revisited it, with the intention to rewrite it using one of the existing cutting edge AI frameworks, Tensorflow. This article shares some thoughts on this AI structure, a Stochastically Connected Neural Network (SCNN).</p><p><strong>Evolution of the human brain — The Neocortex</strong></p><p>“<em>So, how does intelligence work?</em>”. The purpose of the next paragraphs is to give a broad understanding of the basic structures that govern intelligence .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*clgh2UvcO2ldGBbdcA10xg.png" /></figure><p>The human brain is one of the most complex structures in nature. It consists, during its middle age, of more than 100 billion neurons. The evolution of the human brain started approximately half a billion years ago, when invertebrates, such as ants, begun crawling the earth in search of food. Later, vertebrates developed to amphibians, some of which, evolved to reptiles and thereafter to mammals. When you look at the human brain, almost everything you see is neocortex, a relatively recent creation of evolution. Prior to mammals, animals like reptiles had relatively small brains with highly specialised areas for processing sensory information. However, in mammals, a new part of the brain evolved significantly, the neocortical part, acting as an additional processing layer on top of the older brain.</p><p>Going into a detailed description of the human brain would require specialised knowledge and I have very limited expertise to be able to write on the subject in much detail. However, for the purpose of this research, I would like to focus on some of the characteristics of this part of the brain, the neocortex. It is the largest part of the outer layer of the brain and its newest evolved part. The rest of the brain, the limbic system, and the reptilian complex has a significantly different cellular organization. In humans, 76% of the entire brain is neocortex. It consists of the grey matter, the outer part, surrounding a larger inner area called the white matter. The grey matter is a very thin layer, about 2–4 mm thick. It’s structure is relatively uniform and consists of six horizontal layers. This is where neurons live in structures called cortical columns. The white matter is mostly wiring, a collection of axon and dendrite structures. Interestingly, the grey matter’s maze-like folded structure consisting of the “sulci” and “gyri”, as they are called, is simply the solution nature has found to fit an area of such volume inside our head’s finite space.</p><p>Another interesting detail is that within these six layered columnar structures, the neocortical connections between layers are distance anticorrelated. This means that the closest that two neurons live together, the higher the probability is that they will stay connected to each other.</p><p>The relationship of the neocortex with the rest of the brain is that of a complex controller to a collection of satellite processing systems. It acts as a consolidator of the output of the other parts of the brain. Such outputs are the result of complex specialised processes, like sensory and motor skill controls, that each part of the brain is responsible for. By receiving these responses and consolidating them, the neocortex can decide on an overall reaction behaving as a complex memory function able to pursue multistep decisions.</p><p><strong>Intelligence — The Neural Network</strong></p><p>At the heart of intelligence lies the neuron. A neuron receives an electric pulse from connected neurons via its dendrites. If the sum of the signal is sufficiently strong, it will excite itself, pushing a pulse to its axon and passing it to connected neurons with its terminals. Many connected neurons will form a neural network able to process and solve complex problems. Axons are remarkable constructs able to transmit a pulse with zero signal weakening at long distances with speeds of up to 100 meters per second. As an example, sending a message from your head to your toe activates the dorsal root ganglion a nerve comprising of unipolar-type neurons comprising of two axons. The first one starts from the primary motor cortex within the brain and runs through to the spinal cord base to connect to the lower motor neuron. The latter extends its axon all the way to your toe’s muscles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*xt6kXBNLdcxxcGy8H8RyLg.jpeg" /></figure><p>Neural network structures such as this will form families of networks or areas within the brain that start specialising in a specific function. For example, the dorsolateral area (dorsal equals top and lateral closer to the outside) of the prefrontal cortex is crucial for our working memory. It facilitates the contents of our thoughts at any given time; a particularly important constituent for any cognitive function, problem solving process or decision making.</p><p><strong>Artificial intelligence — The Artificial Neural Network</strong></p><p>In the world of computing, the equivalent of the physical neuron is the mathematical construct of the artificial neuron. An artificial neuron will apply a transfer function to all its weighted inputs, usually a summation, and will pass the result through a continuous and differentiable activation function to produce its output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*qfQYBFha5QKBguFXmLWPHA.png" /><figcaption>The artificial Neuron and its digital architecture</figcaption></figure><p>One of the most established structures of the Artificial Neural Network is a sequence of connected layers of neurons. Several techniques can alter the structure of the network (activation functions, signal recursion) but predominantly, each layer will transform its input and will push an output to the next layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*u6MakV7oJJ06EjatMau4OA.png" /><figcaption>A densely connected Artificial Neural Network</figcaption></figure><p>Turning to the SCNN, a signal leak in between non-consecutive layers is introduced in the architecture. The design mimics the spatially stochastic neural connectivity structure of the neocortex. The next graph shows how the previous network might look like with stochastic leaks between non-sequential layers. The structure resembles the Liquid State Machine (LSM) or the Extreme Learning Machine (ELM), with the introduction of probabilistic connection materialisation anti-correlated to distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*QYsJzBxwKOjeq4CD4Pb8YQ.png" /><figcaption>An Artificial Neural Network with intra-layer stochastic connectivity</figcaption></figure><p><strong>Writing the SCNN on Tensorflow</strong></p><p>For the purposes of this prototype a proprietary layer was developed using the Tensorflow existing base <em>tf.keras.Model</em> and <em>tf.keras.layers</em> classes. This is a layer where the probability of its neurons being connected with all the previous layers in a Deep Neural Network (DNN) is stochastically decaying with distance. Therefore, if you had a 5 layers DNN, the layers closer to each other will have a higher probability of being connected compared to layers further apart. This means that a neuron from layer 1 will have many connections with layer 2 but will also hold a few connections with layer 3, fewer with layer 4 and there may or may not exist some with layer 5 and so on and so forth. The SCNN structure when implemented in Tensorflow is easily instantiated, used, or tweaked within the framework. The fact that the new layers and model can extend the relevant Tensorflow classes allows everything in the AI lifecycle process to stay the same. All the usual modules to monitor, optimise, train, evaluate and predict, that are available from the Tensorflow framework can be directly utilised.</p><p><strong>Testing the SCNN on the MNIST dataset</strong></p><p>The MNIST dataset was chosen to measure performance of the SCNN. The dataset consists of 60000 images of handwritten digits from 0 to 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*a7kMuo72eomPgxzi7KKT1w.png" /><figcaption>Sample of the MNIST Dataset</figcaption></figure><p>For the training set, 50000 images were randomly selected, and 10000 images were held for validation. The training and evaluation cycles were repeated 50 times and a small number of 5 training epochs was used at each cycle. No convolutional layers or other optimisation structures were used;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*DWJUhi2mjQrlNaEreH_3tg.png" /></figure><p>The SCNN before any optimisations is showing an average accuracy of 97.82% an increase of approximately 1% compared to a traditional fully connected DNN. The increased complexity of this new structure however, introduces higher computational demand. For example, for the DNN, the average 5 epochs training time on the MNIST dataset is 6.92 secs. The SCNN however, takes 42.1 secs on average to train and shows significant variations in training times between different episodes. The reason for this lies within the stochastic behaviour of connections inside the SCNN structure. All timing metrics were measured on a 7th generation, 4-cores i7 laptop with a 1050GTX GPU that was utilised during training.</p><p><strong>Future Work</strong></p><p>This article is introducing the concept of stochastic connectivity between neural network layers and its design thinking, deriving from elements of neuroscience. There are quite a few thoughts that can be implemented on the SCNN as well as more experiments that can be done on specific use cases. The structure can be injected within larger architectures as a leading or a final DNN. More robust connections can be introduced between neurons simulating lagging effects. Neuron importance can be injected in the stochastic equations. The layer cores can be redesigned to optimise for performance during training. Visualisation layers can be integrated within the SCNN allowing the use of grad-CAM for better interpretation of results in image processing cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44abd7e74d6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning using Unity ML-agents — part II]]></title>
            <link>https://medium.com/@m.skevofylakas/deep-reinforcement-learning-using-unity-ml-agents-part-ii-83212b501ef9?source=rss-373b45aa7a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/83212b501ef9</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[virtual-reality]]></category>
            <dc:creator><![CDATA[Marios Skevofylakas]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 04:44:35 GMT</pubDate>
            <atom:updated>2021-05-01T09:07:43.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*lYubpo4hZdM0G_vr7CwHzA.png" /></figure><h3>Deep Reinforcement Learning using Unity ML-Agents — part II</h3><p>The first part of this article series presented the current AI landscape, the scene that models the prototype, the tools used to create it as well as the physics model implemented. A brief introduction was also given regarding the lifecycle of Deep Reinforcement Learning (DRL). This article presents the structures involved in this DRL system, the training process and the final solution rendering. As a reminder, in this prototype we ask an AI agent to navigate a 3D ship model through a certain terrain formation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cA8yuAecuWWHlWI6tP-KWQ.png" /><figcaption>A fictional scenario where-in a 3D ship model needs to navigate past this terrain formation.</figcaption></figure><h4>The Deep Neural Network structure</h4><p>When it comes to using ML-Agents for DRL in Unity, all the usual hyper-parameters that can be used in DRL are accessible and can be tweaked through a yaml configuration file. Hyperparameters like batch_size, buffer_size, learning rate, gamma, the structure of the DNN and many more are available.</p><p>The gamma parameter is a rather interesting one, it represents the discount of future rewards during the learning process. Essentially, this forces the DNN to weigh the effect of its current decision and therefore the effects it will have on future rewards. Should the agent go for a high reward now or would that decision affect its future in a way that will not allow it to further capitalise on rewards?</p><p>In this prototype a DNN with 2 hidden layers of neurons was used. Tensorflow constructs the input layer leveraging the Unity and ML-Agents integration. The final structure is derived by inspecting the Ray-Perception Sensor component and any requested observation vector.</p><h4>Observation vector</h4><p>The observation vector consists of all the environment variables the AI-system monitors throughout its training process. A ray-casting system was implemented originating from the model centre. It extends to infinity and is designed to detect any object in the scene that is marked as terrain. The next scene frame shows the ray-casting system, notice how rays are coloured red if they hit terrain and white otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LYc3-6fe7JLhaJauRJnAA.png" /><figcaption>The ray casting system uses 10 rays to detect terrain. Each ray returns a 4D vector data denoting direction plus magnitude.</figcaption></figure><p>Besides the ray-casting system we provide another 18 observable features from the vessel’s status and environment including velocity, engine, bow thruster status, distance to destination and more. Those combined with the 10 x 4 observable ray-casts result in a total of 56 observable features.</p><h4>Rewards Policy</h4><p>The reward policy which is what allows the AI agent to learn from its behaviour. It is probably the hardest part to calibrate and a very important factor in successfully training a DRL AI agent. A few examples of rewards in this system include:</p><ul><li>A reward at every iteration that the AI agent is getting closer to its destination.</li><li>A reward if it manages to keep rotational forces low and a penalty otherwise.</li><li>A penalty whenever it collides with any object in the scene.</li></ul><p>The design and balancing of the reward system is a granular process that is fully proprietary depending on the problem at hand. Imbalancing of rewards and penalties can potentially prevent algorithms from converging to a solution.</p><h4>Tensorboard training monitoring</h4><p>One of the great features of ML-Agents is that the framework by default stores Tensorboard logs during the process of agent training. These training logs can be directly imported or monitored in real-time from the Tensorboard UI, allowing for close studying of the entire training process. This provides important information allowing us to understand if the observable vectors and reward policy are such that will allow the DNN to solve the problem. It is frequently the case that the initial designs of such systems will not easily converge. As an example, during the early stages of the design of this system, only the velocity vector was used in order for the AI to understand the model’s inertia. However, the AI ended up taking decisions abruptly accelerating and colliding with terrain. Adding rotational forces vector observables greatly smoothed out this behaviour. Here is a schematic of the Tensorboard interface during several training cycles in the prototype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*D2h7wy7N86TyQ6g8txO85A.png" /><figcaption>Policy metrics during the training process</figcaption></figure><h4>Environment logging</h4><p>A very important aspect of any AI implementation is continuous logging of the environment the agent resides in and its decisions. In this prototype various parameters where stored in every rendered frame including position, rotation, velocity, rudder rotation, engine RPM, rewards and cumulative reward. This allowed for better understanding of the state of the environment in every frame and why the AI system is taking a decision at any given time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*_hX3ZEpMSqz2WP_ZuZGpkw.png" /><figcaption>Logging the AI agent’s environment</figcaption></figure><p>As an example, the next graph shows the velocity and rudder angle during a specific episode of training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*CdGLkbbJVs-kmWGZLJTTtA.png" /><figcaption>Graphing Velocity vs Rudder Rotation in a specific training episode</figcaption></figure><h4>The training ground</h4><p>One of the great things of setting up a virtual training ground for a DRL agent in Unity is that once you have modelled the scene and the agent you can infinitely replicate it. For this prototype, the agent was replicated eight times. By replicating the agent, we get to feed ML-Agents and the DNN with eight times more data on every episode effectively creating a swarm of agents scanning the problem and trying to find an optimal solution. Deciding on the replication factor is purely a matter of computational power at hand. One important detail is that these agents are disconnected from each other. This means that no-one agent knows the states the other agents are in. Moreover, there exists a single AI core that governs the whole process receiving as inputs the observables and action — state transitions of each agent. Each agent’s episode will end whenever it collides with terrain and agents are not able to collide with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BjFo0VCe67c3bVO8OMQgNA.png" /><figcaption>The LIDAR system casting 24 rays detecting terrain. Each ray returns the a 4D vector data denoting direction plus magnitude.</figcaption></figure><h4>Results</h4><p>After 14 hours of training the AI agent has converged to a final solution presented in the next video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F503630593%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F503630593&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1041926088_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1040" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa8c7b4978cfd4ed60fde75a9ae363ad/href">https://medium.com/media/aa8c7b4978cfd4ed60fde75a9ae363ad/href</a></iframe><p>As we can see in the solution video, the 3D model manages to navigate the route without colliding with terrain. The solution might seem straight forward at first glance, however, one has to think about the myriad parameters that this AI system has to navigate in real-time as it explores the problem space.</p><p>An interesting observation during the early stages of the implementation was that the AI system, as it was exploring the problem space, started taking decisions leading to excessive rotations, rendering the solution unrealistic.</p><p>Research using Tensorboard and the environment logs led to an interesting conclusion. What was happening was a result of what is called the curiosity factor. While the AI could find a realistic solution during the early episodes of training, a high curiosity factor led it to continue exploring new ways to optimise its solution.</p><h4><strong>Conclusion</strong></h4><p>Artificial Intelligence is an exciting technology able to transform our lives in many ways. Deep Reinforcement Learning is one of the cutting edge methodologies closely imitating the way we learn from experience. The applications of the technology are infinite and ever so promising across all industries. This series of articles explored the DRL methodology in the context of a simulation of an autonomous navigation system using Unity ML-Agents. In the next part of this article series we will explore ways to turn this prototype into a fully VR-enabled application on Oculus Quest 2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83212b501ef9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning using Unity ML-Agents — part I]]></title>
            <link>https://medium.com/@m.skevofylakas/deep-reinforcement-learning-using-unity-ml-agents-part-i-62a020e96dd?source=rss-373b45aa7a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/62a020e96dd</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[shipping]]></category>
            <category><![CDATA[autonomous-vehicles]]></category>
            <dc:creator><![CDATA[Marios Skevofylakas]]></dc:creator>
            <pubDate>Wed, 28 Apr 2021 05:28:11 GMT</pubDate>
            <atom:updated>2021-05-01T14:16:55.280Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*lYubpo4hZdM0G_vr7CwHzA.png" /></figure><h3>Deep Reinforcement Learning using Unity ML-Agents — part I</h3><p>Deep reinforcement learning (DRL) is one of the most recent Artificial Intelligence (AI) methodologies that has been applied in several areas of the industry. This series of three articles will be exploring a prototype of DRL within the context of a significantly complex problem, that of autonomous navigation systems.</p><p>The prototype was written using Unity, C# and Tensorflow ML-Agents. The first part of the article series mostly explores the existing AI ecosystem and the Unity structure of the prototype. The second part dives deeper into the implemented AI process. Finally, the last part will present the methodology to turn this prototype into a Virtual Reality prototype that can run on a VR headset such as the Oculus Quest 2 using the newest XR framework within Unity.</p><h4>Current AI landscape</h4><p>Before diving a bit deeper to the prototype, let’s spend a little time on a taxonomy of the current AI landscape applicable to the context. There exists a lot of scientific research regarding the main genres of AI and very rich terminology has been developed on the subject. If we take a birds eye view on the AI landscape today we can distil a few major areas where-in AI algorithms reside.</p><p><strong>Unsupervised learning: </strong>This technique is given a dataset to explore on its own with no prior knowledge or guidance. The AI algorithms will examine the data space and try to unravel existing patterns.</p><p><strong>Supervised learning: </strong>This is one of the most typical AI settings. The AI system is given a dataset that models a space as well as prior knowledge regarding historical outcomes. As the AI explores the data space and unravels patterns, it correlates them to the desired continuous or discrete predictive outcome. Once the input space is fully explored the AI can make predictions when presented with a new datum belonging to the same space.</p><p><strong>Reinforcement learning:</strong> This is an approach based on Control Theory and tries to imitate how we, as humans, learn. Effectively, the AI system explores a digital equivalent of the problem space we are trying to analyse. The possible actions that it can take within this environment are modelled. The only feedback it is given, as it is taking decisions to navigate the problem space, is rewards and penalties depending on the decision. The AI gradually calibrates itself so that it takes decisions to avoid penalties and obtain more rewards. This is the type of learning we will be exploring on this article through this prototype in Tensorflow ML-Agents and Unity.</p><p><strong>Imitation learning: </strong>This approach is a close relative to reinforcement learning. The AI agent is able to observe how the expert behaves and tries to imitate her. Combined with reinforcement learning, such an approach can provide a form of bias in the behaviour of the AI agent, that can result in shortening its learning curve.</p><p><strong>Curriculum learning: </strong>An advanced approach that segregates a complex problem into more simple ones. This allows the AI system to solve each simpler problem step by step then combining the solutions it is able to solve the complex problem itself.</p><p><strong>Deep learning: </strong>Deep Learning (DL) is often regarded as an umbrella that can govern all previously mentioned techniques. DL is the latest generation algorithms in Artificial Intelligence. DL algorithms, mainly consisting of Deep Neural Network (DNN) structures, can be deployed on all beforementioned learning scenarios.</p><h4>Unity 2020 &amp; ML-Agents, a new way of visualising AI</h4><p>Unity and Unreal are the two main game engines in the industry and while they are mostly used in game development, they can also be used for enterprise software development on 2D, 3D, Augmented Reality (AR) and Virtual Reality (VR) applications. The ML-Agents package is a recent development that allows the Unity game engine and its underlying C#.NET framework to connect with Tensorflow via a python gateway. Once set up, it enables the use of DRL techniques to train objects to perform certain tasks or solve problems within a 3D scene. Using Unity as a 3D rendering engine we can visualise an AI’s agent decisions and its behaviour within a virtual environment. This provides us with an extra visualisation layer on top of the usual visualisations within data science and one that perhaps is more native to us to observe.</p><h4>Modelling the environment</h4><p>To set this fictional digital scene, we ask an AI agent to navigate a 3D model of a ship through a difficult terrain formation. We model its environment and give it a reward and penalty rule system. Then we let the agent explore and find the solution to the problem at hand.</p><p>Modelling the environment is the artistic &amp; gamification side of the prototype. Unity 2020 was used as the 3D rendering sandbox. All the 3D modules are available in the Unity asset store. You can see the rendering result in the next picture frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cA8yuAecuWWHlWI6tP-KWQ.png" /><figcaption>Setting the scene in Unity 2020.</figcaption></figure><h4>Modelling the physics</h4><p>Whilst the physics modelling for the purposes of the prototype is kept simple, some effort has been put to maintain a few important simulation elements. So while there is no currents, weather effects, or waves acting on the 3D model ship structure, the significant inertia that a ship has when sailing has been modelled, at least on a basic level. Hence, mass and drag exist in the prototype, and inertia and water resistance have been implemented. The engine has a simplified linear ramp-up behaviour capping at 100RPM and the propeller follows that rotation speed. The forces the propeller excels to the water are modelled to originate from its blades. Water resistance is approximated anti-correlated to the vector of direction of inertia and its velocity magnitude. The rudder acts as a rotational force on the 3D model, originating from its position. Finally, two bow (front) side thrusters were also modelled. The later can only be set to an on or off state, applying a constant rotational force at the bow of the 3d model. A digital awareness module was also implemented, able to detect distances from terrain as well as direction and distance from the destination point that was set at the exit of the terrain formation. The next video shows the awareness module as well as some of the forces that act on the 3D ship model structure as it moves.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F503637877%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F503637877&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1041932076_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1040" frameborder="0" scrolling="no"><a href="https://medium.com/media/bed0b3e3b2a2b8d30096897b091dc587/href">https://medium.com/media/bed0b3e3b2a2b8d30096897b091dc587/href</a></iframe><h4>Deep Reinforcement Learning — AI using C# and ML-Agents</h4><p>Before going into the details of how the AI was written in Unity C#, let’s briefly discuss the DRL architecture. When a DRL system is built, we are modelling a set of states that describe the environment the AI algorithm (agent) resides in. We then allow the agent to take some actions in the environment and we provide it with rewards or penalties depending on the action and the state transition it resulted in. A process that is called the policy is what maps actions to states.</p><p>There are a few different approaches in training DNNs for DRL and depending on the approach, we distinguish between value-based, policy-based and model-based DRL. The learning process in DRL is governed by two important algorithms Markov Decision Processes and Q-Learning. Their main difference is the way the DNNs are being calibrated during training. The training lifecycle of the DRL AI agent is presented in the following schematic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*VNv8mmnHAUUtNoULdHi3Mw.png" /><figcaption>The Deep Reinforcement Learning lifecycle.</figcaption></figure><h4>Next steps</h4><p>This article described the existing landscape of AI methodologies and the DRL lifecycle and described how the scene for this prototype was built in Unity. The graphical and 3D interface was presented as well as the physics modelling that enables the AI agent to interact with it’s environment. In the next part of this article series we will dive deeper into the AI structure and DRL policies as well as the training and the tools we have available to monitor the process. Finally, we’ll be able to see a video rendering of the solution the DRL AI agent finds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62a020e96dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predictive analytics using Corda]]></title>
            <link>https://medium.com/corda/predictive-analytics-using-corda-1287e6aad23e?source=rss-373b45aa7a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1287e6aad23e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[real-estate]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[distributed-ledgers]]></category>
            <dc:creator><![CDATA[Marios Skevofylakas]]></dc:creator>
            <pubDate>Wed, 14 Nov 2018 07:57:25 GMT</pubDate>
            <atom:updated>2018-11-14T09:15:19.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*XDvCAZ7Yo4Q9KxlWnieHqQ.png" /></figure><p>Distributed Ledger Technologies are not just here to stay, they are here to shape the future of Information Technology. There has been a significant leap in the evolution of DLT in the past 3 years in terms of its capabilities and 2018 was the year to see the first finalised products in the financial services industry. Outside financial services the public sector is also starting to move beyond use case definition and into prototyping and development. For example, the UK Land Registry Digital Street project aims to explore how DLT and smart contracts can make the property buying / selling process simpler, faster and cheaper. For this project Blockchain Digital is working with the Land Registry to develop Corda Applications and build an innovation eco-system comprising of estate agents, conveyancers, banks, HMRC and wider industry participants; It is a unique period of digital transformation and the year 2019 will be the year to see it all coming into place. We expect rich enhancement of the DLT technology stack and delivery of important products in all sectors including trade finance, supply chains, healthcare and the public sector.</p><p>R3 Corda is the leading technology stack when thinking about DLT. Aside from its extremely rich framework, it displays a significant quality; strong business coupling. Corda makes you think about the solution in terms of business flows and architecture, allowing you to deeply understand the system design before you start writing code. This process enables us to write better code and thus better systems and do this more naturally even within the complex landscape of a DLT ecosystem.</p><p>We are moving from a centralised thought process to the more versatile way of doing business on a densely connected grid. In the process, we will begin to see the benefits the ledger has to offer, those of transparency, traceability, immutability, immediacy and security. As we start storing more and more data in the ledger a familiar question will rise in mind. How do we turn all this data to insight?</p><p><strong>The Use Case</strong></p><p>Blockchain Digital was the first consultancy to recognise how Corda blockchain could be used to solve the problems of the property sector, and our project with the UK Land Registry has been recognised globally. As we have started to look more and more at the industry, we realised that a natural use case candidate would be deploying analytics on property valuation in Corda.</p><p>This article will take you through some early work, ‘thinking out loud’ around how an analytics node might be deployed on a Corda network. The simulated scenario we are using is that of a property owner who wishes to be represented from a real estate agency and list her property at a specific price in the market. For the sake of simplicity, we assume that a property has a single significant parameter that drives the price and that would be its floor area. We envision the existence of an analytics node within the ledger grid that we call the Seer node. The Seer node has a wider view of the ledger allowing it to train a regression model off-the-ledger on properties already listed in the ledger.</p><p><strong>The forecasting algorithm</strong></p><p>We simulated a dataset of 300 properties whose states were injected in the ledger through the Web API that our Corda solution exposes. The parameters that were used to describe a property include the property ID, the floor area, and a placeholder for price. The data State that represents a single property in the ledger looks like:</p><pre><strong>data class </strong>PropertyState(<br>  <strong>val owner</strong>: Party,<br>  <strong>val seer</strong>: Party,<br>  <strong>val propertyId</strong>: Int,<br>  <strong>val price</strong>: Int,<br>  <strong>val floorArea</strong>: Int,<br> <br>  <strong>override val linearId</strong>: UniqueIdentifier = UniqueIdentifier()) :  <br>  LinearState, QueryableState {<br>  <strong>override val participants</strong>: List&lt;Party&gt; = listOf(<strong>owner</strong>, <strong>seer</strong>)<br> }</pre><p>We used polynomial regressions as the algorithm genre for price forecasting. A 3rd degree polynomial regression was used and its response to the simulated dataset and iterative behaviour can be seen in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*IAJVfPY3vvox4aJXCaROrA.gif" /></figure><p>A 3rd degree polynomial regression of property price with regards to property area would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*pS_0O5-n6kmNYj5dMtcIxg.png" /></figure><p><strong>Storing the model in the ledger</strong></p><p>In their essence, and this might not hold true for the entirety of econometrics and ML algorithms, the output result of a regression training process will resemble some kind of mathematical formula. In our case, if we wanted to store and use the trained formula for calculations predicting the fair price of a property given its floor area all we would need would be the 3rd degree betas b0, b1, b2, b3. We can therefore design a Corda model state that could store these parameters and it would look like:</p><pre><strong>data class </strong>ModelState(<br> <strong>val seer</strong>: Party,<br> <strong>val owner</strong>: Party,<br> <strong>val modelId</strong>: Int,<br> <strong>val b0</strong>: Double,<br> <strong>val b1</strong>: Double,<br> <strong>val b2</strong>: Double,<br> <strong>val b3</strong>: Double,</pre><pre><strong> override val linearId</strong>: UniqueIdentifier = UniqueIdentifier()) :    <br> LinearState, QueryableState {<br> <br> <strong>override val participants</strong>: List&lt;Party&gt; = <em>listOf</em>(<strong>seer</strong>, <strong>owner</strong>)</pre><pre>}</pre><p>This Corda state would be governed by the Seer that would be responsible for keeping it up-to-date and circulate it to all involved participants in the network.</p><p><strong>Forecasting Property Prices</strong></p><p>Once a node has access to a property state and the model state it could call a forecasting flow that would bind everything together. The flow would consume the model state and the property state and run a function implementing the pricing polynomial. The forecasting flow could extract the explanatories used for the calculation, in our case area, from the property state and build the formula to the degree of the polynomial using betas from the model state. The function could look like:</p><pre><strong>private fun </strong>predictPrice(inputPropertyState: PropertyState,    <br>                         inputModelState: ModelState): Int {<br> <br>  <strong>val </strong>priceHat = <em>listOf</em>&lt;Double&gt;(<br>  inputModelState.<strong>b0</strong>,    <br>  inputModelState.<strong>b1</strong>, <br>  inputModelState.<strong>b2</strong>, <br>  inputModelState.<strong>b3</strong>).<em>foldIndexed</em>(0.0, <strong>{</strong>ix, priceHat, next <strong>-&gt;          <br>  </strong>priceHat + <br>  next* Math.pow(inputPropertyState.<strong>floorArea</strong>.toDouble(),      <br>  ix.toDouble())<strong>}</strong>)<br> <br>  <strong>return </strong>priceHat.toInt()<br> }</pre><p>After the calculation, a new output state would be stored in the ledger with the updated forecasted price of the property.</p><p><strong>Reflecting upon the future of AI in DLT</strong></p><p>This work is an early stage prototype with some initial thoughts put on design paper and implemented in Corda. There are many improvements that can be done. An important one would be refactoring the model state into a reference state. Reference states that will be introduced in Corda 4.0 are states that do not get consumed from transactions in the ledger but act as input parameters that stay relatively stable within the life-cycle of the application. The model state can be a good candidate for such a structure because ML algorithms are usually not continuously trained but their structure gets batch updated, something that could happen e.g. every end of week.</p><p>Other future thoughts include researching the structure of the grid itself that might be able to not only simplify analytics problems but also help naturally increase the accuracy strength and versatility of individual predictors. What if we wanted to build a region based house pricing model? Traditionally we might go about to partition the problem in regions, a process that can potentially include significant effort ranging from simple grouping operations on a local node to hot &amp; cold cluster balancing on area indexing. In the context of DLT though things could naturally become simpler. With the existence of a single Seer node for every region of participants and the Network service using the locality data of the nodes to suggest the closest Seer in the group, then one could think of dedicated regional Seers employing only analytics on the data of that region. Taking the idea, a bit further and keeping in mind the concept of combinator functions we could envision the existence of a global Seer that consolidates data and statistics from regional Seers to provide a global view of the Ledger.</p><p><strong>Conclusion</strong></p><p>This is a first of a series of articles on possible AI implementations using Corda. Blockchain Digital will remain active in the context and will continue to experiment on different designs and prototypes within the different genres of ML such as classification and clustering as well as different ways of storing and using them in the ledger.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1287e6aad23e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/corda/predictive-analytics-using-corda-1287e6aad23e">Predictive analytics using Corda</a> was originally published in <a href="https://medium.com/corda">Corda</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>