<?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 Mateusfreitasrosa on Medium]]></title>
        <description><![CDATA[Stories by Mateusfreitasrosa on Medium]]></description>
        <link>https://medium.com/@mateusfreitasrosa?source=rss-82c78f2a5a97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1dFfXLAkB0MyP7FjpvQruQ.jpeg</url>
            <title>Stories by Mateusfreitasrosa on Medium</title>
            <link>https://medium.com/@mateusfreitasrosa?source=rss-82c78f2a5a97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:54:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mateusfreitasrosa/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[Connecting Texts with LLMs and Graphs: An Approach for Identifying Similar Themes]]></title>
            <link>https://medium.com/@mateusfreitasrosa/connecting-texts-with-llms-and-graphs-an-approach-for-identifying-similar-themes-7b8c2e11adbc?source=rss-82c78f2a5a97------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b8c2e11adbc</guid>
            <category><![CDATA[ai-text-segmentation]]></category>
            <category><![CDATA[ai-document-analysis]]></category>
            <category><![CDATA[text-clustering]]></category>
            <category><![CDATA[llms-and-graph-theory]]></category>
            <category><![CDATA[cosine-similarity]]></category>
            <dc:creator><![CDATA[Mateusfreitasrosa]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 21:17:39 GMT</pubDate>
            <atom:updated>2024-09-08T21:47:35.521Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! My name is Mateus Rosa. I’ve been a data scientist since February 2021 and graduated in Information Systems in August 2022. This past week, I participated in a challenge proposed by my leadership in my current position. In this challenge, together with my colleagues, I was able to explore and combine techniques that I already knew, but had not yet applied together. For this reason, I want to share this learning/”discovery”.</p><p>To start the article, I first want to ask you a few questions. Have you ever heard of LLMs or Large Language Models, or perhaps the term NLP, Natural Language Processing? Have you ever worked with or applied graph theory to a solution? Do you know the power of this data structure? Have you ever imagined needing to search for a text document among thousands of other documents, without Dr. Google? Or better yet, have you ever imagined having just a few hours to deliver a spreadsheet to your boss segmenting topics from text documents, but there are thousands of text documents?</p><p>Well, the purpose of this article is to introduce you to a small piece of the world of LLMs and the combination of these models with graph theory for text segmentation.</p><p>Today, we have all had some interaction with artificial intelligence, even if indirectly. Social networks, video games, banking systems, ChatGPT, and many other systems use some form of artificial intelligence in their operations. These models can be supervised, unsupervised, reinforcement-based, or LLMs. They are designed to solve problems where predefined calculations or equations do not exist, approaching solutions with high accuracy, even if they are not 100% precise. This highlights the impact of artificial intelligence and its ability to generate financially beneficial solutions.</p><p>Looking at the current market, we see that many companies have long been using supervised, unsupervised, and reinforcement learning models that address various business problems. With the advent of LLMs, we are witnessing a significant evolution in how we approach and solve complex problems.</p><p>In this article, we will explore how combining LLMs with graph theory can enhance the segmentation of text documents. By leveraging LLMs, which excel in understanding and generating human language, along with the structured data framework of graph theory, we can create innovative solutions for organizing and analyzing large volumes of textual data. This integration allows us to uncover relationships and patterns that would be challenging to identify using traditional methods.</p><p>We will delve into the specifics of how LLMs can be used to extract and encode text data, and how graph theory can be employed to model and analyze the connections between various documents. By the end of this article, you will gain insights into this approach and its practical applications, demonstrating the potential of these technologies to transform text analysis and data organization. And finally, I hope this article helps you not only to successfully perform text segmentation but also to ignite your creativity for the universe of LLMs, understanding their potential both technologically and financially.</p><p>With that said, let’s embark on this short journey into exploring and implementing a process that segments similar text documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*dW2gn4wpgUVGVXm9.gif" /></figure><p>We will be using the <strong>Medium Post Titles Dataset</strong>. This dataset contains titles and subtitles of articles published on the <a href="https://www.kaggle.com/datasets/nulldata/medium-post-titles">Medium Post Titles</a>. Currently, it has 126,418 rows of data, which is a considerable amount for our practical example. Therefore, we will choose to use only a fraction of this dataset to facilitate processing.</p><p>Additionally, I would like to highlight the website <a href="https://huggingface.co/">Hugging Face</a>, which offers a wide range of models trained by the community. These models range from binary classifiers to text, audio, and video generators. Hugging Face is a powerful tool to explore, and we mention it here because we will use one of their models to generate embeddings, a fundamental component for our text segmentation task.</p><h3>Installing Dependencies</h3><p>Let’s start by installing the necessary libraries for our project:</p><pre>!pip install sentence_transformers networkx numpy scikit-learn torch pandas</pre><p>Here is a brief explanation of what each library does:</p><ul><li><strong>sentence_transformers</strong>: Allows the use of sentence embedding models, such as BAAI/bge-m3, to convert text data into numerical vectors for analyzing similarities and clustering.</li><li><strong>networkx</strong>: Used for creating and manipulating graphs, essential for our graph-based text segmentation.</li><li><strong>numpy</strong>: A numerical computing library that facilitates mathematical operations with arrays and matrices.</li><li><strong>scikit-learn</strong>: Provides tools for machine learning, such as cosine similarity calculations, to help measure how similar texts are based on their embeddings.</li><li><strong>torch</strong>: A framework used for tensor computation, especially useful in deep learning and GPU utilization.</li><li><strong>pandas</strong>: Facilitates data manipulation and analysis by providing fast and flexible data structures like DataFrames.</li></ul><p>These libraries are essential to build a complete text segmentation solution based on graphs and embeddings.</p><h3>(Optional) Accelerating with GPU</h3><p>If you have an Nvidia GPU and want to accelerate the embedding generation process, you can also install PyTorch with GPU support by following the instructions in the <a href="https://pytorch.org/get-started/previous-versions/">official documentation</a>. Utilizing a GPU can significantly speed up the execution time. However, it is important to properly configure CUDA, a crucial step for your GPU to be used in the process.</p><p>If you do not have a GPU or prefer not to go through the CUDA setup, don’t worry: the entire tutorial can still be executed normally with a CPU, although the embedding process may be a bit slower.</p><h3>Now, Let’s Get to What Matters!</h3><p>With everything set up, we are ready to start developing our text segmentation solution using graphs. We will use the <strong>BAAI/bge-m3</strong> model to generate embeddings that will help us efficiently group texts. Let’s explore how these techniques, when combined, allow us to understand and categorize large volumes of textual data.</p><p>Get ready to dive into the world of LLMs and graph theory!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*mzFMN54r8suGz88j.gif" /></figure><h3>Loading the Data</h3><p>First, let’s load the dataset and select a smaller sample for processing. This step is crucial to avoid memory issues since the process involves creating Cartesian products between the data, which causes the complexity to grow exponentially (O(n²)) as the number of texts increases.</p><pre>import pandas as pd<br><br># Load the dataset containing the titles of Medium posts<br>df_post_title = pd.read_csv(&#39;medium_post_titles.csv&#39;)<br><br># Reduce the dataset to a sample of 10,000 entries for faster processing<br>df_post_title = df_post_title.sample(10000)<br><br># Reset the indices to be sequential, which is necessary for the embedding process<br>df_post_title.reset_index(drop=True, inplace=True)<br><br># Print the shape of the dataset to verify the size<br>df_post_title.shape</pre><h3>Loading the BAAI/bge-m3 Model</h3><p>Now, let’s load the pre-trained <strong>BAAI/bge-m3</strong> model for generating embeddings.</p><pre>from sentence_transformers import SentenceTransformer<br><br># Load the pre-trained BAAI/bge-m3 model<br>model = SentenceTransformer(&#39;BAAI/bge-m3&#39;)<br>print(&#39;BAAI/bge-m3 model loaded successfully.&#39;)</pre><p>The <strong>BAAI/bge-m3</strong> model is a pre-trained large language model (LLM) designed for generating high-quality embeddings from text. It is useful for tasks such as text clustering, similarity, and classification. This model effectively captures semantic information, making it ideal for downstream NLP applications.</p><p>For more details, feel free to visit the official model page on Hugging Face: <a href="https://huggingface.co/BAAI/bge-m3">BAAI/bge-m3</a>.</p><p>Now that we have our data and model ready, let’s move forward with creating embeddings and building a graph-based solution for text segmentation!</p><h3>Generating Embeddings</h3><p>Now, let’s generate the embeddings.</p><pre>%%time<br><br># Assuming `df_post_title` contains columns &#39;title&#39; and &#39;subtitle&#39;<br># Convert and get the columns to string format<br>post_titles = df_post_title[&#39;title&#39;].astype(str)<br>post_subtitles = df_post_title[&#39;subtitle&#39;].astype(str)<br><br># Generate embeddings for the post titles<br>title_embeddings = model.encode(post_titles)<br>print(&#39;Title embeddings successfully generated.&#39;)<br><br># Generate embeddings for the post subtitles<br>subtitle_embeddings = model.encode(post_subtitles)<br>print(&#39;Subtitle embeddings successfully generated.&#39;)</pre><h3>A Brief Introduction to This Term:</h3><p>Embeddings are dense vector representations of data, where each item (such as a word, sentence, or document) is mapped to a continuous-valued vector in a high-dimensional space. These vectors capture semantic relationships between items, allowing similar items to have similar embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-1Yh2XzfLEkK0RVO6y5IQ.png" /></figure><p>In the image above, we illustrate the process of generating embeddings. A sentence like “Coffee, because adulting is hard.” passes through an embedding model that transforms the text into a vector of numerical values. Each vector represents the core information of the text, which can be used in various machine learning tasks, such as text clustering or similarity searches. These embeddings enable algorithms to process and compare large amounts of text efficiently.</p><h3>Calculating Similarity Between Embeddings Using Cosine Similarity</h3><pre>from sklearn.metrics.pairwise import cosine_similarity<br>import numpy as np<br><br># Compute cosine similarity for title and subtitle embeddings<br>title_similarity = cosine_similarity(embeddings_title)<br>subtitle_similarity = cosine_similarity(embeddings_subtitle)<br><br># Define weights for title and subtitle similarities<br>title_weight = 0.5<br>subtitle_weight = 0.5<br><br># Compute weighted combined similarity matrix<br>combined_similarity_matrix = (<br>    title_weight * title_similarity +<br>    subtitle_weight * subtitle_similarity<br>)<br><br>print(&quot;Weighted combined similarity matrix computed successfully.&quot;)</pre><p>Cosine Similarity measures the angle between two vectors in a vector space, as shown in the image below. When the vectors point in the same direction (smaller angle), the cosine similarity is close to 1, indicating that the texts are semantically similar. When the angle between the vectors is larger, the similarity is closer to 0, suggesting that the texts are different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igDGQLsTl1LK-VDV7ufTIg.png" /></figure><p>In the example shown in the image, each sentence is converted into an embedding vector, which can be represented by a set of numbers that capture its semantic characteristics. The angle θ between these vectors indicates the similarity between the texts. The smaller the angle, the greater the similarity.</p><p>In the provided code, we calculate the cosine similarity for the embeddings of both titles and subtitles, allowing us to identify how similar they are to each other. After that, we perform a weighted average of these similarities, combining the two results with equal weights to create a final similarity matrix that takes into account both the titles and subtitles of the texts.</p><p>At this point, the output of the cosine_similarity function consists of a square matrix whose dimensions are determined by the number of texts provided. In our example, considering 10,000 rows of data, we obtain a similarity matrix of size 10,000 x 10,000. This matrix represents the similarity between all possible combinations of these 10,000 texts. For instance, the first row of the matrix shows the similarity between the first embedding and all other embeddings.</p><h3>Filtering Combinations with High Similarity</h3><p>From the 10,000 x 10,000 matrix generated by the previous function, we realize that not all combinations are of interest. Therefore, we need to filter the combinations that show a similarity above a certain threshold. The <strong>threshold</strong> represents the cutoff point from which we consider two texts to be similar. In the following example, we set a threshold of 0.8. This means that similarities above 0.8 are considered as similar texts, while values below this threshold are not.</p><pre># Apply the threshold to filter similar texts<br>threshold = 0.8<br>similar_texts = np.argwhere(combined_similarity_matrix &gt; threshold)</pre><h3>Defining Textual Groups with Graphs</h3><p>Graphs are extremely useful data structures for representing interrelated information. They are particularly effective when these connections have a level of strength, distance, or any other metric that highlights the relationship between two or more points. In our case, we want to use graphs to group texts that are similar to each other, as determined by the embeddings and the calculated similarities.</p><p>In the image below, I present a graph representation that illustrates distances between cities. The connections represent the paths between cities and their respective distances in miles. This is a simplified example to help understand the concept of graphs. This type of representation is widely used in the <strong>Traveling Salesman Problem</strong>, which aims to determine the most efficient route (with the least cost or distance) while traveling through all cities in an optimized manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbpXu8go1930XnVvPJWB4Q.png" /></figure><p>Now, let’s apply the concept of graphs to our text segmentation problem. In the following image, we see groups of text themes represented as graphs. Each node in the graph represents a text, and the edges indicate the similarity between them, based on the generated embeddings. The groups formed, such as “jazz music,” “AI: Self-Driving Cars,” and “Basic statistics,” demonstrate how texts can be grouped based on their similarities, creating distinct thematic clusters. This visualization helps to understand the connections and emerging themes among the texts, using embedding and graph techniques to organize large volumes of data in a meaningful way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBFDbaAcGmP7sFgn8mg-Pw.png" /></figure><p>In the image above, by setting a higher similarity threshold, we can identify groups of themes that are semantically closer. This allows us to visualize how certain texts are more strongly connected to each other, forming distinct clusters, such as “jazz music,” “AI: Self-Driving Cars,” and “Basic statistics.”</p><h3>Building the Similarity Graph</h3><p>To create a graphical representation of text groups that have high similarity among themselves, we will use the networkx library to construct a graph. Each node in the graph will represent a text, and the edges (connections) between them will be weighted by the similarity between the texts, as determined by the combined similarity matrix.</p><pre>import networkx as nx<br><br># Create a graph<br>G = nx.Graph()<br><br># Add edges to the graph with weights based on text similarity<br>for (i, j) in similar_texts:<br>    # Set the weight using the similarity matrix<br>    weight = combined_similarity_matrix[i, j]<br>    G.add_edge(int(i), int(j), weight=weight)<br><br>print(&quot;Graph constructed with nodes representing texts and weighted edges representing text similarities.&quot;)</pre><h3>Analyzing Text Groups</h3><p>After defining the graph, the next step is to identify the connected components, i.e., groups of texts that are directly or indirectly related to each other. By doing this, we can visualize which texts are grouped based on high similarity.</p><pre># Find all connected components (clusters) in the graph<br>connected_components = list(nx.connected_components(G))<br><br># Convert connected components to a list of lists<br>grouped_values = [list(component) for component in connected_components]<br><br>print(&quot;Connected node groups:&quot;)<br>print(grouped_values)</pre><h3>Assigning Groups and Calculating Average Similarity in the DataFrame</h3><p>Now that we have identified the connected text groups, we can add this information to our initial DataFrame. For each text, we assign a group and calculate the average similarity of the connections within that group.</p><pre>import numpy as np <br><br># Add a &#39;group&#39; column initialized as NaN<br>df_post_title[&#39;group&#39;] = np.nan<br><br># Add a &#39;mean_similarity&#39; column to store the average similarity values<br>df_post_title[&#39;mean_similarity&#39;] = np.nan<br><br># Map each node to its group<br>node_to_group = {}<br>for idx, group in enumerate(grouped_values):<br>    for node in group:<br>        node_to_group[node] = idx<br><br># Fill the &#39;group&#39; column in the DataFrame<br>df_post_title[&#39;group&#39;] = df_post_title.index.map(node_to_group)<br><br>print(&quot;Group assignment to DataFrame completed.&quot;)<br>print(df_post_title[&#39;group&#39;].value_counts())</pre><h3>Calculating the Similarity Strength of Each Group</h3><p>Finally, for each group of texts, we calculate the average similarity of the connections (edges) between the nodes (texts) within that group. This gives us an idea of how strongly connected each group is. The more connected a group is, the higher the group’s average similarity.</p><pre># Calculate the average similarity values for each group<br>group_similarities = {}<br>for group in grouped_values:<br>    # Find all edges within the group<br>    edges = [(u, v) for u in group for v in group if u &lt; v]<br>    if edges:<br>        # Calculate the sum of similarities for the edges in the group<br>        total_similarity = sum(G[u][v][&#39;weight&#39;] for u, v in edges if G.has_edge(u, v))<br>        avg_similarity = total_similarity / len(edges)<br>    else:<br>        avg_similarity = 0<br>    group_aux = int(df_post_title.iloc[group[0]][&#39;group&#39;])<br>    group_similarities[group_aux] = avg_similarity  # Use the first node as the group identifier<br><br># Fill the &#39;mean_similarity&#39; column in the DataFrame with the average similarity for each group<br>df_post_title[&#39;mean_similarity&#39;] = df_post_title[&#39;group&#39;].map(group_similarities)<br><br>print(&quot;Average similarity for each group calculated and added to DataFrame.&quot;)</pre><p>The final result is a DataFrame with the columns group and mean_similarity, where each row represents the group to which the text belongs and the group&#39;s average similarity. It is interesting to note that the mean_similarity value reflects how connected the group is. If the group has strong and numerous connections, the value will be high; if it is less connected, the value will be low.</p><p>Finally, we have the result of clustering the Medium articles. In the image below, I present one of the groups defined by the algorithm. Notice that, in this group, the focus is on Artificial Intelligence (AI) and its application in autonomous cars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*D4NLtyb8MjC8apWVdNJIVw.png" /></figure><p>In the image below, we have another group that suggests a theme related to Jazz music.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*5fsctzH9TPBLOPvg43ajiw.png" /></figure><p>The algorithm generates several groups due to its simple implementation (which is the main goal of this article: to present clear and accessible code). However, you can go beyond this initial step by applying some improvements to refine the results.</p><p>For example, you could remove groups that contain only a single text (outliers), which would significantly reduce the number of groups, but also leave many articles without a defined group. Another approach is to experiment with different threshold values to see how the model behaves with higher or lower similarity cutoffs.</p><p>These refinement steps will allow for more detailed text segmentation, providing a more robust and customized analysis of large volumes of textual data.</p><h3>We Have Reached the End!</h3><p>I hope you enjoyed this journey exploring LLM algorithms together with graph theory. Keep in mind that this is just one of the many ways to approach this topic. We could, for example, use clustering algorithms instead of graphs, among other approaches. However, the goal of this article is to spark the reader’s curiosity, presenting LLMs and showing how this technique can be combined to solve contemporary problems. I hope I have managed to convey both knowledge and curiosity for the vast universe of LLMs.</p><p>If you are still hungry for knowledge, here are some interesting approaches that utilize much of what we learned in this article:</p><ul><li><strong>Intelligent Search System</strong>: Develop a system that, given an input text, can find related documents that match the context or theme of the searched text.</li><li><strong>Clustering with Unsupervised Models</strong>: Explore techniques such as K-means, DBScan, among others, to cluster texts based on embeddings, without needing prior knowledge about the number of groups.</li><li><strong>Topic Classification with Transformer Models</strong>: Use LLMs like BERT and GPT to automatically categorize texts into predefined topics, improving large-scale document classification systems.</li></ul><p>Thanks for joining me on this journey! See you in the next adventure, young padawan! 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*cC1BMsmZ3qHKOi40.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b8c2e11adbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop Your First Reinforcement Learning Algorithm for Video Games (from scratch!!!).]]></title>
            <link>https://medium.com/@mateusfreitasrosa/develop-your-first-reinforcement-learning-algorithm-for-video-games-from-scratch-20c84df1eaab?source=rss-82c78f2a5a97------2</link>
            <guid isPermaLink="false">https://medium.com/p/20c84df1eaab</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Mateusfreitasrosa]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 02:48:55 GMT</pubDate>
            <atom:updated>2023-08-14T02:48:55.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! My name is Mateus de Freitas Rosa. I’ve been a data scientist since February 2021 and graduated in Information Systems in August 2022. For my Final Year Project, I developed a Reinforcement Learning model geared towards video games. This project was the starting point in my journey with this machine learning technique. I’m excited to share this knowledge with you!</p><p>To begin our learning and coding journey, it’s essential that we first set up our development environment. This ensures that we’re all working in sync and achieving similar results when following the same instructions.</p><p>In this case, I’ll be using the Anaconda platform to set up our development environment. Anaconda is a free and open-source distribution of the Python and R programming languages, and it’s widely used for data science and machine learning. Moreover, it provides a convenient system for package management and virtual environments, which allows us to isolate different projects and their respective dependencies.</p><p>If you wish to follow along and replicate my steps, I suggest you install Anaconda on your machine. This will ensure our working environments are identical, and our code runs the same way.</p><p>To download and install the Anaconda platform, you can visit the official website: <a href="https://www.anaconda.com/">https://www.anaconda.com/</a>. There you will find the latest versions of the Anaconda distribution for different operating systems. Choose the version that fits your OS best, download it, and follow the installation instructions.</p><p>From this point on, I’m assuming you have successfully installed the Anaconda platform on your machine. If you encountered any issues during the installation, there are plenty of online resources, including the official Anaconda documentation, that can help you troubleshoot any problems you might have faced.</p><p>With the Anaconda platform installed, we’re ready to start setting up our development environment and dive into the world of Reinforcement Learning!</p><h3>1. Environment Setup</h3><p>In this guide, we’ve chosen to use older versions of Python, as well as packages like Tensorflow, Keras, among others. The reason for this is that we specifically want to use version 1 of Tensorflow. In my personal setup and testing, I found that TensorFlow 1 tends to prioritize CPU usage over GPU. Surprisingly, on my machine, this CPU preference resulted in notably superior performance, making the training processes more efficient. It’s crucial to point out that this observation is based on my personal experience, and may vary depending on the setup and specifications of other machines.</p><p>Thus, this document will teach you how to develop an intelligent agent using reinforcement learning and computer vision with TensorFlow 1. If you’re already familiar with TensorFlow 2 and feel comfortable using it, you’re free to adapt and apply different configurations than mine.</p><h4>1.1 Creating a Virtual Environment with Anaconda</h4><p>To create a virtual environment in Anaconda, you have the option of using the graphical interface or the command line. To use the command line, open the “Anaconda Prompt”.</p><p>Run the command below to create a new virtual environment:</p><pre>conda create -n reinforcementlearning python=3.6</pre><p>This command does the following:</p><ul><li>conda create: this is the command that instructs Anaconda to create a new virtual environment.</li><li>-n reinforcementlearning: this part names the environment “reinforcementlearning”.</li><li>python=3.6: this specifies that we want to use Python version 3.6 in this environment.</li></ul><p>In summary, the above command is directing Anaconda to create a new virtual environment named “reinforcementlearning”, with Python version 3.6 installed.</p><h4>1.2 Accessing the Previously Created Environment</h4><p>After creating the virtual environment in Anaconda, we need to “activate” it in order to use it. This is done by entering the virtual environment, which can be done through the command line. The command to activate the environment is:</p><pre>conda activate reinforcementlearning</pre><p>This command has the following parts:</p><ul><li>conda activate: This is the command that instructs Anaconda to activate a specific environment.</li><li>reinforcementlearning: This is the name of the environment we created earlier and want to activate now.</li></ul><p>In summary, by running the above command, you are telling Anaconda to enter the virtual environment named “reinforcementlearning”, making it the active environment for your current session. This means any package you install or any code you run will be done within this environment, isolated from the rest of the system.</p><h4>1.3 Installing Required Packages</h4><p>To install the libraries required for our project, we will continue to use the Anaconda Prompt, which we have had open since the previous steps.</p><p>Here is the list of essential packages we need for our project to function:</p><pre>conda install -c conda-forge gym<br>pip install tensorflow==1.13.1<br>pip install keras==2.2.4<br>pip install opencv-python<br>pip install numpy<br>pip install pandas<br>pip install matplotlib<br>pip install imageio                <br>conda install -c conda-forge gym-atari<br>pip install imageio-ffmpeg                           <br>pip install jupyterlab</pre><p>Each line of this code block is a command that installs a specific package. To avoid potential errors, it’s recommended that you execute each line individually, waiting for the complete installation of the package before proceeding to the next one.</p><p>These commands ensure that all the libraries we need, such as TensorFlow for creating convolutional neural networks, Gym for simulating the game environment, and other useful libraries for data manipulation and graphics, are installed and ready for use in our “reinforcementlearning” environment.</p><p>Excelente! Agora temos um ambiente virtual Anaconda completamente configurado e pronto para mergulharmos de cabeça na programação!</p><h3>2. Introduction to Development</h3><p>I’d like to emphasize that reinforcement learning is a topic that requires some prior knowledge for those who wish to delve deeper, or even for the full understanding of the project we are undertaking. Thus, this article assumes you have some familiarity with Machine Learning, Artificial and Convolutional Neural Networks, intermediate Python programming skills, Linear Algebra, among other knowledge.</p><p>However, if you feel you’re lacking any of these prerequisites, don’t worry. This article has been structured in such a way that, even without mastering all these concepts, you can still follow the journey and achieve the end goal: to develop an intelligent agent that plays Atari games. The content has been crafted incrementally, making it easier to understand and apply concepts, even if they’re new to you.</p><p>Furthermore, I’ll be available to clarify any doubts that may arise throughout this process, making this an ideal environment for both learning and practice. So, feel encouraged to embark on this journey with us!</p><h4>2.1 What is Reinforcement Learning?</h4><p>Reinforcement learning is a subfield of artificial intelligence that uses the idea of reward and punishment to guide an agent in learning the best actions to take in specific situations.</p><p>In this type of learning, the agent (a computer program, a robot, or another autonomous system) interacts with an environment and, with every action it takes, receives feedback. This feedback can be positive (a reward) if the action was beneficial, or negative (a punishment) if it was harmful. The agent then uses this feedback to learn which actions are the best to take in each situation, aiming to maximize the total sum of rewards over time.</p><p>Essentially, reinforcement learning is an optimization process: the agent seeks to learn the best action policy — a kind of “rule map” that dictates which action to take in each situation — to obtain the highest possible reward. This type of learning is especially useful in scenarios where the agent must learn to make decisions on its own, basing its actions on the experience gained through trial and error.</p><p>In this context, video games emerge as excellent testbeds for reinforcement learning. They offer complex and challenging environments that allow the agent to explore, make mistakes, and succeed, ultimately finding the most efficient solutions. Each game played becomes an opportunity to learn and refine strategies, making games an ideal platform for applying reinforcement learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*IXnrmsgsap5vjFJV.png" /></figure><p>The image above provides a visual representation of how reinforcement machine learning operates. Begin by imagining that our agent is in an initial position, which we call State (St). From this point, the agent performs an action (At) at a specific moment t, interacting with the environment. In response to the agent’s action, the environment not only offers feedback in the form of a reward (Rt+1) but also reveals the next state (St+1). This cycle, action-reward-state, repeats, fueling the agent’s ongoing learning process.</p><h3>3. Building the Intelligent Agent</h3><p>We’ve already had quite a chat, haven’t we? Hehehe. Now, how about we move from talking and jump into action? In this next step, I’ll use the code I developed during my undergraduate thesis research, but with some adjustments to make it easier to understand: <a href="https://repositorio.ufu.br/handle/123456789/36265">https://repositorio.ufu.br/handle/123456789/36265</a>.</p><p>Hey, did you notice that we left some reinforcement learning concepts undefined? You’re right! But, I have a plan: how about I introduce these concepts as we build our agent? This way, you can see everything in action and, surely, it will be easier to grasp. So, are you ready to continue this adventure? Don’t worry; our conversation is far from over!</p><h4>3.1 Importing the libraries we will use</h4><pre>import gym<br>import cv2<br>import numpy as np<br>from collections import deque<br>import imageio<br>import os<br>import random<br>import matplotlib.pyplot as plt<br>import pickle<br>import time<br>import pandas as pd<br>import itertools<br><br>import tensorflow as tf<br>from keras import backend as K<br><br>from keras.models import Sequential<br>from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten<br>from keras.optimizers import Adam</pre><p>These are all the packages we will need for this project. As we progress through the development, I will explain the function of each of them.</p><h4>3.2 Definition of the Agent object and its parameters.</h4><pre>class Agent(): <br>    def __init__(self, state_size, action_size):<br>        self.state_size                 =       state_size<br>        self.action_size                =       action_size<br>        self.memory                     =       deque(maxlen=LEN_MEMORY_QUEUE)<br>        self.min_learning_rate          =       .0008<br>        self.max_learning_rate          =       .01<br>        self.epochs_interval_lr         =       150<br>        self.learning_rate_decay        =       (self.max_learning_rate - self.min_learning_rate) / self.epochs_interval_lr<br>        self.gamma                      =       .99<br>        self.exploration_rate           =       1<br>        self.exploration_min            =       .07<br>        self.exploration_decay          =       1 / 100000 # A variável irá se atualizar.<br>        self.k_frames                   =       4<br>        self.frame_height               =       self.state_size[0]<br>        self.frame_width                =       self.state_size[1]<br>        self.brain                      =       self._build_model()<br>        self.brain_target               =       self._build_model()<br>        self.freq_update_nn             =       1000<br>        self.initial_start_size         =       5000</pre><ul><li><strong>state_size</strong>: This variable represents the dimensions of the state. In our case, since the state is an image, and we consider it as a two-dimensional matrix, the state_size represents the format of this matrix.</li><li><strong>action_size</strong>: This refers to the number of possible actions the agent can perform. Depending on the game, this number may vary. In our case, with Pong-v0, we only have three possible moves for the paddle: move up, move down, or stay still.</li><li><strong>memory</strong>: This is where we store the agent’s memory, which includes all states, future states, rewards, and actions.</li><li><strong>min_learning_rate</strong>, <strong>max_learning_rate</strong>, <strong>epochs_interval_lr </strong>e <strong>learning_rate_decay</strong>:<br>In the model I’m presenting, I found that adjusting the agent’s learning rate allows it to evolve faster. We set a maximum and minimum learning rate, an epoch interval to oscillate between these rates, and the learning_rate_decay calculates how much we need to reduce the maximum rate to reach the minimum rate within the epoch interval.</li><li><strong>gamma</strong>:<br>This constant is used in the reinforcement learning calculation.</li><li><strong>exploration_rate</strong>:<br>Indicates the initial exploration rate (epsilon).</li><li><strong>exploration_min</strong>:<br>This is the minimum exploration rate or limit.</li><li><strong>exploration_decay</strong>:<br>Represents the decline of the exploration rate with each training session.</li><li><strong>k_frames<br></strong>This parameter represents the number of concatenated images that will be used to feed the Convolutional Neural Network. When this value is greater than 1, it transforms the input image for the Convolutional Neural Network into a three-dimensional structure, where the third dimension introduces a temporal element to the image.</li><li><strong>frame_height</strong> e <strong>frame_width</strong>:<br>They are simply the height and width of the state_size variable.</li><li><strong>brain</strong> e <strong>brain_target</strong>:<br>Here we have a crucial point. Why do we create two convolutional neural networks for a single agent? Reinforcement learning involves an agent performing actions to find combinations that maximize its reward. To do this, the agent will need to train its neural network every K frames. However, if we do this with a single neural network, learning becomes unstable because we would be constantly changing the neural network’s state. The solution to this problem is to use two neural networks. The second neural network (the more stable one — brain_target) is used only to predict the agent’s next actions, and we update its weights with those of the first neural network (the less stable one — brain) every “freq_update_nn” training sessions.</li><li><strong>freq_update_nn</strong>:<br>Indicates the number of training sessions between each update of the second neural network, the brain_target.</li><li><strong>initial_start_size</strong>:<br>Represents the minimum number of frames we need to store in memory before starting to train the model.</li></ul><h4>3.3 Creating the Convolutional Neural Network Architecture</h4><pre>def _build_model(self):<br>        # Neural Net for Deep-Q learning Model<br>        model = Sequential()<br>        <br>        ## Build Convolutional NetWork<br>        model.add(Conv2D(32, (8,8), strides=4, input_shape=(self.state_size[0], self.state_size[1], self.k_frames), activation=&#39;relu&#39;, padding=&#39;valid&#39;))<br>        model.add(Conv2D(64, (4,4), strides=2, activation=&#39;relu&#39;, padding=&#39;valid&#39;))<br>        model.add(Conv2D(64, (3,3), strides=1, activation=&#39;relu&#39;, padding=&#39;valid&#39;))<br><br>        model.add(Flatten())<br>        ## Build Neural Network<br>        model.add(Dense(512, activation=&#39;relu&#39;))          <br>        model.add(Dense(256, activation=&#39;relu&#39;, kernel_initializer=&#39;glorot_uniform&#39;))<br>        model.add(Dense(64, activation=&#39;relu&#39;, kernel_initializer=&#39;glorot_uniform&#39;))<br>            <br>        model.add(Dense(self.action_size, activation=&#39;linear&#39;))<br>        model.compile(loss=huber_loss_mean, optimizer=Adam(lr=self.max_learning_rate))<br>            <br>        model.summary()<br><br>        return model</pre><p>This architecture is rooted in the article “Human-level control through deep reinforcement learning” authored by Minh and his collaborators (Mnih, Volodymyr, et al., nature 518.7540, 2015: 529–533). Due to the complexity of the topic, I won’t go into detail about each parameter of the architecture in this article. I strongly recommend that you delve into each method presented in the Keras documentation for a more in-depth understanding. Broadly speaking, we create a convolutional architecture to accept the pre-processed image. This output is then fed into an Artificial Neural Network that will perform the subsequent processing.</p><h4>3.4 Stacking “k-frames” images</h4><pre>## Build batch of images for train<br>def pack_K_frames(self, sample_batch_size):<br>        if len(self.memory) &lt; self.k_frames+2:<br>            return<br>        <br>        state = np.empty((sample_batch_size, self.k_frames, self.frame_height, self.frame_width))<br>        action = np.empty(sample_batch_size, dtype=np.uint8)<br>        reward = np.empty(sample_batch_size, dtype=np.float32)<br>        next_state = np.empty((sample_batch_size, self.k_frames, self.frame_height, self.frame_width))<br>        done = np.empty(sample_batch_size, dtype=np.bool_)<br><br>        for k in range(sample_batch_size):<br>            index = random.randint(0, len(self.memory)-self.k_frames-2)<br>            <br>            for i, idx_memory in enumerate(range(index, index+self.k_frames)):<br>                s, a, r, n_s, d = self.memory[idx_memory]<br>            <br>                state[k][i] = s<br>                next_state[k][i] = n_s<br>                <br>            done[k] = d<br>            action[k] = a<br>            reward[k] = r<br>              <br>        #State = (32,4,84,84)  -&gt; State Transpose = (32,84,84,4) <br>        return np.transpose(state, axes=(0,2,3,1)), action, reward, np.transpose(next_state, axes=(0,2,3,1)), done<br><br>## Build last k_frame images for predict<br>def get_last_k_frames(self, state):<br>        frames = np.empty((self.k_frames, self.frame_height, self.frame_width))<br><br>        for i in range(0, self.k_frames):<br>            _, _, _, n_s, _ = self.memory[len(self.memory)-(self.k_frames-i)]<br>            frames[i] = n_s<br>            <br>        return np.transpose(frames, axes=(1,2,0))</pre><p>This temporal layer that we add to our images, which will feed the Convolutional Neural Network, plays a crucial role in our topic: Atari Games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*uHMyea_Ozcj5q3NC" /></figure><p>Consider this image of a baseball. Imagine you’re in a game, with your advanced smartphone, and you manage to capture a perfectly sharp photo of the baseball at a specific point in its trajectory. However, even with this high-quality image, without the presence of shadows or other motion indicators, it would be challenging to determine the ball’s direction based solely on that single image. It’s precisely this kind of challenge that our intelligent agent will face. In the game we’re analyzing — Pong — we deal with moving objects, and we need to devise an effective method to identify and interpret these movements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*JtVKvnlo-mi1n2Br.png" /></figure><p>A strategy to allow our agent to detect the movement of objects in an image is the use of a few or several sequential images. Following the reasoning described earlier, imagine that instead of a single photo, you’ve captured four consecutive images in an extremely short time interval. The effect generated by combining these four images would be something similar to the figure above. In other words, by considering a temporal sequence of frames, you’d be able to infer the ball’s direction of movement. The same principle applies to our intelligent agent: by taking into account more than one image in its learning process, it will be able to understand the direction of the game objects’ movements, which will assist it in making decisions and planning plays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YpeJ4ltQ8FLMo3Hu.gif" /></figure><p><em>As an addition to our knowledge, it’s worth noting that by incorporating the dimension of time into a two-dimensional image, we are actually converting it into a video. This is the underlying logic of a video camera operation, which simply captures multiple images in a short span of time.</em></p><h4>3.5 How the agent should choose its next action.</h4><pre>def act(self, state):<br>    if np.random.rand() &lt;= self.exploration_rate or len(self.memory) &lt; self.k_frames+1:<br>        return random.randrange(self.action_size)<br>    <br>    k_frames_state = self.get_last_k_frames(state)<br>    k_frames_state = np.expand_dims(k_frames_state, axis=0)<br>    act_values = self.brain.predict(k_frames_state, verbose=0)<br>    return np.argmax(act_values[0])</pre><p>We are now delving into the heart of the reinforcement learning process: training the agent. Here’s how it works:</p><p>Exploration and Exploitation (Exploration and Explotation) play a central role in this stage. Let’s further clarify these two terms:</p><p>Exploration: The ability to try out new plays, those the agent hasn’t yet experienced or known about. This technique is crucial for the agent to discover new play combinations. Technically speaking, exploration involves a random action.</p><p>Exploitation: The ability to make moves based on what the agent already knows.</p><p>Both techniques are essential for the agent’s learning process. Exploration allows the agent to encounter states it wouldn’t typically experience on its own, while Exploitation enables the agent to keep using moves that historically yield higher rewards.</p><p>Many articles on reinforcement learning cite the “Multi-Armed Bandit” dilemma. This problem, from probability theory and decision-making, seeks to optimize the selection between various options, each with uncertain rewards. The name derives from an analogy with a casino player facing multiple slot machines (or “one-armed bandits”).</p><p>In this challenge, at each round, an agent has to choose one out of several options (or “arms”). Each choice yields a reward determined by an unknown probability distribution. The goal is to maximize the total reward over many rounds.</p><p>The agent must strike a balance between “exploration” (trying out different options to gain insights into potential rewards) and “exploitation” (selecting the option believed, based on current information, to be the most advantageous).</p><p>In the context of our specific problem, we need to manage exploration and exploitation judiciously. To achieve this, we plan to set a variable for the agent that will determine the likelihood of it opting for exploration over exploitation. We call this variable “exploration_rate.” As training progresses, this variable’s value will gradually decrease until it reaches a predetermined minimum set in the agent’s parameters.</p><p>In summary, the agent starts with a 100% probability of exploring the environment. As training sessions progress, this exploration rate is slowly reduced until it reaches a set minimum in the agent’s parameters. Over time, the agent will operate more on its accumulated knowledge (exploitation) rather than randomly exploring.</p><h4>3.7 Reward-Based Feedback and Model Adjustments</h4><pre>def replay(self, sample_batch_size):<br>    <br>    ## Check if &quot;memory&quot; has more record then &quot;sample_batch_size&quot;<br>    if len(self.memory) &lt; sample_batch_size:<br>        return<br>    <br>    ## Get formatted records from train and predict.<br>    state, action, reward, next_state, done = self.pack_K_frames(sample_batch_size)<br>    <br>    ## Predict<br>    predicted = self.brain_target.predict(next_state, verbose=0) #Previsão proximo estado.<br>    target_f = self.brain.predict(state, verbose=0) #Previsão estado atual.<br><br>    ## Calculate targets<br>    targets = reward + self.gamma * np.amax(predicted, axis=1) * (1 - done)<br>    target_f[np.arange(sample_batch_size), action] = targets<br><br>    ## Train<br>    history = self.brain.fit(state, target_f, batch_size=sample_batch_size, epochs=1, verbose=0)<br>        <br>    ## Update exploration rate<br>    if self.exploration_rate &gt; self.exploration_min:<br>        self.exploration_rate -= self.exploration_decay<br>    <br>    return history, self.exploration_rate</pre><p>This function is the cherry on top of our project, as this is where we execute reinforcement learning. For this reason, I will break down each section of this function to explain bit by bit.</p><pre>state, action, reward, next_state, done = self.pack_K_frames(sample_batch_size)</pre><p>In this section, we are using the “pack_K_frames” function, which has already been explained earlier. This function returns the batch of the size we request. In our case, we will use a batch of 32.</p><pre>predicted = self.brain_target.predict(next_state, verbose=0) <br>target_f = self.brain.predict(state, verbose=0)</pre><p>In this segment, it’s highlighted that we conduct two predictions using the two previously mentioned convolutional neural networks. The first line corresponds to the prediction made by the more stable network, while in the second line, the prediction is carried out with the less stable network.</p><pre>targets = reward + (self.gamma * np.amax(predicted, axis=1) * (1 - done))<br>target_f[np.arange(sample_batch_size), action] = targets</pre><p>This section of the code is essential for understanding reinforcement learning, specifically in the context of Q-learning. The core idea is to update the Q-values for a specific state and action based on the immediate reward and the estimate of the future Q-value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1xxjJAQxvMLZSKFp.png" /></figure><p>This is the Bellman Equation for Q-Learning, where:</p><ul><li>s is the current state.</li><li>a is the action taken in state s.</li><li>r is the immediate reward after taking action a in state s.</li><li>γ is the discount factor that determines the importance of future rewards relative to immediate rewards.</li><li>maxa′​Q(s′,a′) is the maximum Q value for the next state s′ over all possible actions a′.</li></ul><p><strong>Done Condition</strong>: The factor (1 - done) ensures that if the episode ends after taking the action (i.e., if we reach a terminal state), then the future reward will be 0 since there are no more actions to be taken.</p><h4>Explanation Related to the Code:</h4><pre>targets = reward + (self.gamma * np.amax(predicted, axis=1) * (1 - done))</pre><ul><li>reward: Is the reward obtained after executing an action in a specific state.</li><li>self.gamma: Represents the discount factor.</li><li>np.amax(predicted, axis=1): This retrieves the maximum Q value among all possible actions in the next state s′. The np.amax function returns the maximum along the specified axis, which, in this case, is the action axis.</li><li>(1 - done): If ‘done’ is true (i.e., the episode has ended), then the product will be 0. Otherwise, it will be 1.</li></ul><pre>target_f[np.arange(sample_batch_size), action] = targets</pre><ul><li>Here, we are updating the Q values of the neural network. target_f is the matrix that contains the Q values we want to predict.</li><li>np.arange(sample_batch_size): Creates an array of indices for each sample in the batch.</li><li>action: Represents the actions taken in each batch sample.</li><li>Together, target_f[np.arange(sample_batch_size), action] selects the specific Q values of the action taken in each sample.</li></ul><p>The line, therefore, updates these specific Q values to the newly computed values in ‘targets’.</p><pre>self.brain.fit(state, target_f, batch_size=sample_batch_size, epochs=1, verbose=0)</pre><p>Next, we train the convolutional neural network, which is the more unstable one, using the ‘target_f’ variable. This variable stores the values derived from the Bellman Equation for Q-Learning.</p><pre>if self.exploration_rate &gt; self.exploration_min:<br>  self.exploration_rate -= self.exploration_decay</pre><p>Lastly, we decrease the exploration rate, so with each training, the agent is more inclined to make decisions based on what it has already learned, rather than choosing random actions.</p><pre>def update_target_model(self, current_frame):<br>  if (current_frame % self.freq_update_nn == 0 and TRAIN and current_frame &gt; self.initial_start_size):<br>      self.brain_target.set_weights(self.brain.get_weights())</pre><p>The next function of the agent is responsible for updating the weights of the convolutional neural network. In this implementation, the update is carried out every “self.freq_update_nn” frames.</p><p>Congratulations on making it this far! With all the knowledge we’ve shared, you are now ready to dive into the world of Reinforcement Learning! 🚀🤖🎉 The complete code for you to use or even base your projects on is available on my GitHub.</p><p><a href="https://github.com/MateusDeFreitasRosa/RLGameAIEye">https://github.com/MateusDeFreitasRosa/RLGameAIEye</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*IxgABxK-g-IqSr4M.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20c84df1eaab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desenvolva Seu Primeiro Algoritmo de Aprendizado por Reforço para Jogos Eletrônicos (do zero!!!).]]></title>
            <link>https://medium.com/@mateusfreitasrosa/desenvolva-seu-primeiro-algoritmo-de-aprendizado-por-refor%C3%A7o-para-jogos-eletr%C3%B4nicos-do-zero-495243ebb2d6?source=rss-82c78f2a5a97------2</link>
            <guid isPermaLink="false">https://medium.com/p/495243ebb2d6</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[aprendizado-por-reforço]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[visão-computacional]]></category>
            <category><![CDATA[aprendizado-de-maquina]]></category>
            <dc:creator><![CDATA[Mateusfreitasrosa]]></dc:creator>
            <pubDate>Sat, 12 Aug 2023 18:49:46 GMT</pubDate>
            <atom:updated>2023-08-12T18:49:46.566Z</atom:updated>
            <content:encoded><![CDATA[<p>Olá! Meu nome é Mateus de Freitas Rosa. Sou cientista de dados desde fevereiro de 2021 e me graduei em Sistemas de Informação em agosto de 2022. No meu Trabalho de Conclusão de Curso, desenvolvi um modelo de Aprendizado por Reforço voltado para jogos eletrônicos. Esse projeto foi o pontapé inicial na minha jornada com essa técnica de aprendizado de máquina. Estou entusiasmado em compartilhar esse conhecimento com você!</p><p>Para iniciarmos nossa jornada de aprendizado e codificação, é essencial que primeiro preparemos nosso ambiente de desenvolvimento. Isso garante que todos estejamos trabalhando de maneira sincronizada e obtenhamos resultados similares ao seguir as mesmas instruções.</p><p>Neste caso, vou utilizar a plataforma Anaconda para configurar nosso ambiente de desenvolvimento. O Anaconda é uma distribuição gratuita e de código aberto das linguagens de programação Python e R, e é amplamente utilizado para ciência de dados e aprendizado de máquina. Além disso, oferece um sistema conveniente para o gerenciamento de pacotes e ambientes virtuais, que nos permite isolar diferentes projetos e suas respectivas dependências.</p><p>Se você quiser acompanhar e replicar meus passos, sugiro que instale o Anaconda em sua máquina. Isso garantirá que nossos ambientes de trabalho sejam idênticos e que nosso código seja executado da mesma maneira.</p><p>Para baixar e instalar a plataforma Anaconda, você pode acessar o site oficial: <a href="https://www.anaconda.com/">https://www.anaconda.com/</a>. Lá você encontrará as versões mais recentes da distribuição Anaconda para diferentes sistemas operacionais. Escolha a versão que melhor se adequa ao seu sistema operacional, faça o download e siga as instruções para a instalação.</p><p>A partir deste ponto, estou assumindo que você já instalou com sucesso a plataforma Anaconda em sua máquina. Se encontrou algum problema durante a instalação, há muitos recursos online, incluindo a documentação oficial do Anaconda, que podem ajudá-lo a solucionar quaisquer problemas que possa ter encontrado.</p><p>Com a plataforma Anaconda instalada, estamos prontos para começar a configurar nosso ambiente de desenvolvimento e mergulhar no mundo do Aprendizado de Máquina Por Reforço!</p><h3><strong>1. Configuração do ambiente</strong></h3><p>Neste código, optamos por usar versões mais antigas do Python, assim como dos pacotes Tensorflow, Keras, entre outros. A razão para isso é que queremos especificamente utilizar a versão 1 do Tensorflow. Em minha configuração e testes pessoais, percebi que o TensorFlow 1 tem uma propensão a priorizar o uso da CPU em vez da GPU. Surpreendentemente, em minha máquina, essa preferência pela CPU resultou em um desempenho notavelmente superior, tornando os processos de treinamento mais eficientes. É importante destacar que essa observação é baseada em minha experiência pessoal, e pode variar dependendo da configuração e especificações de outras máquinas.</p><p>Portanto, este documento irá te ensinar a desenvolver um agente inteligente utilizando aprendizado de máquina por reforço e visão computacional com o TensorFlow 1. Se você já tem familiaridade com o TensorFlow 2 e se sente confortável em utilizá-lo, fica a seu critério adaptar e aplicar configurações diferentes das minhas.</p><h4>1.1 Criação do ambiente virtual com o Anaconda</h4><p>Para criar um ambiente virtual no Anaconda, você tem a opção de usar a interface gráfica ou a linha de comando. Para usar a linha de comando, abra o “Anaconda Prompt”.</p><p>Execute o comando abaixo para criar um novo ambiente virtual:</p><pre>conda create -n reinforcementlearning python=3.6</pre><p>Este comando faz o seguinte:</p><ul><li>conda create: este é o comando que pede ao Anaconda para criar um novo ambiente virtual.</li><li>-n reinforcementlearning: esta parte nomeia o ambiente como &quot;reinforcementlearning&quot;.</li><li>python=3.6: isso especifica que queremos usar a versão 3.6 do Python neste ambiente.</li></ul><p>Resumindo, o comando acima está instruindo o Anaconda a criar um novo ambiente virtual chamado “reinforcementlearning”, com a versão 3.6 do Python instalada.</p><h4>1.2 Acessar o ambiente anteriormente criado</h4><p>Depois de criar o ambiente virtual no Anaconda, precisamos “ativá-lo” para poder utilizá-lo. Isso é feito entrando no ambiente virtual, o que podemos fazer através da linha de comando. O comando para ativar o ambiente é:</p><pre>conda activate reinforcementlearning</pre><p>Este comando tem as seguintes partes:</p><ul><li>conda activate: Este é o comando que solicita ao Anaconda para ativar um ambiente específico.</li><li>reinforcementlearning: Este é o nome do ambiente que criamos anteriormente e queremos ativar agora.</li></ul><p>Em resumo, ao executar o comando acima, você estará dizendo ao Anaconda para entrar no ambiente virtual chamado “reinforcementlearning”, tornando-o o ambiente ativo para sua sessão atual. Isso significa que qualquer pacote que você instalar ou qualquer código que você execute será feito dentro deste ambiente, isolado do restante do sistema.</p><h4>1.3 Instalação de pacotes necessários.</h4><p>Para instalar as bibliotecas necessárias para o nosso projeto, continuaremos a utilizar o Anaconda Prompt, que já temos aberto desde os passos anteriores.</p><p>Aqui está a lista dos pacotes essenciais que precisamos para o funcionamento do nosso projeto:</p><pre>conda install -c conda-forge gym<br>pip install tensorflow==1.13.1<br>pip install keras==2.2.4<br>pip install opencv-python<br>pip install numpy<br>pip install pandas<br>pip install matplotlib<br>pip install imageio                <br>conda install -c conda-forge gym-atari<br>pip install imageio-ffmpeg                           <br>pip install jupyterlab</pre><p>Cada linha deste bloco de código é um comando que instala um pacote específico. Para evitar possíveis erros, é recomendado que você execute cada linha individualmente, aguardando a instalação completa do pacote antes de prosseguir para o próximo.</p><p>Esses comandos garantem que todas as bibliotecas de que precisamos, como TensorFlow para a criação de redes neurais convolucionais, Gym para a simulação do ambiente do jogo, e outras bibliotecas úteis para manipulação de dados e gráficos, estejam instaladas e prontas para uso em nosso ambiente “reinforcementlearning”.</p><p>Excelente! Agora temos um ambiente virtual Anaconda completamente configurado e pronto para mergulharmos de cabeça na programação!</p><h3>2. Introdução ao Desenvolvimento</h3><p>Gostaria de ressaltar que o aprendizado de máquina por reforço é uma temática que exige algum conhecimento prévio para quem deseja se aprofundar, ou mesmo para a plena compreensão do projeto que estamos empreendendo. Assim, este artigo assume que você tenha alguma familiaridade com Aprendizado de Máquina, Redes Neurais Artificiais e Convolucionais, e habilidades de programação Python de nível intermediário, Álgebra Linear, entre outros conhecimentos.</p><p>No entanto, caso você sinta que está faltando algum desses pré-requisitos, não se preocupe. Este artigo foi planejado de tal forma que, mesmo sem dominar todos esses conceitos, você ainda poderá seguir a jornada e alcançar o objetivo final: desenvolver um agente inteligente que joga jogos de Atari. O conteúdo foi elaborado de forma incremental, facilitando o entendimento e a aplicação dos conceitos, mesmo que estes sejam novos para você.</p><p>Além disso, estarei à disposição para esclarecer qualquer dúvida que possa surgir ao longo deste processo, tornando este um ambiente propício para o aprendizado e a prática. Portanto, sinta-se encorajado a embarcar conosco nesta jornada!</p><h4>2.1 O Que é o Aprendizado de Máquina por Reforço?</h4><p>O aprendizado de máquina por reforço é um subcampo da inteligência artificial que utiliza a ideia de recompensa e punição para orientar um agente a aprender as melhores ações a serem tomadas em determinadas situações.</p><p>Neste tipo de aprendizado, o agente (um programa de computador, um robô ou outro sistema autônomo) interage com um ambiente e, a cada ação que realiza, recebe um feedback. Este feedback pode ser positivo (uma recompensa) se a ação tomada for benéfica, ou negativo (uma punição) se for prejudicial. O agente, então, utiliza esse feedback para aprender quais ações são as melhores a tomar em cada situação, de forma a maximizar a soma total de recompensas ao longo do tempo.</p><p>Essencialmente, o aprendizado por reforço é um processo de otimização: o agente procura aprender a melhor política de ação — uma espécie de “mapa de regras” que diz qual ação tomar em cada situação — para obter a maior recompensa possível. Este tipo de aprendizado é particularmente útil em situações onde o agente deve aprender a tomar decisões por conta própria, baseando-se na experiência adquirida através de tentativa e erro.</p><p>Nesse contexto, os jogos eletrônicos emergem como excelentes campos de teste para o aprendizado por reforço. Eles oferecem ambientes complexos e desafiadores que permitem ao agente explorar, errar, e acertar, até encontrar as soluções mais eficientes. Cada partida jogada se torna uma oportunidade para aprender e aprimorar estratégias, fazendo dos jogos uma plataforma ideal para a aplicação do aprendizado por reforço.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*ssQY8L5byRUftoob.png" /></figure><p>A imagem acima fornece uma representação visual do funcionamento do aprendizado de máquina por reforço. Comece imaginando que nosso agente se encontre em uma posição inicial, que chamamos de Estado (St). A partir deste ponto, o agente executa uma ação (At) em um momento específico t, interagindo com o ambiente. Em resposta à ação do agente, o ambiente não só oferece um feedback na forma de uma recompensa (Rt+1), como também revela o próximo estado (St+1). Esse ciclo, ação-recompensa-estado, se repete, alimentando o processo de aprendizado contínuo do agente.</p><h3>3. Desenvolvimento do Agente Inteligente</h3><p>Já conversamos bastante, não é mesmo? Hehehe. Agora, que tal sairmos do papo e partirmos para a ação? Neste próximo passo, vou usar o código que desenvolvi durante a minha pesquisa de TCC, só que com alguns ajustes para facilitar a compreensão: <a href="https://repositorio.ufu.br/handle/123456789/36265">https://repositorio.ufu.br/handle/123456789/36265</a>.</p><p>Ei, percebeu que deixamos alguns conceitos do aprendizado por reforço sem definição? Acertou! Mas, tenho um plano: que tal se eu for introduzindo esses conceitos ao longo da construção do nosso agente? Assim, você poderá ver tudo na prática e, com certeza, ficará mais fácil de compreender. Então, preparado(a) para continuarmos essa aventura? Não se preocupe, nossa conversa ainda está longe do fim!</p><h4>3.1 Importação das bibliotecas que iremos utilizar</h4><pre>import gym<br>import cv2<br>import numpy as np<br>from collections import deque<br>import imageio<br>import os<br>import random<br>import matplotlib.pyplot as plt<br>import pickle<br>import time<br>import pandas as pd<br>import itertools<br><br>import tensorflow as tf<br>from keras import backend as K<br><br>from keras.models import Sequential<br>from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten<br>from keras.optimizers import Adam</pre><p>Esses são todos os pacotes que vamos precisar neste projeto. Conforme avançarmos no desenvolvimento, vou explicando a função de cada um deles.</p><h4>3.2 Definição do objeto Agente e de seus parâmetros</h4><pre>class Agent(): <br>    def __init__(self, state_size, action_size):<br>        self.state_size                 =       state_size<br>        self.action_size                =       action_size<br>        self.memory                     =       deque(maxlen=LEN_MEMORY_QUEUE)<br>        self.min_learning_rate          =       .0008<br>        self.max_learning_rate          =       .01<br>        self.epochs_interval_lr         =       150<br>        self.learning_rate_decay        =       (self.max_learning_rate - self.min_learning_rate) / self.epochs_interval_lr<br>        self.gamma                      =       .99<br>        self.exploration_rate           =       1<br>        self.exploration_min            =       .07<br>        self.exploration_decay          =       1 / 100000 # A variável irá se atualizar.<br>        self.k_frames                   =       4<br>        self.frame_height               =       self.state_size[0]<br>        self.frame_width                =       self.state_size[1]<br>        self.brain                      =       self._build_model()<br>        self.brain_target               =       self._build_model()<br>        self.freq_update_nn             =       1000<br>        self.initial_start_size         =       5000</pre><ul><li><strong>state_size</strong>: Esta variável representa as dimensões do estado. No nosso caso, como o estado é uma imagem, e consideramos uma matriz bidimensional, o state_size representa o formato dessa matriz.</li><li><strong>action_size</strong>: Refere-se ao número de ações possíveis que o agente pode executar. Dependendo do jogo, esse número pode variar. No nosso caso, com o Pong-v0, temos apenas três movimentos possíveis para a raquete: subir, descer ou permanecer parada.</li><li><strong>memory</strong>: É onde guardamos a memória do agente, que inclui todos os estados, estados futuros, recompensas e ações.</li><li><strong>min_learning_rate</strong>, <strong>max_learning_rate</strong>, <strong>epochs_interval_lr </strong>e <strong>learning_rate_decay</strong>: <br>No modelo que estou apresentando, observei que ajustar a taxa de aprendizado do agente permite que ele evolua mais rapidamente. Definimos uma taxa de aprendizado máxima e mínima, um intervalo de épocas para oscilar entre essas taxas e o learning_rate_decay que calcula quanto precisamos reduzir a taxa máxima para alcançar a taxa mínima dentro do intervalo de épocas.</li><li><strong>gamma</strong>:<br>Essa constante é usada no cálculo do aprendizado por reforço.</li><li><strong>exploration_rate</strong>: <br>Indica a taxa de exploração (episilion) inicial.</li><li><strong>exploration_min</strong>: <br>Esta é a taxa de exploração mínima ou limite.</li><li><strong>exploration_decay</strong>: <br>Representa o declínio da taxa de exploração a cada treino.</li><li><strong>k_frames<br></strong>Este parâmetro representa o número de imagens concatenadas que serão usadas para alimentar a Rede Neural Convolucional. Quando este valor é maior que 1, transforma-se a imagem de entrada para a Rede Neural Convolucional em uma estrutura tridimensional, em que a terceira dimensão introduz um elemento temporal à imagem.</li><li><strong>frame_height</strong> e <strong>frame_width</strong>: <br>São simplesmente a altura e a largura da variável state_size.</li><li><strong>brain</strong> e <strong>brain_target</strong>: <br>Aqui temos um ponto crucial. Por que criamos duas redes neurais convolucionais para um único agente? O aprendizado por reforço envolve um agente realizando ações para encontrar combinações que maximizem sua recompensa. Para isso, o agente precisará treinar sua rede neural a cada K frames. Porém, se fizermos isso com uma única rede neural, o aprendizado se torna instável, pois estaríamos alterando o estado da rede neural constantemente. A solução para este problema é utilizar duas redes neurais. A segunda rede neural (mais estável — brain_target) é usada apenas para prever as próximas ações do agente e atualizamos seus pesos com os da primeira rede neural (a mais instável — brain) a cada “freq_update_nn” treinos.</li><li><strong>freq_update_nn</strong>: <br>Indica a quantidade de treinos entre cada atualização da segunda rede neural, a brain_target.</li><li><strong>initial_start_size</strong>:<br>Representa a quantidade mínima de frames que precisamos armazenar em memória antes de começar a treinar o modelo.</li></ul><h4>3.3 Criando a Arquitetura da Rede Neural Convolucional</h4><pre>def _build_model(self):<br>        # Neural Net for Deep-Q learning Model<br>        model = Sequential()<br>        <br>        ## Build Convolutional NetWork<br>        model.add(Conv2D(32, (8,8), strides=4, input_shape=(self.state_size[0], self.state_size[1], self.k_frames), activation=&#39;relu&#39;, padding=&#39;valid&#39;))<br>        model.add(Conv2D(64, (4,4), strides=2, activation=&#39;relu&#39;, padding=&#39;valid&#39;))<br>        model.add(Conv2D(64, (3,3), strides=1, activation=&#39;relu&#39;, padding=&#39;valid&#39;))<br><br>        model.add(Flatten())<br>        ## Build Neural Network<br>        model.add(Dense(512, activation=&#39;relu&#39;))          <br>        model.add(Dense(256, activation=&#39;relu&#39;, kernel_initializer=&#39;glorot_uniform&#39;))<br>        model.add(Dense(64, activation=&#39;relu&#39;, kernel_initializer=&#39;glorot_uniform&#39;))<br>            <br>        model.add(Dense(self.action_size, activation=&#39;linear&#39;))<br>        model.compile(loss=huber_loss_mean, optimizer=Adam(lr=self.max_learning_rate))<br>            <br>        model.summary()<br><br>        return model</pre><p>Esta arquitetura tem suas raízes no artigo “Human-level control through deep reinforcement learning” de autoria de Minh e seus colaboradores (Mnih, Volodymyr, et al., nature 518.7540, 2015: 529–533). Devido à complexidade do tópico, não entrarei em detalhes sobre cada parâmetro da arquitetura neste artigo. Recomendo fortemente que você explore cada método apresentado na documentação do Keras para uma compreensão mais aprofundada. Em termos gerais, criamos uma arquitetura convolucional para receber a imagem pré-processada. Em seguida, essa saída é introduzida em uma Rede Neural Artifical que fará o processamento subsequente.</p><h4>3.4 Empilhamento de “k-frames” imagens</h4><pre>## Build batch of images for train<br>def pack_K_frames(self, sample_batch_size):<br>        if len(self.memory) &lt; self.k_frames+2:<br>            return<br>        <br>        state = np.empty((sample_batch_size, self.k_frames, self.frame_height, self.frame_width))<br>        action = np.empty(sample_batch_size, dtype=np.uint8)<br>        reward = np.empty(sample_batch_size, dtype=np.float32)<br>        next_state = np.empty((sample_batch_size, self.k_frames, self.frame_height, self.frame_width))<br>        done = np.empty(sample_batch_size, dtype=np.bool_)<br><br>        for k in range(sample_batch_size):<br>            index = random.randint(0, len(self.memory)-self.k_frames-2)<br>            <br>            for i, idx_memory in enumerate(range(index, index+self.k_frames)):<br>                s, a, r, n_s, d = self.memory[idx_memory]<br>            <br>                state[k][i] = s<br>                next_state[k][i] = n_s<br>                <br>            done[k] = d<br>            action[k] = a<br>            reward[k] = r<br>              <br>        #State = (32,4,84,84)  -&gt; State Transpose = (32,84,84,4) <br>        return np.transpose(state, axes=(0,2,3,1)), action, reward, np.transpose(next_state, axes=(0,2,3,1)), done<br><br>## Build last k_frame images for predict<br>def get_last_k_frames(self, state):<br>        frames = np.empty((self.k_frames, self.frame_height, self.frame_width))<br><br>        for i in range(0, self.k_frames):<br>            _, _, _, n_s, _ = self.memory[len(self.memory)-(self.k_frames-i)]<br>            frames[i] = n_s<br>            <br>        return np.transpose(frames, axes=(1,2,0))</pre><p>Esta camada temporal que adicionamos em nossas imagens que irão alimentar a Rede Neural Convolucional, tem um papel crucial para nosso tema: Jogos de Atari.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Dov8jC_Du8rc2hR8" /></figure><p>Consideremos esta imagem de uma bola de baseball. Imagine que você esteja em um jogo, com seu smartphone avançado, e consegue capturar uma foto perfeitamente nítida da bola de baseball em um ponto específico de sua trajetória. Contudo, mesmo com essa imagem de alta qualidade, sem a presença de sombras ou outros indicativos de movimento, seria desafiador determinar a direção da bola baseando-se somente nessa única imagem. É precisamente esse tipo de desafio que nosso agente inteligente enfrentará. No jogo que estamos analisando — o Pong — lidamos com objetos em movimento, e precisamos elaborar um método eficaz para identificar e interpretar esses movimentos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sy2ndJXCPJmRxQPXtOxdFw.png" /></figure><p>Uma estratégia para permitir que nosso agente detecte o movimento dos objetos em uma imagem é o uso de algumas ou várias imagens sequenciais. Seguindo o raciocínio descrito anteriormente, imagine que, em vez de uma única foto, você tenha capturado quatro imagens consecutivas em um intervalo de tempo extremamente curto. O efeito gerado ao combinar essas quatro imagens seria algo parecido com a figura acima. Em outras palavras, ao considerar uma sequência temporal de quadros, você seria capaz de inferir a direção do movimento da bola. O mesmo princípio se aplica ao nosso agente inteligente: ao levar em conta mais de uma imagem em seu processo de aprendizado, ele será capaz de entender a direção dos movimentos dos objetos no jogo, o que o auxiliará na tomada de decisões e planejamento de jogadas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdI4mVkQnhd6TKLWfsWSiQ.gif" /></figure><p><em>Como um acréscimo ao nosso conhecimento, é interessante salientar que, ao incorporar a dimensão do tempo a uma imagem de duas dimensões, estamos, na verdade, convertendo-a em um vídeo. Esta é a lógica subjacente à operação de uma câmera de vídeo, que nada mais faz do que capturar várias imagens em um breve espaço de tempo.</em></p><h4>3.5 Como o agente deve escolher sua próxima ação.</h4><pre>def act(self, state):<br>    if np.random.rand() &lt;= self.exploration_rate or len(self.memory) &lt; self.k_frames+1:<br>        return random.randrange(self.action_size)<br>    <br>    k_frames_state = self.get_last_k_frames(state)<br>    k_frames_state = np.expand_dims(k_frames_state, axis=0)<br>    act_values = self.brain.predict(k_frames_state, verbose=0)<br>    return np.argmax(act_values[0])</pre><p>Aqui entramos em uma discussão sobre Exploração e Explotação (Exploration and Explotation). A definição para esses dois termos são:</p><p>Exploração: A capacidade de explorar novas jogadas, essas que o agente ainda não experimentou ou conheceu. Essa técnica é importante para que o agente possa encontrar novas combinações de jogadas. Em termos técnicos, a exploração é uma ação aleatória.</p><p>Explotação: A capacidade de realizar jogadas baseadas no que já é conhecido pelo agente.</p><p>Ambas as técnicas são importante para o aprendizado do agente, pois a Exploração permite que o agente conheça estados que ele por si não iria experimentar, e a Explotação permite que o agente continue utilizando as jogadas que historicamente ele sabe que irá ter mais ganhos de recompensas.</p><p>Em muitos artigos sobre o aprendizado de máquina por reforço é citado o dilema do “Multi-Armed Bandit”. O problema do “Multi-Armed Bandit” é um desafio da teoria das probabilidades e das decisões que visa otimizar a seleção entre várias opções com diferentes recompensas incertas. O nome vem de uma analogia com um jogador de cassino enfrentando várias máquinas caça-níqueis (ou “one-armed bandits”).</p><p>Nesse problema, um agente deve escolher, em cada rodada, uma entre várias opções (ou “braços”). Cada opção fornece uma recompensa determinada por uma distribuição de probabilidade desconhecida. O objetivo é maximizar a recompensa total ao longo de várias rodadas.</p><p>O agente precisa balancear a “exploração” (experimentar diferentes opções para ganhar insights sobre as recompensas potenciais) e a “explotação” (escolher a opção que ele acredita, com base em informações atuais, ser a mais vantajosa).</p><p>No contexto específico de nosso problema, precisamos administrar de maneira equilibrada a exploração e a explotação. Para isso, planejamos definir uma variável para o agente que determinará a probabilidade de ele optar pela exploração em vez da explotação. Nomeamos essa variável como “exploration_rate”. Durante os treinamentos, o valor dessa variável irá gradualmente diminuir, até que atinja um valor mínimo previamente estabelecido nos parâmetros do agente.</p><p>Em resumo, o agente inicia com 100% de probabilidade de explorar o ambiente. À medida que os treinamentos progridem, essa taxa de exploração é gradualmente reduzida até chegar a um limite mínimo definido nos parâmetros do agente. Com o passar do tempo, o agente começará a operar mais com base em seus conhecimentos acumulados (explotação), em vez de explorar aleatoriamente.</p><h4>3.6 Treinamento do modelo com aprendizado por Reforço</h4><pre>def replay(self, sample_batch_size):<br>    <br>    ## Check if &quot;memory&quot; has more record then &quot;sample_batch_size&quot;<br>    if len(self.memory) &lt; sample_batch_size:<br>        return<br>    <br>    ## Get formatted records from train and predict.<br>    state, action, reward, next_state, done = self.pack_K_frames(sample_batch_size)<br>    <br>    ## Predict<br>    predicted = self.brain_target.predict(next_state, verbose=0) #Previsão proximo estado.<br>    target_f = self.brain.predict(state, verbose=0) #Previsão estado atual.<br><br>    ## Calculate targets<br>    targets = reward + self.gamma * np.amax(predicted, axis=1) * (1 - done)<br>    target_f[np.arange(sample_batch_size), action] = targets<br><br>    ## Train<br>    history = self.brain.fit(state, target_f, batch_size=sample_batch_size, epochs=1, verbose=0)<br>        <br>    ## Update exploration rate<br>    if self.exploration_rate &gt; self.exploration_min:<br>        self.exploration_rate -= self.exploration_decay<br>    <br>    return history, self.exploration_rate</pre><p>Esta função é a cereja do bolo do nosso projeto, pois é aqui que executamos aprendizado por reforço. Por este motivo, vou recortar cada trecho desta função para explicar trecho por trecho.</p><pre>state, action, reward, next_state, done = self.pack_K_frames(sample_batch_size)</pre><p>Neste trecho, estamos utilizando a função “pack_K_frames” que já foi explicada anteriormente. Essa função nos retorna o batch do tamanho que solicitarmos. No nosso caso vamos utilizar um batch de 32.</p><pre>predicted = self.brain_target.predict(next_state, verbose=0) <br>target_f = self.brain.predict(state, verbose=0)</pre><p>Neste segmento, destaca-se que conduzimos duas predições usando as duas redes neurais convolucionais previamente mencionadas. A primeira linha corresponde à predição feita pela rede mais estável, enquanto na segunda linha, a predição é realizada com a rede mais instável.</p><pre>targets = reward + (self.gamma * np.amax(predicted, axis=1) * (1 - done))<br>target_f[np.arange(sample_batch_size), action] = targets</pre><p>Esse trecho do código é fundamental para entender o aprendizado por reforço, especificamente no contexto de Q-learning. A ideia central é atualizar os valores Q para um estado e ação específicos com base na recompensa imediata e a estimativa do valor Q futuro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gt40OiJa1ol8XbwG.png" /><figcaption>Equação de Bellman para Q-Learning</figcaption></figure><p>Está é a Equação de Bellman para Q-Learning, onde:</p><ul><li><em>s</em> é o estado atual.</li><li><em>a</em> é a ação tomada no estado <em>s</em>.</li><li><em>r</em> é a recompensa imediata após tomar a ação <em>a</em> no estado <em>s</em>.</li><li><em>γ</em> é o fator de desconto que determina a importância das recompensas futuras em relação às recompensas imediatas.</li><li>max<em>a</em>′​<em>Q</em>(<em>s</em>′,<em>a</em>′) é o valor Q máximo para o próximo estado <em>s</em>′ sobre todas as ações possíveis <em>a</em>′.</li></ul><p>Condição <strong><em>done</em></strong>: O fator (1 - done) garante que se o episódio terminar depois de tomar a ação (ou seja, se chegarmos a um estado terminal), então a recompensa futura será 0, uma vez que não há mais ações a serem tomadas.</p><h4>Explicação Relacionada ao Código:</h4><pre>targets = reward + (self.gamma * np.amax(predicted, axis=1) * (1 - done))</pre><ul><li>reward: É a recompensa obtida após executar uma ação em um estado específico.</li><li>self.gamma: Representa o fator de desconto.</li><li>np.amax(predicted, axis=1): Isso pega o valor Q máximo entre todas as ações possíveis no próximo estado <em>s</em>′. A função np.amax retorna o máximo ao longo do eixo especificado, que, neste caso, é o eixo das ações.</li><li>(1 - done): Se &#39;done&#39; for verdadeiro (ou seja, o episódio terminou), então o produto será 0. Caso contrário, será 1.</li></ul><pre>target_f[np.arange(sample_batch_size), action] = targets</pre><ul><li>Aqui, estamos atualizando os valores Q da rede neural. target_f é a matriz que contém os valores Q que queremos prever.</li><li>np.arange(sample_batch_size): Cria um array de índices para cada amostra no batch.</li><li>action: Representa as ações tomadas em cada amostra do batch.</li><li>Juntos, target_f[np.arange(sample_batch_size), action] seleciona os valores Q específicos da ação tomada em cada amostra.</li></ul><p>A linha, portanto, atualiza esses valores Q específicos para os valores recém-calculados em ‘targets’.</p><pre>self.brain.fit(state, target_f, batch_size=sample_batch_size, epochs=1, verbose=0)</pre><p>A seguir, treinamos a rede neural convolucional a qual é a mais instável usando a variável ‘target_f’. Essa variável armazena os valores derivados da Equação de Bellman para Q-Learning.</p><pre>if self.exploration_rate &gt; self.exploration_min:<br>  self.exploration_rate -= self.exploration_decay</pre><p>Por fim, diminuímos a taxa de exploração, de modo que, a cada treinamento, o agente tende a tomar decisões baseadas no que já aprendeu, em vez de escolher ações aleatórias.</p><pre>def update_target_model(self, current_frame):<br>  if (current_frame % self.freq_update_nn == 0 and TRAIN and current_frame &gt; self.initial_start_size):<br>      self.brain_target.set_weights(self.brain.get_weights())</pre><p>Esta próxima função do agente é responsável pela atualização dos pesos da rede neural convolucional. Nesta implementação, a atualização é realizada a cada “self.freq_update_nn” quadros (frames).</p><p>Parabéns por chegar até aqui! Com todo o conhecimento que compartilhamos, você já está pronto para mergulhar no mundo do Aprendizado por Reforço! 🚀🤖🎉<br>O código completo para que você possa utilizar ou até mesmo se basear está em meu GitHub.</p><p><a href="https://github.com/MateusDeFreitasRosa/RLGameAIEye">GitHub - MateusDeFreitasRosa/RLGameAIEye</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*sm4XwrBAqvJiwxAt.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495243ebb2d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>