<?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 Javier Galdeano Rodríguez on Medium]]></title>
        <description><![CDATA[Stories by Javier Galdeano Rodríguez on Medium]]></description>
        <link>https://medium.com/@javigaldeano?source=rss-3a6d8c7d3088------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lxUl9-cfZx215M7CkXywew.jpeg</url>
            <title>Stories by Javier Galdeano Rodríguez on Medium</title>
            <link>https://medium.com/@javigaldeano?source=rss-3a6d8c7d3088------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:46:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@javigaldeano/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[Building a Neural Network from Scratch]]></title>
            <link>https://medium.com/@javigaldeano/building-a-neural-network-from-scratch-17106e1dc7b8?source=rss-3a6d8c7d3088------2</link>
            <guid isPermaLink="false">https://medium.com/p/17106e1dc7b8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Javier Galdeano Rodríguez]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 17:00:32 GMT</pubDate>
            <atom:updated>2024-08-29T17:00:32.198Z</atom:updated>
            <content:encoded><![CDATA[<p>Guide to build a Fully Connected Neural Network using just Python and Numpy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*cD3VGNDJiIG2Imf1OCI_vg.jpeg" /></figure><p>As artificial intelligence increasingly becomes a part of our lives, numerous libraries have emerged to simplify the development of new models for programmers, data scientists, and analysts. However, while these tools attract newcomers to the field, they often obscure the theoretical knowledge underlying these software programs. In this post, the aim is to explain the most important aspects of constructing an artificial neural network and to implement this knowledge in Python. I hope this will be useful and help you better understand how these models work! Any suggestions or questions are always welcome!</p><h3>1.- Neural Networks</h3><p>A neural network is a computer program designed to make decisions in a manner similar to the human brain. It does this by employing processes that mimic how neurons interact with each other to reach conclusions about a specific task. The knowledge embedded in these mathematical models is derived from the training data they are provided with.</p><p>Let’s consider the example of a basketball player. Initially, if the player has never attempted a three-point shot, their accuracy from that distance will likely be low. However, as the player continues to practice, they will gradually determine with greater confidence how much force to apply to the ball (among other variables that need to be considered) to make as many successful shots as possible. The more attempts they make, the more experience they gain, and the higher the number of successful three-point shots they will achieve.</p><h4>Basic representation of a Neural Network</h4><p>The fundamental unit of a Neural Network is the neuron, also known as a node. These small processing units are grouped together to form layers. There are different types of layers based on their functionality: input layers, which are responsible for feeding the dataset information into the network; hidden layers, which perform the necessary transformations to extract features from the data; and output layers, which provide a final result based on the features derived from the previous layers. Below is a graphical example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNXUxTK64lb6FfkSeiAgwA.gif" /><figcaption>Ilustration 2: 5-Layer Feed Forward Fully Connected Neural Network</figcaption></figure><h3>2.- Building a Neural Network step-by-step</h3><p>To understand how this type of neural network operates, we will implement each of the necessary steps for constructing and training the network.</p><h4>2.1.- Layer initialization</h4><p>The initial step in constructing the network involves defining the number of layers and the number of neurons per layer. There is no predefined structure that guarantees the optimal solution for a given task. However, certain studies provide guidance on how to structure neural networks effectively depending of the problem faced.</p><p>For this example, Deep Feedforward Networks will be introduced. In this models, informations flows through the layers from the input, x, through the hidden layers until reaching the output, y. No feedback connections are used in this kind of models.</p><p>These are extremely essential in Machine Learning as they form the basis of many applications, such as Convolutional Networks, which are commonly used for object detection.</p><p>So, back to the layer initiaization. Taking into account that the number of nodes of the input layer depends mainly on the training dataset and the number of nodes of the output layer depends on the task we are solving, we just have to determine the number of hidden layers and nodes per layer we want to use to extract features from the training dataset.</p><p><strong>Implementation</strong></p><p>Following the theorical implementation, let’s have a look at the Python code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/643e3049f20b08ea9034065e83839255/href">https://medium.com/media/643e3049f20b08ea9034065e83839255/href</a></iframe><p>Before explaining and developing new elements of a Deep Feedforward Network, here’s the practical structure used for this tutorial. It will have 3 hidden layers, with 2000, 800, 100 neurons respectively. Check the visualization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkGoCeTUQ7Pzj-qk_MAFRQ.gif" /><figcaption>Ilustration 3: My Net Design</figcaption></figure><p>Each node will be connected with every single node of just the following layer, allowing the flow of information through the net.</p><h4>2.2.- Parameter initilization</h4><p>Based on the chosen structure, the next step is to initialize the parameters that enable the network to function. Each required parameter has predefined dimensions. They need to be optimized in order to improve accuracy of the model and only hidden and output layers will have them.</p><p>Let’s have a look:</p><p><strong>2.2.1.- W, Layer Weights</strong></p><p>Weights are coefficients associated with input’s characteristics which determine the contribution of each characteristic to the output of the model. Weights are optimized during training to reduce the loss obtained after each iteration of the training dataset.</p><p>The dimensions of the weight matrix for each layer are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*jJjNf7tupD_Lw3gNP4gQJQ.png" /><figcaption>Ilustration 4: Weight matrix’s dimensions</figcaption></figure><p>This structure allows each neuron in the previous layer to be connected to the neurons in the current layer. This way, every node will assing an weight value to the output of every neuron from the previous layer.</p><p><strong>2.2.2.- B, Layer Bias</strong></p><p>Bias adjust the output of the model to better represent the relation between inputs and outputs. Each layer will have a bias vector, denoted as b. The dimensions of this vector are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*DBHqvCMmP-d8wC_sd3AGZg.png" /><figcaption>Ilustration 5: Bias vector’s dimensions</figcaption></figure><p>meaning it will have as many rows as there are neurons in the layer.</p><p>Intuitively, we can conclude two things:</p><ul><li><strong>Every neuron will have a customizable weight vector</strong>. Because of the connections between nodes in consecutive layers, every node will have a weight value associated with each neuron it is connected to from the previous layer. By grouping all the weight vectors from the neurons in a layer, a weight matrix is formed.</li><li><strong>Every neuron will have a customizable bias value</strong>. The nodes in the hidden and output layers will individually have a bias value that is optimized during training. As neurons are grouped into layers, these bias values will collectively form a bias vector.</li></ul><p>Finally, a visual representation of weights and bias matrices to better understand both concepts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrdQXffTQxZSAUgJV2Nizw.gif" /><figcaption>Ilustration 6: Weights and bias matrices initialization</figcaption></figure><h4><strong>2.3.- Forward Propagation Implementation</strong></h4><p>Feedforward neural networks have an input X, which provides the initial information that flows through the network, propagating through the hidden layers and ultimately producing an output denoted as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/26/1*MIeCBW7Xp7AkTa4Wc3_BhQ.png" /><figcaption>Ilustration 7: Output of Neural Network</figcaption></figure><p>This output is used in the computation of the supervised loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/101/1*r6soQrusKj1qTR_kKscZRQ.png" /><figcaption>Ilustration 8: Notation to identify loss between labels and NN predictions</figcaption></figure><p><strong>2.3.1.- Z, preactivation parameters</strong></p><p>So, to begin with, pre-activation parameters need to be computed. These are the linear combination of inputs and, actual weights and bias of the layer. For every layer, Z is calculated as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*CT1xAoZehYe1pZJCVktf0w.png" /><figcaption>Ilustration 9: Preactivation parameters formula</figcaption></figure><p>If we specify the dimensions of each matrix, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*kIYg1rZ0AsL2wSv_fca-zg.png" /><figcaption>Ilustration 10: Matrix dimensiones in pre-activation parameters calculus</figcaption></figure><p>So, every node of the layer will output a pre-activation. All values will be grouped into a column vector, Z.</p><p><strong>Implementation</strong></p><p>Following the theorical implementation, let’s have a look at the Python code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0534ad04f680670d89bb7e366b8a562/href">https://medium.com/media/f0534ad04f680670d89bb7e366b8a562/href</a></iframe><p><strong>2.3.2.- A, Activation Parameters</strong></p><p>Afterwards, the activation will be computed. This means applying an activation function to Z. Notice that Z and A will share the same dimensions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JecNaxS0XdFiSMzJERtTLA.gif" /><figcaption>Ilustration 11: Visual representation of matrices shapes in forward propagation</figcaption></figure><p><strong>Implementation</strong></p><p>Following the theorical implementation, let’s have a look at the Python code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f34cfe01895324d0b95416f0e9cd26d/href">https://medium.com/media/5f34cfe01895324d0b95416f0e9cd26d/href</a></iframe><h4><strong>2.4.- Cost Calculation</strong></h4><p>This is one of the essential steps in building a machine learning model. Implementing a cost function is the tool that allows us to measure how well the model is performing with respect to the observed data. This calculation serves as the “engine” that enables us to adjust the weights W of our model to reduce the error by gaining experience from the training dataset.</p><p>Take into account that multiple cost functions exists depending on the task or preferences of the user.</p><p><strong>Implementation</strong></p><p>Following the theorical implementation, let’s have a look at the Python code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab9d94126808bad961233a474004dcbd/href">https://medium.com/media/ab9d94126808bad961233a474004dcbd/href</a></iframe><h4><strong>2.5.- Backpropagation Implementation</strong></h4><p>The backpropagation algorithm enables the information about the cost obtained during forward propagation to be propagated backward (in the opposite direction of forward propagation) with the goal of computing the gradient. It is important to distinguish this process from parameter updates, which are carried out by another algorithm, such as stochastic gradient descent.</p><p><strong>Why use the gradient? </strong>For this simplified and introductory example of neural networks, we will use gradient descent as the optimization algorithm to minimize the objective function, which is our cost or loss function. This is an iterative process that adjusts the model parameters to reduce the observed error.</p><p>Assuming we have a function <em>y = f(x)</em>, the derivative, denoted as <em>f’(x)</em>, provides the slope of the function at a given point <em>x</em>. The use of the derivative is helpful because it provides information about how to change <em>x</em> to improve <em>y</em>, i.e., to reduce the loss. Below is a 2D example extracted from the book: Goodfellow, I., Bengio, Y., &amp; Courville, A. (2016). <em>Deep Learning.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*dZIWL20FTKXC-9cbnR82Zw.png" /><figcaption>Ilustration 12: How derivatives can be used to follow the function downhill to a minimum. Extracted from Goodfellow, I., Bengio, Y., &amp; Courville, A. (2016). <em>Deep Learning.</em></figcaption></figure><p>For functions with multiple inputs, as in our case, with a large number of parameters, the concept of partial derivatives is employed. A partial derivative measures how the function changes when the parameter <em>X_i​</em> changes at a given point. The gradient is the vector that contains all the partial derivatives, denoted as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*rj4si5J3lbM4Ht_-PBAjuw.png" /><figcaption>Ilustration 13: Gradient vector</figcaption></figure><p>To minimize the loss function, we need to find the direction in which it decreases the fastest, which is calculated using directional derivatives. The gradient is ascending, meaning it points upwards, while the gradient descent, i.e., <em>−∇_x f(x)</em>, points in the direction we want to move. Below is a graphical example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*OgY5ajMsyhgN1hcBsbvvgA.png" /><figcaption>Ilustration 14: 3D Representation with partial derivatives and gradient at point (-1, 7, 45)</figcaption></figure><p>We can observe how the partial derivatives are calculated with respect to the variables <em>X</em> and <em>Y</em>, while the gradient is ascending. So, as mentioned, we’ll move in the opposite direction of the gradient.</p><p>Now, let’s run 10 iterations of the gradient descent algorithm and observe the new points being generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*FhDO93QwMlEzxCui44ds3A.png" /><figcaption>Ilustration 15: Generation of new points with gradient descent</figcaption></figure><p>As you can see, newer points are obtaining a lower error. Keep in mind that this is a very simplified yet illustrative example of function optimization. In a real problem, saddle points or local minima could stall the learning process. This can be addressed through different parameter initialization strategies.</p><p><strong>2.5.1.- Parameters used for backpropagation</strong></p><p>Regarding the dimensions of the parameters used for backpropagation, they will have the same dimensions as the parameters involved in their calculation.</p><p><strong>Implementation</strong></p><p>Following the theorical implementation, let’s have a look at the Python code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86450afcf627991b75a71d86a25a4577/href">https://medium.com/media/86450afcf627991b75a71d86a25a4577/href</a></iframe><h4>2.6.- Parameter update</h4><p>Having explained the gradient descent algorithm, we just need to know how to calculate those new points. The update rule for the parameters is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*pCQ4DEmL44oolNq7J9AYow.png" /><figcaption>Ilustration 16: Updating parameters formula</figcaption></figure><p>where ϵ is a positive scalar that determines the magnitude of the parameter update, known as the “learning rate.” Here’s a visual demostration of how the update will be completed for the output layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_oPqmOyUARQYWacieyk0zg.gif" /><figcaption>Ilustration 17: Updating output layer parameters via gradient descent algorithm</figcaption></figure><p>Finally, we’ll have to continue updating every hidden layer in our network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CI9gyykGyd1cZSJXgkN4jw.gif" /><figcaption>Ilustration 18: Updating hidden layers parameters via gradient descent algorithm</figcaption></figure><p><strong>Implementation</strong></p><p>Following the theorical implementation, let’s have a look at the Python code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7af03f602b4bbdd9b2cf6bf00a0e5e70/href">https://medium.com/media/7af03f602b4bbdd9b2cf6bf00a0e5e70/href</a></iframe><p>Having explained all the necessary implementations for constructing a neural network from scratch, we will now put the concepts into practice with code in a real-world example:</p><h3>3.- Practical example: Binary Classification</h3><p>To apply the theoretical concepts discussed earlier, I will implement the training of a neural network for binary classification. The process is divided into the following sections:</p><h4>3.1.- Dataset used</h4><p>For the classification task, images will be used. Specifically, the well-known CIFAR-10 dataset will be employed. This dataset consists of 60,000 color images, each of size 32x32, categorized into 10 classes (with 6,000 images per class). The data is divided into 50,000 training images and 10,000 test images. The classes are: ‘Airplane’, ‘Car’, ‘Bird’, ‘Cat’, ‘Deer’, ‘Dog’, ‘Frog’, ‘Horse’, ‘Ship’, ‘Truck’.</p><p>Since we will be performing binary classification, we will use the images of trucks and frogs.</p><h4>3.2.- Selecting parameters and hyperparameters</h4><p>Although we previously discussed the size of parameters such as weights and biases, we did not address their initialization values. Generally, there is no standard approach for correctly initializing these parameters in the first iteration. However, the following considerations should be taken into account:</p><ul><li>Weights: it is important to initialize all weights to small random values. The technique used in this example is the <strong>He Initialization</strong>, that takes into account the non-linearity of activation functions, reducing the magnitudes of input signals exponentially.</li><li>Bias: these can be initialized with small random positive values or zeros. In this example, we’ve used zeros.</li></ul><p>Other hyperparameters used are: learning rate, which is initialized to 0&#39;01; 3 hidden layers with 2000, 800, and 100 neurons, respectively.</p><h4>3.3.- Training the ANN</h4><p>While training a neural network is much more complex than this simple example, to track the accuracy of the network as it is being trained, we will save both the error on the training data and the error on the test data, which the network does not learn from, during each iteration. The progression of the error is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*tcXnJ4OoIm9qhHubUrNtUg.png" /><figcaption>Ilustration 19: Training and Validation error during training</figcaption></figure><p>According to the graph, we can observe that the network begins to stabilize in the later stages, and the validation set remains close to the training curve, not overfitting the training set and generalizing effectively with unseen data.</p><p>Therefore, in line with what has been discussed earlier, although there are many more aspects to consider during training, we will consider this training satisfactory.</p><h3>4.- Conclusion</h3><p>The development of a Machine Learning system is an iterative process where various parameters, hyperparameters, and data distributions are tested with the goal of minimizing error as much as possible with unknown and updated data before deployment. However, in this post, such a process was not undertaken as it is simply an introductory implementation of Deep Neural Networks.</p><p>If any reader wishes to experiment with using training batches instead of the complete dataset, employing other optimization algorithms like Adam, optimizing training through an Early Stopping method… the GitHub repository with the designed code is provided below.</p><p>Finally, as mentioned in the introduction, any questions or concerns are welcome. Thank you for reading, and I hope the concepts related to implementing this type of neural network have been as clarified as possible.</p><h3>5.- References</h3><ol><li>Goodfellow, I., Bengio, Y., &amp; Courville, A. (2016). <em>Deep Learning.</em></li><li>Coursera: Neural Networks and Deep Learning. Deep Learnig.AI</li></ol><h3>6.- GitHub Repo</h3><p><a href="https://github.com/JGaldeano12/deep-feedforward-network/">https://github.com/JGaldeano12/deep-feedforward-network/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17106e1dc7b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Reinforcement Learning: Markov Decision Processes]]></title>
            <link>https://medium.com/@javigaldeano/understanding-reinforcement-learning-markov-decision-processes-bb4b0fd55826?source=rss-3a6d8c7d3088------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb4b0fd55826</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[markov-decision-process]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Javier Galdeano Rodríguez]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 16:24:46 GMT</pubDate>
            <atom:updated>2023-09-25T16:24:46.627Z</atom:updated>
            <content:encoded><![CDATA[<p>Brief intro into Markov Decision Processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Up-OAlBqo6p5aFowrspcLw.jpeg" /></figure><p>Welcome everybody. Following my previous post about Q-Learning applied to Trading, I’m going to make a guide to help everybody understand the fundamentals of Reinforcement Learning, so we all can reafirm the contents learned.</p><p>To begin with this path, I’ll give you a quick view about the basics of Markov Decision Processes, which are known to be “<em>a mathematically idealized form of a RL Problem</em>”.</p><h3><strong>Part 1: The Agent-Environment Interface</strong></h3><p>Two basic elements get involve in a RL problem:</p><ul><li><strong>Agent</strong>: which is the ones who learns and decides with the knowledge learnt.</li><li><strong>Environment</strong>: this is what interacts with the agent. It’s simplier if we define everything that cannot be arbitrarily changed by the agent part of the environment.</li></ul><p>This two elements continually interact. The environment will present an <strong>state</strong> to the agent. A <strong>state</strong> could be easily understood by thinking of a representation of the environment, and it is noted as <strong>S</strong>. Based on this representation, the <strong>agent,</strong> taking into account the knowledge it has about the environment, takes an <strong>action</strong>, noted as <strong>A</strong>. Following this action at a particular state, the agent will receive a <strong>reward</strong> that is a numerical value and will find itself in a new state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*8RS3DjLe79KJ9zGNxEJzNg.png" /><figcaption>Agent-Environment in a Markov Decision Process</figcaption></figure><p>This way, the Agent will make a sequence that begins in a state, chooses an action, gets a reward…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*ixzzguJfMwkuX7wEmwdBQA.png" /><figcaption>Trajectory of the Agent through different states</figcaption></figure><p>In case of working on a finite MDP, a well-defined number of states, actions and rewards will take into place. For particular values of the random variables S’ and R’, there is a probability of those values ocurring at time t, given particular values of the preceding state and action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*9VPWrqBWFpMvdDVHcRQwXg.png" /><figcaption>Discrete Probability Distributions Definition</figcaption></figure><p>An MDP environment is characterize by the probabilities given by p. This probabilities represents mainly that the probablity of the next state (S’) and the reward of taking that action at that particular state (R) depends on the immediately preceeding state and action.</p><p>It’s quite interesting to know that with that four-argument function, p, we can compute anything else we want to know from the environment, such as the state-transition probabilites…:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*GCnNX3FZLw3JKAEDWRIq3w.png" /><figcaption>State-Action Pairs Expected Rewards Definition</figcaption></figure><h3>Part 2: Goals and Rewards</h3><p>Let’s focus on the main objective. The purpose of a RL problem is maximizing the total reward. Considering that, this means maximizing the long-term cumulative reward, not the inmediate reward. This is crucial, we have to keep in mind the main goal to achieve the task. If we are training a Chess agent, we should only give reward for winning, not for making moves, controlling the center of the board or even taking opponet’s pieces during the game. Another example could be using self-driving car: we could focus the agent to make subtasks such as adjusting the music, temperature… or just focus on getting from a point A to B safely.</p><p>Remember…</p><blockquote>The reward signal is your way of communicating to the agent what you want to achieved, not how you want it achieved. [1]</blockquote><h3>Part 3: Returns and Episodes</h3><p>Taking into account we want to maximize the long-term reward , we can denote it as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*_Iqe9CWiH3v1nkczVyLZIg.png" /><figcaption>Cumulative Expected Return Formula</figcaption></figure><p>If we think about it, it trully makes sense if it’s applied in environments where the interaction with the agent breaks naturally into subsequences, which are known as episodes. Each episode will end at the terminal state, resetting the environment to its initial state, or starting state. Using the example of Chess-Agent, independently of winning or losing in a episode, the next one will begin no matter what happened before. However, there will be different rewards. This kind of episodes are known as <strong>episodic tasks</strong>.</p><p>Alternatively, the interaction can’t be divided easily into episodes, as it goes continually without limit. For example, the self-driving agent we mentioned before. No matter what it faces, even if it’s unknown, the agent will have to constantly take action to avoid crashes and make the travel safely.</p><p>However… How will the return formula work if we have infinite time steps? Wouldn’t it be infinte too? To understand how it will work, a new factor will be considered, <strong>discounting</strong>. Thanks to this, the agent will select actions so the long-term rewards are maximized by determinating the present value of future rewards as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*DpxsC-e8qCeNzqMdSjzGoA.png" /></figure><p>This means that a reward received K time steps in the future is only worth the value obtained with the formula. The closer to 1 Y is, the more importance to future rewards is given by the agent. However, the closer to 0 Y is, the higher importance is given to inmediate rewards.</p><p>When the agent is only concerned with maximizing inmediate rewards (which means that Y = 0), it is known as “myopic”.</p><p>Let’s have a look at the discounted reward definition, which evaluates the quality of the actions taken by the agent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*RAaLwKycGxjY0cMGV7N4-Q.png" /><figcaption>Cumulative Reward Return Formula (With Discounting Factor)</figcaption></figure><p>Where:</p><ul><li>Y: also known as “gamma” or discounting factor. It determines the relative importance between future and instant rewards.</li><li>Rt+k+1: this is the reward received in the time step t+k+1, incluiding the instant reward (k=0), next step reward (k=1)… and it goes on until infinite.</li></ul><h3>Part 4: Policies and Value Functions</h3><p>How can we define how good our agent is? Well, we need to estimate how good it is in terms of furture rewards that could be expected through decision-making. A policy is commongly known as the mapping between states to probabilities of selecting each possible action. A policy is known as π, and it determines the probabilty that the agent chooses action A in the State S.</p><p>Then, we get to known to the value function. This is the function estimated for knowing how good is the agent at a specific state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--Dcevv4M0B0k6e3Wh_Aug.gif" /><figcaption>State-Value Function following Policy π</figcaption></figure><p>Also, we can get to know the action-value function which defines the value of taking action a at a state s following policy π. Let’s have a look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxzNmdr5N1GazvdLQqqTlQ.gif" /><figcaption>Action-Value Function following Policy π</figcaption></figure><p>This two functions can be estimated from experience, which means that, if the agent follows policy π maintining an average of the actual return then the average will converge to state’s value function. We can call estimation methods of this kind as Monte Carlo Methods, as the involve averaging over multiple random samples of actual returns.</p><blockquote>A fundamental property of value functions used throughout reinforcement learning and dynamic programming is that they satisfy recursive relationships similar to that which we have already established for the return. [1]</blockquote><p>This equation is the Bellman equation for V_π, describing how the value of a state s is related to the values of the following states and its rewards following the policy π.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*cxD4QXFVBHsu_Xu1d1iV5g.png" /><figcaption>Bellman Equation for V_π</figcaption></figure><ul><li><strong>V_π(s)</strong>: expected value of a Random variable being at state s following policy π.</li><li><strong>π(a|s)</strong>: probability of selecting action a in state s.</li><li><strong>p(s’,r|s,a)</strong>: probability of passing from state s to s’ by taking action a and receiving reward r.</li></ul><p>As you can see, it’s calculated as the weighted sum of immediate rewards and the values of following states, considering transition probabilities and action selection probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*li3TucIY2BaPHo0EPOrdWw.png" /><figcaption>Backup Diagram</figcaption></figure><p>This diagram is a known as Backup Diagram. They represent the relationships between update and backup operations of a RL Method.</p><h3>Part 5: Optimal Policies and Optimal Value Functions</h3><p>When we are solving a RL problem, there will be one policy that could be defined as “better” or equal than every other policy that could be defined: the optimal policy.</p><blockquote>A policy <strong>π </strong>is defined to be better than or equal to a policy <strong>π’</strong> if its expected return is greater than or equal to that of <strong>π’</strong> for all states. [1]</blockquote><p>If there’s more than one optimal policy, we can group them by <strong>π*. </strong>Also, if they are considered optimal policies, they will share state-value function…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*EXaf4g1Oj-Ut1fDkFQi9LQ.png" /><figcaption>Optimal State-Value Function</figcaption></figure><p>… and action-value function…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*9YE_YIcrdxkeMR-UDKNVRQ.png" /><figcaption>Optimal Action-Value Function</figcaption></figure><p>Next, we will introduce the Bellman Optimality Equation, establishing that the optimal value for an state s is equal the maximum value for all possible actions in that state. Solving this equation allow us determine the optimal state-value function, and then, it’s optimal policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*2UGvu3NgaeWfrh515K6nFQ.png" /><figcaption>Bellman Optimality Equation for V*</figcaption></figure><p>Also, we can define the Bellman optimality equation for q*:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*8YC_bVh06qQh-GHyxFrjEw.png" /><figcaption>Bellman Optimality Equation for Q*</figcaption></figure><p>This way, if you have the optimal value function, V*, all the actions that appear to be the best ones, will be the optimal actions.</p><h3>Conclusion</h3><p>Well! That was a quick summary of MDP for RL. I know it’s quite dense and I trully recommend to complement this reading with some books, articles or even YouTube videos, and of course, implement in a project of this characteristics.</p><h3>References</h3><ul><li>[1] R. S. Sutton y A. G. Barto, Reinforcement Learning: An Introduction (Second Edition).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb4b0fd55826" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning: Using ML for Trading]]></title>
            <link>https://medium.com/@javigaldeano/reinforcement-learning-using-ml-for-trading-e2faa5d09caa?source=rss-3a6d8c7d3088------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2faa5d09caa</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Javier Galdeano Rodríguez]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 17:10:40 GMT</pubDate>
            <atom:updated>2023-09-10T17:10:40.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*IXVZjwJYFe7Jh062CUU4Lw.png" /></figure><h4><strong>Introduction</strong></h4><p>Hi! I’m Javier Galdeano. I’m a recently graduated Informatic Engineer interested in applying technology to real life situations. As I’m quite curious about AI, I’ll develop some simple projects to start my journey, hoping we can share point of views and learn new things!</p><p>This is also my first article in Medium so… I hope you enjoy it!</p><h4>Reinforcement Learning</h4><p>Currently, two main AI methods are being considered: supervised and unsupervised learning. However, Reinforcement Learning is considered a new paradigm of AI, commonly identified as a type of unsupervised learning method.</p><p>In a RL problem, the Agent will learn what to do in all situations so it maximize a reward. The way it learns is mainly by discovering which actions yield the most reward, just, by trying them during training. Being this the main idea, let’s see the components of a RL problem:</p><h4><strong>Elements of a RL Problem</strong></h4><ul><li><strong>Agent</strong>: it’s the action teller. I’ll train it to take actions maximizing the rewards.</li><li><strong>Environment</strong>: it’s the world the agent will face when taking actions. This will be all the historical price data we are considering for trading.</li><li><strong>State</strong>: it’s the current representation of the environment. This is the actual state of the environment, meaning the data from the day we are looking forward to act in.</li><li><strong>Action</strong>: these are the decisions the agent can make at every single state. In my case, I’ve considered three main choices: Selling, Not acting, Buying.</li><li><strong>Reward</strong>: the benefit of making an action at a state. We’ll simply calculate the difference between day prices.</li><li><strong>Policy</strong>: it’s the strategy the agent will follow in order to maximize the long term rewards. This could be maximizing benefits, minimizing loss… There’s plenty of options. I’ll consider <strong>maximizing benefits</strong>.</li></ul><h4><strong>Q-Learning</strong></h4><p>Understanding the elements of our problem… What could be considered a solution to a RL Problem? Well…</p><blockquote>“Solving a reinforcement learning task means, roughly, finding a policy that achieves a lot of reward over the long run. A policy π is defined to be better than or equal to a policy π’ if its expected return is greater than or equal to that of π’ for all states.” [1]</blockquote><p>Several methods have been implemented, being Q-Learning the one applied in this article. Q-Learning was a development of an Off-Policy Temporal Difference Control Algorithm accomplished in 1989 by Chris Watkins.</p><blockquote>“In this case, the learned action-value function, Q, directly approximates q*, the optimal action-value function, independent of the policy being followed” [1]</blockquote><p>Which elements do we have to considered in a Q-Learning Problem?</p><ul><li><strong>Q-Value</strong>: generally denoted as Q(s,a), corresponding to the expected reward after choosing an action in a particular state, following a decision making strategy. <strong>S</strong> is known as the <strong>state</strong>, while <strong>A</strong> is the <strong>action</strong> taken.</li><li><strong>Q-Function</strong>: it’s a functional representation of the Q-Values, commonly applied to sophisticated problems with continuous states and actions.</li><li><strong>Q-Table</strong>: it’s a data structure that stores the Q values ​​for each state and action pair. Q-Table is used to store and update Q-Values as training phases are completed by interacting with the environment.</li></ul><p>The updating procedure of the Q-Table is accomplished by the Bellman Equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*V1QbJBBISIIzIX84W7nzBw.png" /><figcaption>Bellman Equation</figcaption></figure><p>Where:</p><ul><li><strong>Q(s,a)</strong>: current Q-Value.</li><li><strong>α</strong>: known as the <strong>learning rate</strong>. This parameter determines the magnitude of updating the Q-Values during training. Its range of values is [0,1].</li><li><strong>γ</strong>: known as the <strong>discount factor</strong>. This parameter helps the agent choosing the action, providing an importance value between inmediate rewards over future ones. The higher the value is, the greater the preference for immediate rewards there will be.</li><li><strong>R</strong>: reward expected.</li><li><strong>Max(Q(s’,a’))</strong>: highest Q-Value stored in the Q-Table for the state, between all posible actions.</li></ul><p>Now that I’ve presented a simple overview of this kind of problem… Let’s kick things off with the implementation:</p><h3><strong>Part 1: Environment</strong></h3><p>As previously said, the environment it’s all the data I’ll have in order to train the agent, which in this case is limited by the market we use. I’ve chosen Bitcoin/EUR. Let’s see how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*MA7Z-7Xn_7SyUwxcgAjVsw.png" /><figcaption>Bitcoin/EUR Closing prices between 2014–09–18 and 2023–07–28</figcaption></figure><p>But know, let’s think about the theory mentioned before… If our agent needs to be trained for every single state (which will be the OHLCV data provided), taking into account the unique information every day has… Will ever be a state repeated in the future?</p><p>I truly believe it’s a lost of time trying to train the agent without transforming the data, so, let’s do it! What I’ll take into account when defining the environment the agent will face is the <strong>Rate of Change</strong> or <strong>ROC</strong>. It is defined as the variation between two prices during a period of time. Let’s check it’s formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*2Gv_EVJhF3QAVVxddF3mVg.png" /><figcaption>Rate of Change (ROC) Equation</figcaption></figure><p>Where “Closing Price X” is the actual price, and “Closing Price X-N” is the price N days before the actual one. Now, we might have more interesting data representation but still lots of different states, so I’ll make categories for this transformations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*U4hkkiU0LLsGgtMQFnxXxw.png" /><figcaption>ROC Categories Defined</figcaption></figure><p>Dividing the dataset in this categories, states will be more frequent, making the agent more capable of extracting patterns which could be applied to decision making. Periods included will be N = {1,7,14,30}.</p><p>First of all, considering all the data and the categories, the states will have the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*2w8hQzgzLdj_Nrjo9EwCiQ.png" /><figcaption>Preview example of the proccesed states</figcaption></figure><p>Knowing this, there will be as many Q-Table rows as unique states have been processed.</p><h3>Part 2: Training the Agent</h3><p>Let’s dive right into the training phase. First, we have to define our agent:</p><pre>class AgenteQ:<br>    <br>    def __init__(self, states, num_states, num_actions, learning_rate, discount_factor):<br>        &quot;&quot;&quot;<br>        Default constructor<br><br>        @param num_states: number of existent states in dataset<br>        @param num_actions: number of possible actions<br>        @param learning_rate: magnitude of updating q-values<br>        @param discount_factor: relative importance of long-term rewards<br>        &quot;&quot;&quot;<br>        self.num_states = num_states<br>        self.num_actions = num_actions<br>        self.learning_rate  = learning_rate<br>        self.discount_factor = discount_factor<br>        self.q_table = np.zeros((num_states,num_actions))<br>        self.states = np.array(states)</pre><p>Next, we need to define the method in which the agent will choose the best action:</p><pre>    def choose_action(self,state,epsilon):<br>        &quot;&quot;&quot;<br>        Function used to choose the optimal action through a Epsilon-Greedy policy<br><br>        @param state: state the agent is facing<br>        @param epsilon: exploration-exploitation ratio of actions<br>        &quot;&quot;&quot;<br>        if np.random.uniform() &lt; epsilon:<br>            return int(np.random.choice(self.num_actions))<br>        else:<br>            index = np.where((self.states == state).all(axis=1))<br>            if index[0].size == 0:<br>                return int(0)<br>            else:<br>                return int(np.argmax(self.q_table[index[0],:]))</pre><p>Finally, I’ll define the method which will help us update the actual Q-Values in the Q-Table of the Agent:</p><pre>   def actualize_q_table(self,state,action,reward,next_state):<br>        &quot;&quot;&quot;<br>        Function to update de Q-Values.<br>        <br>        Q(s,a)-&gt;Q(s,a)+α⋅(r+γ*max(a&#39;)*Q(s&#39;,a&#39;)-Q(s,a))<br>            Q(s,a) ===&gt; valor actual para el par state-acción en la Q-Table.<br>            α ========&gt; tasa de aprendizaje (cuan agresivo se produce el ajuste de valores en la Q-Table)<br>            r ========&gt; reward obtenida al tomar la acción &#39;a&#39; en el state &#39;s&#39;<br>            γ ========&gt; factor de descuento (ponderación de importancia de rewards futuras-inmediatas)<br>            max(a&#39;)*Q(s&#39;,a&#39;) ===&gt; máximo valor de la Q-Table para las posibles actiones en el siguiente state (estimación del valor futuro)<br><br>        @param state: state to update<br>        @param action: action choosen<br>        @param reward: reward for taking the action<br>        @param next_state: following state<br>        &quot;&quot;&quot;<br><br>        index = np.where((self.states == state).all(axis=1))<br>        next_state = np.where((self.states == next_state).all(axis=1))<br><br>        # Actual Value -&gt; Q(s,a)<br>        valor_q_actual = self.q_table[index[0],action]<br><br>        # Max. value for the next state -&gt; max(a&#39;)*Q(s&#39;,a&#39;)<br>        valor_q_next = np.max(self.q_table[next_state[0]])<br><br>        # r+γ*max(a&#39;)*Q(s&#39;,a&#39;)<br>        valor_objective = reward + self.learning_rate * valor_q_next<br><br>        # Update the Q-Values of the Q-Table<br>        self.q_table[index[0],action] = valor_q_actual + self.learning_rate*(valor_objective-valor_q_actual)</pre><p>However… How can we initialize our Q-Table? Well, different point of views are discussed about this topic. Although some people decide to initialize the Q-Table with random values, it’s an option to initialize it with 0 (and that is what I choose). So, the first look of the Q-Table will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*HMY624cO5TjI0IT6x3iXyw.png" /><figcaption>Initialization of the Q-Table</figcaption></figure><p>Next, I’ll define the training method:</p><pre>def train_agent(states, dataOHLCV, q_value_agent, initial_investment, num_episodes):<br>        &quot;&quot;&quot;<br>        Function to train the agent<br>        @param states: states provided to the training phase<br>        @param dataOHLCV: OHLCV of the states provided<br>        @param q_value_agent: instance of the define agent<br>        @param initial_investment: initial portfolio value<br>        @num_episodes: number of episodes of the training phase<br>        &quot;&quot;&quot;<br>        max_epsilon = 1.00<br>        min_epsilon = 0.00<br>        exploration_decay_rate = 0.01<br>        epsilon = max_epsilon<br><br>        portfolio_performance = []<br><br>        for iteration in range(num_episodes):<br>            if epsilon-exploration_decay_rate &gt;= min_epsilon:<br>                epsilon = epsilon - exploration_decay_rate<br><br>            Owned = False<br>            Portfolio_Value = []<br>            Portfolio_Value.append(initial_investment)<br>            QuantityOwned = np.float64(0)<br><br>            for i in range(len(states)-1):<br>                # Índices<br>                next = states[i+1]<br>                state = i<br>    <br>                # reward<br>                reward = 0<br><br>                # action a realizar<br>                action = q_value_agent.choose_action(states[i],epsilon)<br><br>                if action == 0:<br>                    if Owned == False:<br>                        reward = (-1)*(((dataOHLCV[i+1,3]-dataOHLCV[i,3])/dataOHLCV[i,3]))*100<br>                        q_value_agent.update_q_table(states[i],action,reward,next)<br>                        Portfolio_Value.append(Portfolio_Value[i])<br>                    else:<br>                        reward = (-1)*(((dataOHLCV[i+1,3]-dataOHLCV[i,3])/dataOHLCV[i,3]))*100<br>                        q_value_agent.update_q_table(states[i],action,reward,next)<br>                        Owned = False<br>                        Portfolio_Value.append(QuantityOwned*dataOHLCV[i,3])<br>                        QuantityOwned = 0<br><br>                elif action == 1:<br>                    if Owned == False:<br>                        reward = ((dataOHLCV[i+1,3]-dataOHLCV[i,3])/dataOHLCV[i,3])*100<br>                        q_value_agent.update_q_table(states[i],action,reward,next)<br>                        Portfolio_Value.append(Portfolio_Value[i])<br>                    else:<br>                        reward = ((dataOHLCV[i+1,3]-dataOHLCV[i,3])/dataOHLCV[i,3])*100<br>                        q_value_agent.update_q_table(states[i],action,reward,next)<br>                        Portfolio_Value.append(QuantityOwned*dataOHLCV[i,3])<br><br>                elif action == 2:<br>                    if Owned == False:<br>                        reward = ((dataOHLCV[i+1,3]-dataOHLCV[i,3])/dataOHLCV[i,3])*100<br>                        q_value_agent.update_q_table(states[i],action,reward,next)<br>                        Owned = True<br>                        QuantityOwned = Portfolio_Value[i-1]/dataOHLCV[i,3]<br>                        Portfolio_Value.append(Portfolio_Value[i])<br>                    else:<br>                        reward = ((dataOHLCV[i+1,3]-dataOHLCV[i,3])/dataOHLCV[i,3])*100<br>                        q_value_agent.update_q_table(states[i],action,reward,next)<br>                        Portfolio_Value.append(QuantityOwned*dataOHLCV[i,3])                    <br>            portfolio_performance.append(Portfolio_Value[len(Portfolio_Value)-1])<br>            <br>        return Portfolio_Value,  portfolio_performance</pre><p>Then, after the training phase, the Q-Table will have this look-alike:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*5hZiqpILhXFvBmpqUfR-Xg.png" /><figcaption>Final State of Q-Table (After training)</figcaption></figure><p>Finally, let’s check what are the returns of our agent during the training! Two different graphs, the final return of our agent and the final the return per epoch during training:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUVK-zlogF65oErtf7iIGQ.png" /><figcaption>Portfolio progress during last training epoch</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oblkSS0gOE1bbAJSFc3jOA.png" /><figcaption>Final Portfolio Return per epoch during training phase</figcaption></figure><h3>Part 3: Testing the Agent</h3><p>This will be the final exam of the agent. Now, it will face unknown data. What will I consider a good result? Well, in this case, given that this is the first RL problem I try to solve, I’ll be satisfied just with returns over Buy &amp; Hold Strategy.</p><p>Let’s have a hasty examination of our testing method:</p><pre>def act(states, dataOHLCV, q_value_agent, initial_investment):<br>    portfolio_performance = []<br>    epsilon = 0.001<br>    Owned=False<br>    <br>    Portfolio_Value = []<br>    Portfolio_Value.append(initial_investment)<br>    <br>    QuantityOwned = np.float64(0)<br><br>    for i in range(len(states)-1):<br>        action = q_value_agent.choose_action(states[i],epsilon)<br>        <br>        if action == 0:<br>            if Owned == False:<br>                Portfolio_Value.append(Portfolio_Value[i])<br>            else:<br>                Owned = False<br>                Portfolio_Value.append(QuantityOwned*dataOHLCV[i,3])<br>                QuantityOwned = 0<br><br>        elif action == 1:<br>            if Owned == False:<br>                Portfolio_Value.append(Portfolio_Value[i])<br>            else:<br>                Portfolio_Value.append(QuantityOwned*dataOHLCV[i,3])<br><br>        elif action == 2:<br>            if Owned == False:<br>                Owned = True<br>                QuantityOwned = Portfolio_Value[i-1]/dataOHLCV[i,3]<br>                Portfolio_Value.append(Portfolio_Value[i])<br>            else:<br>                Portfolio_Value.append(QuantityOwned*dataOHLCV[i,3])         <br><br>        portfolio_performance.append(Portfolio_Value[len(Portfolio_Value)-1])<br>    return Portfolio_Value</pre><p>Let’s wrap this project up! This is the portfolio value during testing phase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4iADuS0dHhtaalrRNMXDw.png" /><figcaption>Bitcoin Price vs Portfolio Value</figcaption></figure><p>As you can see, the agent hasn’t lost value through the testing phase, but the final value is still lower than the Buy &amp; Hold strategy:</p><ul><li><strong>Final Value</strong>: 10.538,16€</li><li><strong>Buy &amp; Hold Return</strong>: 12.474,00€</li></ul><p>Even though Buy &amp; Hold takes the win, clearly there’s room to improve. A promising piece of information we could extract, it’s that the maximum value obtained while testing was <strong>11.994,00€</strong>, which is closer to Buy &amp; Hold strategy. There’s several things we need emphasize:</p><ul><li>I have just provided ROC Data to the Agent, and clearly, this is not even a trading strategy. More sophisticated ones could be tried in the future.</li><li>No complex preprocessing phase. Usually, correlation analysis have to be made to improve data quality provided to the agent.</li><li>No complex hyperparameters tuning made. This is complicated problem in itself.</li></ul><p>This could be future steps of the project, or even following steps for the reader if you consider so. Mainly, this topics haven’t been covered because my main aim was to get to known new types of ML solutions, while I’m quite interested in algorithmic trading.</p><h3>Thanks for reading!</h3><p>Well, that was it. I hope you enjoy my first post. It’s my first time writing on a blog and I’m not quite sure whether this could help the reader to initiate her/himself with RL.</p><p>Taking this into account, every single doubt or advice you want to give me… will be really appreciated! Hope we’ll see again soon in another project!</p><h3>References</h3><p>This are some recommended lectures to fully understand RL and Q-Learning, used for the article:</p><ul><li>[1] R. S. Sutton y A. G. Barto, Reinforcement Learning: An Introduction (Second Edition).</li><li>[2] Y. Hilpisch, Python For Finance: Mastering Data-driven Finance.</li><li>[3] J. P. Mueller y L. Massaron, Machine Learning for Dummies.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2faa5d09caa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>