<?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 Gabriel Cassimiro on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Cassimiro on Medium]]></description>
        <link>https://medium.com/@gabrielcassimiro17?source=rss-3692fb93d7e5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Iv9vg8Oi292SbmTCmxKCqA.png</url>
            <title>Stories by Gabriel Cassimiro on Medium</title>
            <link>https://medium.com/@gabrielcassimiro17?source=rss-3692fb93d7e5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 18 May 2026 11:32:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabrielcassimiro17/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[The LangGraph Guide to the Galaxy — part 1]]></title>
            <link>https://medium.com/geekculture/the-langgraph-guide-to-the-galaxy-part-1-5f3a0e29f0f4?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f3a0e29f0f4</guid>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 14:13:57 GMT</pubDate>
            <atom:updated>2024-11-06T14:13:57.726Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The </strong>LangGraph <strong>Guide to the Galaxy — part 1</strong></h3><p>In this guide, I will explain the core concepts of LangGraph and use a real project with a complex agent to illustrate the concepts. My idea here is to go deep in the concepts so feel free to skip to certain parts that interest you more. Below is the table of contents:</p><ol><li><strong>Introduction</strong></li></ol><ul><li><strong>Why LangGraph?</strong></li><li><strong>What is LangGraph?</strong></li></ul><p><strong>2. Key Concepts</strong></p><ul><li><strong>Understanding Nodes, Edges and State</strong></li><li><strong>Cyclic Graphs in LangGraph</strong></li><li><strong>Tools integration</strong></li></ul><h3>1. Introduction</h3><p>So let’s start from the beginning.</p><h4>Why do you need LangGraph?</h4><p>In the current landscape of 2024, companies, startups and individuals are rushing to create solutions using the mystical power of GenAI. However, very few are able to produce production ready systems, with enough quality and maintainability.</p><p>A couple of frameworks were created to help with some challenges that Gen AI present such as LangChain, Haystack and Llama Index (among ton others). These frameworks have provided foundational tools for integrating large language models, managing data retrieval, and orchestrating complex AI workflows.</p><p>One phrase from one of the biggest AI personalities, Andrew NG, goes like this:</p><blockquote>The future of Generative Artificial Intelligence is Agentic</blockquote><p>What does this mean?</p><p>Ng’s statement demonstrates the shift towards AI systems that act as autonomous agents — capable of making decisions, performing tasks, and interacting with other systems independently. This goes beyond simple, static models and towards dynamic AI that can reason, plan, and adapt on its own.</p><p>So as these solutions get more complex, it creates the need to create and use more advanced frameworks that can support these new capabilities and tasks required by these agentic systems. This is where LangGraph comes in.</p><h4>What is LangGraph</h4><p>From the official documentation:</p><blockquote><a href="https://langchain-ai.github.io/langgraph/">LangGraph</a> is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows. […] it offers these core benefits: cycles, controllability, and persistence.</blockquote><p>So in a nutshell this is a framework for creating LLM Agents that are able to use cyclic workflows with a structured architecture.</p><p>LangGraph’s flexible API supports diverse control flows — single agent, multi-agent, hierarchical, and sequential — and robustly handles realistic, complex scenarios.</p><h3>2. Key Concepts</h3><h4>Understanding Nodes, Edges, and State</h4><p>Nodes and Edges are the main building blocks of LangGraph. In a few words, nodes are the main logic and steps of the system and the edges are the flow of those steps.</p><p><strong>Nodes</strong></p><p>Starting with the nodes, this component is where we will create our action for each step of our system. Each node will have a function, a model, or a tool that will be executed. In Python, they are simply a Runnable object.</p><p>We can design nodes for tasks such as connecting to an API, executing a simple task, or interacting with a Language Model. Some nodes are pre-built by the lib, but you can easily create your own tailored to your need.</p><p><strong>Edges</strong></p><p>Edges are the connections between the nodes, directing the flow of the system. They can be simply directional or can have some conditional logic to direct to the next step.</p><p>Before building our first graph let’s look at one more core building block, the State.</p><p><strong>State</strong></p><p>The State in LangGraph is the component that enables nodes to use context or data generated by another node. It is basically the saved outputs from the nodes saved so that other nodes can access them.</p><p>A State is usually a TypedDict with each attribute being an information we want to persist. So if we want to keep a Chat History we would create an attribute like “messages” to keep a list of the interactions between the Human and the LLM.</p><p>In the execution of the graph, the State will be passed to each node and can be modified in that step. So the input of the node is the State and the returned object from each node becomes the new State to be passed to the next step.</p><p>So let’s build a simple version to illustrate these concepts:</p><p>In this graph, we will call the LLM with a question, count the words in the response, and if the response is bigger than 10 words upper case everything, and smaller lower case everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*AgM6tQSssD_JDTuOhdwX7A.png" /><figcaption>Image by Author</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bb45c95238adc8e023726987809ac66/href">https://medium.com/media/9bb45c95238adc8e023726987809ac66/href</a></iframe><p>This graph demonstrates nodes with calls to LLMs and with simple functions, all of them interacting with the state. We also have simple and conditional edges, with a router implemented to direct the flow.</p><p>Ok, so let’s dive into the pieces.</p><p>First, we defined all the components: the State class, the nodes as functions, and one function for our conditional edge.</p><p>Then, we went into defining the graph. Here we use a StateGraph as the graph object and use the add_node function to name each node and add the function related to that node. After adding the nodes, we define the edges between them. The add_edge function is used to create simple directional edges and the add_conditional_edge for the conditional ones. Pretty self-explanatory, right?</p><p>The conditional edges use a function to route the flow of the application. In the example, it is the function “router” that simply returns a key if the number of words in the response is more or less than 10. This key is then used to route to the next node.</p><p>Finally, we compile the graph using the .compile method, transforming the graph into an executable workflow.</p><p>To call the graph we use .invoke() and pass a dict with the keys and values of the state attribute we want to fill.</p><p>The response from the graph is the full state. So to access the last message we have to get the correct key containing the list of messages and get the last appended message. The outputs from the print statements at the end of the code are:</p><pre>dict_keys([&#39;messages&#39;, &#39;number_of_words&#39;])<br>ARTIFICIAL INTELLIGENCE: MACHINES MIMICKING HUMAN COGNITIVE FUNCTIONS.<br>7</pre><p>This is still a simple implementation, and the main benefits of LangGraph are not yet in full display. For that let’s look into Cyclic Workflows and Tools.</p><h4><strong>Cyclic Graphs in LangGraph</strong></h4><p>The cyclic graph is one of the key features that sets LangGraph apart from other linear frameworks. This feature allows the nodes to not only process the data and pass it forward but to also loop back to previous nodes or even themselves.</p><p>So a cyclic graph is a graph that has edges that can loop back to earlier nodes. One of the most straightforward uses for this is allowing Agents to call tools to get the output and generate the final answer. Other use cases are Multi-Agent Systems, Planning and Reflection Agents. All these architectures will be covered in the second part of this article.</p><h4>Tools integration</h4><p>Let’s talk now about tools.</p><p>A couple of models have the capacity to call external tools with features like <a href="https://codelabs.developers.google.com/codelabs/gemini-function-calling">Gemini’s Function Calling</a>. This makes it easier to interact with external APIs and gives the LLM much more capabilities.</p><p>In <a href="https://langchain-ai.github.io/langgraph/reference/prebuilt/#toolnode">LangGraph Tool Nodes</a> encapsulate the logic of calling the APIs and managing the parsings required. This is a pre-built node but if you want you can create your own.</p><p>In the next part, we will take a look at a full project implementing everything into a scalable solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f3a0e29f0f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/the-langgraph-guide-to-the-galaxy-part-1-5f3a0e29f0f4">The LangGraph Guide to the Galaxy — part 1</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Sommelier built with PaLM API and LangChain]]></title>
            <link>https://gabrielcassimiro17.medium.com/ai-sommelier-built-with-palm-api-and-langchain-1b270c41a16a?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b270c41a16a</guid>
            <category><![CDATA[palm-api]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[palm]]></category>
            <category><![CDATA[pinecone]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 12:03:54 GMT</pubDate>
            <atom:updated>2023-09-26T12:03:54.992Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI Sommelier Built with PaLM API and LangChain</h3><h4>Project walkthrough to build an LLM-powered application using PaLM API, Pinecone as the vector database, and Streamlit as the interface.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nc5xthLsbA007oGigQWoQg.jpeg" /><figcaption>Image by <a href="https://unsplash.com/pt-br/@hermez777?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hermes Rivera</a> at <a href="https://unsplash.com/pt-br/fotografias/aK6WGqxyHFw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this article, I aim to demonstrate how to use the PaLM API to build solutions using LangChain. I will build a solution using LangChain chains, Google Embeddings, Pinecone as the VectorDB, and Streamlit as the interface to interact with users.</p><p>The problem we want to tackle is personalized wine recommendations. I want to build an AI capable of recommending wines based on user preference and also using a database containing 130K wines.</p><p>The full code can be found <a href="https://github.com/gabrielcassimiro17/ai-sommelier/tree/main">here</a>.</p><h4>The data</h4><p>The data used in this project is the dataset <a href="https://www.kaggle.com/datasets/zynicide/wine-reviews">wine reviews</a>, <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">license</a>. This dataset contains 130K reviews of wines. It also contains the country, region, variety, and winery of each wine. This is a sample of the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pS2JF0w2idyiR5bEjBpZyg.png" /><figcaption>Image by Author</figcaption></figure><h4>The Problem</h4><p>So, to tackle our problem we want to first understand the taste of the user, then search the database for the wines that may be a good recommendation, and decide which one is the final recommendation.</p><p>To get the user input we will use a simple questionnaire inside of Streamlit with the following questions:</p><ol><li>Preferred Taste Profile;</li><li>Level of experience;</li><li>Red or White wine preference;</li><li>Favorite Flavours;</li><li>Pairing intent;</li><li>Open field to add any information about your taste.</li></ol><p>All of these (except the last) have pre-selected categories. However, since we are using LLMs this isn&#39;t strictly necessary. We could leave all questions with free text input because the LLM is able to use it without the categories. However, to guide the user I chose to use categories.</p><h4>The Architecture</h4><p>The Architecture of the solution is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGR0JNlcYitImdZGoDiaZA.jpeg" /><figcaption>Image by Author</figcaption></figure><p>For the solution, we will have two calls to the LLM API. In the first one, we will pass the taste form information and ask for the LLM to generate a string query that summarizes the taste and will be used for similarity search on the vector DB. After that, we can find the most similar descriptions of the wines to the person&#39;s taste.</p><p>However, this is not enough for a final decision, because some characteristics like red vs. white are not taken into account by this simple similarity search. That is why we call the LLM again passing the original taste form and the top 3 most similar wines to the LLM and ask it to select the best one for it and explain the reasoning.</p><h4>The Code</h4><p>Let&#39;s start by looking at the chains used for the calls to the API.</p><p>First, if you do not know already what is LangChain, this is a brief definition:</p><blockquote>LangChain is a framework for developing applications powered by language models.</blockquote><p>That is the official definition of LangChain. This framework was created recently and is already used as the industry standard for building tools powered by LLMs.</p><p>Chains are a core feature of LangChain and enable the integration of various components to form a unified application. They can format user input using a PromptTemplate and then forward it to an LLM. By linking multiple chains or combining them with other elements, we can create more complex chains.</p><p>This is the code for both of the chains:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96180daa25efe93859ecbad9f13ca02b/href">https://medium.com/media/96180daa25efe93859ecbad9f13ca02b/href</a></iframe><p>Here we have a couple of elements I would like to point out. First, we have the <strong>Response Schema</strong> and <strong>Output Parser</strong>. These are used to create a prompt in which the LLM will always return the output with the same structure and the parser will process that output to be able to work back in the code.</p><p>Then we have the prompt built using the <strong>Chat Prompt Template</strong>. This allows us to pass variables into the prompt like the answers of the taste form. Lastly, we put everything back together with the <strong>Sequential Chain</strong>, defining the inputs and outputs.</p><p>Now we have to initialize the DB.</p><h4>The Database</h4><p>For the Vector Database, we are using Pinecone however you can easily change the one you want to use because we are using LangChain to interact with the DB.</p><p>To add the wines to the Database we need to first create an Embedding of each one and then upload them. We can easily perform this with the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfabb083f45f1ec6ad3ba7da48cdc5b4/href">https://medium.com/media/cfabb083f45f1ec6ad3ba7da48cdc5b4/href</a></iframe><p>We create an instance of Document from LangChain containing the text and the Metadata. Then we use LangChain and Google PaLM Embeddings to upload to Pinecone. The embeddings have 768 dimensions.</p><p>For this implementation I am using the free tier from Pinecone, which allows for 1 free index of the standard resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKh0zYAx3vg9BDIfCPpbFQ.png" /><figcaption>Image by Author</figcaption></figure><p>Now we just need to put everything together passing the input from the application to the chains and connect to the vector database.</p><h4>The App</h4><p>The App will be the main control of the flow. It is also where we will create all the resources we need: the form, the PaLM API Connection, the Pinecone connection and the final visualization.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e8f031d5ad2a6bfa7510852744e03ba/href">https://medium.com/media/8e8f031d5ad2a6bfa7510852744e03ba/href</a></iframe><p>This code can be divided in three main parts:</p><ol><li>The form to get the user input;</li><li>The interaction of the chains and the vector database;</li><li>The display of the final recommendation.</li></ol><p>These parts are executed inside the main script but for a larger application should be modularized.</p><p>This is an example of using the tool:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZwlTmyhlJg943dZnTE4vQ.png" /><figcaption>Image by Author</figcaption></figure><p>So this is the final product. All we have to do now is deploy this application. With this in mind, the first thing we need is to allow the user to choose which LLM to use and have an input for the API key.</p><p><strong>The final version can be seen </strong><a href="https://ai-sommelier.streamlit.app/"><strong>here</strong></a><strong>.</strong></p><h4>Conclusion</h4><p>Using LangChain allows us to build quick and in a modular manner. For the problem of recommending wines based on a database we were able to use Chains with two prompts that helped to understand the users taste, find some options to suggest and make the final decision with an explanation.</p><p>An easy way to interact with the user is through an interface such as Streamlit, making it fast to develop and deploy.</p><p>Thanks for reading.</p><p>If you like the content and want to support me, you can buy me a coffee:</p><p><a href="https://www.buymeacoffee.com/cassimiro">Gabriel Cassimiro is a Data Scientist sharing free content to the community</a></p><p>Here are a few other articles you might be interested in:</p><ul><li><a href="https://towardsdatascience.com/async-calls-for-chains-with-langchain-3818c16062ed">Async calls for Chains with Langchain</a></li><li><a href="https://towardsdatascience.com/solving-unity-environment-with-deep-reinforcement-learning-836dc181ee3b">Solving Unity Environment with Deep Reinforcement Learning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b270c41a16a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Output Parsing Function Calling vs. LangChain]]></title>
            <link>https://medium.com/data-science/llm-output-parsing-function-calling-vs-langchain-63b80545b3a7?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/63b80545b3a7</guid>
            <category><![CDATA[openai-api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 19:13:18 GMT</pubDate>
            <atom:updated>2023-09-21T19:13:18.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLM Output Parsing: Function Calling vs. LangChain</h3><h4>How to consistently parse outputs from LLMs using Open AI API and LangChain function calling: evaluating the methods’ advantages and disadvantages</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQbwvXrR6vQKVLZ-BEv9tg.jpeg" /><figcaption>Image by <a href="https://unsplash.com/pt-br/@thevictorbarrios?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Victor Barrios</a> at <a href="https://unsplash.com/pt-br/fotografias/yjygDnvRuaI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Creating tools with LLMs requires multiple components, such as vector databases, chains, agents, document splitters, and many other new tools.</p><p>However, one of the most crucial components is the LLM output parsing. If you cannot receive structured responses from your LLM, you will have a hard time working with the generations. This becomes even more evident when we want a single call to the LLM to output more than one piece of information.</p><p>Let’s illustrate the problem with a hypothetical scenario:</p><p>We want the LLM to output from a single call the <strong>ingredients</strong> and the <strong>steps</strong> to make a certain recipe. But we want to have both of these items separately to use in two different parts of our system.</p><pre>import openai<br><br>recipe = &#39;Fish and chips&#39;<br>query = f&quot;&quot;&quot;What is the recipe for {recipe}? <br>Return the ingredients list and steps separately.&quot;&quot;&quot;<br><br>response = openai.ChatCompletion.create(<br>    model=&quot;gpt-3.5-turbo-0613&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query}])<br><br>response_message = response[&quot;choices&quot;][0][&quot;message&quot;]<br>print(response_message[&#39;content&#39;])</pre><p>This returns the following:</p><pre>Ingredients for fish and chips:<br>- 1 pound white fish fillets (such as cod or haddock)<br>- 1 cup all-purpose flour<br>- 1 teaspoon baking powder<br>- 1 teaspoon salt<br>- 1/2 teaspoon black pepper<br>- 1 cup cold beer<br>- Vegetable oil, for frying<br>- 4 large russet potatoes<br>- Salt, to taste<br><br>Steps to make fish and chips:<br><br>1. Preheat the oven to 200°C (400°F).<br>2. Peel the potatoes and cut them into thick, uniform strips. Rinse the potato strips in cold water to remove excess starch. Pat them dry using a clean kitchen towel.<br>3. In a large pot or deep fryer, heat vegetable oil to 175°C (350°F). Ensure there is enough oil to completely submerge the potatoes and fish.<br>4. In a mixing bowl, combine the flour, baking powder, salt, and black pepper. Whisk in the cold beer gradually until a smooth batter forms. Set the batter aside.<br>5. Take the dried potato strips and fry them in batches for about 5-6 minutes or until golden brown. Remove the fries using a slotted spoon and place them on a paper towel-lined dish to drain excess oil. Keep them warm in the preheated oven.<br>6. Dip each fish fillet into the prepared batter, ensuring it is well coated. Let any excess batter drip off before carefully placing the fillet into the hot oil.<br>7. Fry the fish fillets for 4-5 minutes on each side or until they turn golden brown and become crispy. Remove them from the oil using a slotted spoon and place them on a paper towel-lined dish to drain excess oil.<br>8. Season the fish and chips with salt while they are still hot.<br>9. Serve the fish and chips hot with tartar sauce, malt vinegar, or ketchup as desired.<br><br>Enjoy your homemade fish and chips!</pre><p>This is a huge string and parsing it would be hard because the LLM can return slightly different structures breaking whatever code you write. You could argue that asking in the prompt to always return “Ingredients:” and “Steps:” could resolve and you are not wrong. This could work, however you would still need to process the string manually and be open to eventual variations and hallucinations.</p><h3>Solution</h3><p>There are a couple of ways we could solve this problem. One was mentioned above, but there are a couple of tested ways that might be better. In this article, I will show two options:</p><ol><li>Open AI Function calling;</li><li>LangChain Output Parser.</li></ol><h4>Open AI Function calling</h4><p>This is a method that I have been trying and is giving the most consistent results. We use the Function Calling capability of the Open AI API so that the model returns the response as a structured JSON.</p><p>This functionality has the objective of providing the LLM the ability to call an external function by providing the inputs as a JSON. The models were fine-tuned to understand when they need to use a given function. An example of this is a function for current weather. If you ask GPT for the current weather, it won’t be able to tell you, but you can provide a function that does this and pass it to GPT so it will know that it can be accessed given some input.</p><p>If you want to dive deeper into this functionality here is the <a href="https://openai.com/blog/function-calling-and-other-api-updates">announcement from Open AI</a> and here is a <a href="https://towardsdatascience.com/how-to-use-openais-function-calling-e35bdac88ae7">great article</a>.</p><p>So let’s look in the code at what this would look like given our problem at hand. Let’s break down the code:</p><pre>functions = [<br>    {<br>        &quot;name&quot;: &quot;return_recipe&quot;,<br>        &quot;description&quot;: &quot;Return the recipe asked&quot;,<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;ingredients&quot;: {<br>                    &quot;type&quot;: &quot;string&quot;,<br>                    &quot;description&quot;: &quot;The ingredients list.&quot;<br>                },<br>                &quot;steps&quot;: {<br>                    &quot;type&quot;: &quot;string&quot;,<br>                    &quot;description&quot;: &quot;The recipe steps.&quot;<br>                },<br>            },<br>            },<br>            &quot;required&quot;: [&quot;ingredients&quot;,&quot;steps&quot;],<br>        }<br>]</pre><p>The first thing we need to do is declare the functions that will be available to the LLM. We have to give it a name and a description so that the model understands when it should use the function. Here we tell it the this function is used to return the recipe asked.</p><p>Then we go into the parameters. First, we say that it is of type object and the properties it can use are ingredients and steps. Both of these also have a description and a type to guide the LLM on the output. Finally, we specify which of those properties are required to call the function (this means we could have optional fields that the LLM would judge if it wanted to use them).</p><p>Let’s use that now in a call to the LLM:</p><pre>import openai<br><br>recipe = &#39;Fish and chips&#39;<br>query = f&quot;What is the recipe for {recipe}? Return the ingredients list and steps separately.&quot;<br><br><br>response = openai.ChatCompletion.create(<br>    model=&quot;gpt-3.5-turbo-0613&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query}],<br>    functions=functions,<br>    function_call={&#39;name&#39;:&#39;return_recipe&#39;}<br>)<br>response_message = response[&quot;choices&quot;][0][&quot;message&quot;]<br><br>print(response_message)<br>print(response_message[&#39;function_call&#39;][&#39;arguments&#39;])</pre><p>Here we start by creating our query to the API by formatting a base prompt with what could be a variable input (recipe). Then, we declare our API call using “gpt-3.5-turbo-0613”, we pass our query in the messages argument, and now we pass our functions.</p><p>There are two arguments regarding our functions. The first one we pass the list of objects in the format shown above with the functions the model has access to. And the second argument “function_call” we specify how the model should use those functions. There are three options:</p><ol><li>“Auto” -&gt; the model decides between user response or function calling;</li><li>“none” -&gt; the model does not call the function and returns the user response;</li><li>{“name”: “my_function_name”} -&gt; specifying a function name forces the model to use it.</li></ol><p>You can find the official documentation <a href="https://platform.openai.com/docs/api-reference/chat/create">here</a>.</p><p>In our case and for using as output parsing we used the latter:</p><pre>function_call={&#39;name&#39;:&#39;return_recipe&#39;}</pre><p>So now we can look at our responses. The response we get (after this filter [“choices”][0][“message”]) is:</p><pre>{<br>  &quot;role&quot;: &quot;assistant&quot;,<br>  &quot;content&quot;: null,<br>  &quot;function_call&quot;: {<br>    &quot;name&quot;: &quot;return_recipe&quot;,<br>    &quot;arguments&quot;: &quot;{\n  \&quot;ingredients\&quot;: \&quot;For the fish:\\n- 1 lb white fish fillets\\n- 1 cup all-purpose flour\\n- 1 tsp baking powder\\n- 1 tsp salt\\n- 1/2 tsp black pepper\\n- 1 cup cold water\\n- Vegetable oil, for frying\\nFor the chips:\\n- 4 large potatoes\\n- Vegetable oil, for frying\\n- Salt, to taste\&quot;,\n  \&quot;steps\&quot;: \&quot;1. Start by preparing the fish. In a shallow dish, combine the flour, baking powder, salt, and black pepper.\\n2. Gradually whisk in the cold water until the batter is smooth.\\n3. Heat vegetable oil in a large frying pan or deep fryer.\\n4. Dip the fish fillets into the batter, coating them evenly.\\n5. Gently place the coated fillets into the hot oil and fry for 4-5 minutes on each side, or until golden brown and crispy.\\n6. Remove the fried fish from the oil and place them on a paper towel-lined plate to drain any excess oil.\\n7. For the chips, peel the potatoes and cut them into thick chips.\\n8. Heat vegetable oil in a deep fryer or large pan.\\n9. Fry the chips in batches until golden and crisp.\\n10. Remove the chips from the oil and place them on a paper towel-lined plate to drain any excess oil.\\n11. Season the chips with salt.\\n12. Serve the fish and chips together, and enjoy!\&quot;\n}&quot;<br>  }<br>}</pre><p>If we parse it further into the “function_call” we can see our intended structured response:</p><pre>{<br>  &quot;ingredients&quot;: &quot;For the fish:\n- 1 lb white fish fillets\n- 1 cup all-purpose flour\n- 1 tsp baking powder\n- 1 tsp salt\n- 1/2 tsp black pepper\n- 1 cup cold water\n- Vegetable oil, for frying\nFor the chips:\n- 4 large potatoes\n- Vegetable oil, for frying\n- Salt, to taste&quot;,<br>  &quot;steps&quot;: &quot;1. Start by preparing the fish. In a shallow dish, combine the flour, baking powder, salt, and black pepper.\n2. Gradually whisk in the cold water until the batter is smooth.\n3. Heat vegetable oil in a large frying pan or deep fryer.\n4. Dip the fish fillets into the batter, coating them evenly.\n5. Gently place the coated fillets into the hot oil and fry for 4-5 minutes on each side, or until golden brown and crispy.\n6. Remove the fried fish from the oil and place them on a paper towel-lined plate to drain any excess oil.\n7. For the chips, peel the potatoes and cut them into thick chips.\n8. Heat vegetable oil in a deep fryer or large pan.\n9. Fry the chips in batches until golden and crisp.\n10. Remove the chips from the oil and place them on a paper towel-lined plate to drain any excess oil.\n11. Season the chips with salt.\n12. Serve the fish and chips together, and enjoy!&quot;<br>}</pre><h4>Conclusion for function calling</h4><p>It is possible to use the feature of function calling straight from the Open AI API. This allows us to have a dictionary format response with the same keys every time the LLM is called.</p><p>To use it is pretty straightforward, you just have to declare the functions object specifying the name, description, and properties focused on your task but specifying (in the description) that this should be the response of the model. Also, when calling the API we can force the model to use our function, making it even more consistent.</p><p>The main downside of this method is that it is not supported by all LLM models and APIs. So if we wanted to use Google PaLM API we would have to use another method.</p><h3>LangChain Output Parsers</h3><p>One alternative we have that is model-agnostic is using LangChain.</p><p>First, what is LangChain?</p><blockquote>LangChain is a framework for developing applications powered by language models.</blockquote><p>That is the official definition of LangChain. This framework was created recently and is already used as the industry standard for building tools powered by LLMs.</p><p>It has a functionality that is great for our use case called “Output Parsers”. In this module, there are multiple objects that can be created to return and parse different types of formats from LLM calls. It achieves this, by first declaring what the format is and passing it in the prompt to the LLM. Then it uses the object created previously to parse the response.</p><p>Let’s break down the code:</p><pre>from langchain.prompts import ChatPromptTemplate<br>from langchain.output_parsers import ResponseSchema, StructuredOutputParser<br>from langchain.llms import GooglePalm, OpenAI<br><br><br>ingredients = ResponseSchema(<br>        name=&quot;ingredients&quot;,<br>        description=&quot;The ingredients from recipe, as a unique string.&quot;,<br>    )<br>steps = ResponseSchema(<br>        name=&quot;steps&quot;,<br>        description=&quot;The steps to prepare the recipe, as a unique string.&quot;,<br>    )<br><br>output_parser = StructuredOutputParser.from_response_schemas(<br>    [ingredients, steps]<br>)<br><br>response_format = output_parser.get_format_instructions()<br>print(response_format)<br><br>prompt = ChatPromptTemplate.from_template(&quot;What is the recipe for {recipe}? Return the ingredients list and steps separately. \n {format_instructions}&quot;)</pre><p>The first thing we do here is create our Response Schema that will be the input for our parser. We create one for the ingredients and one for the steps, each containing a name that will be the key of the dictionary and a description that will guide the LLM on the response.</p><p>Then we create our StructuredOutputParser from those response schemas. There are multiple ways to do this, with different styles of parsers. Look <a href="https://python.langchain.com/docs/modules/model_io/output_parsers/">here</a> to learn more about them.</p><p>Lastly, we get our format instructions and define our prompt that will have the recipe name and the format instructions as inputs. The format instructions are these:</p><pre>&quot;&quot;&quot;<br>The output should be a markdown code snippet formatted in the following schema, including the leading and trailing &quot;```json&quot; and &quot;```&quot;:<br><br>```json<br>{<br> &quot;ingredients&quot;: string  // The ingredients from recipe, as a unique string.<br> &quot;steps&quot;: string  // The steps to prepare the recipe, as a unique string.<br>}  <br>&quot;&quot;&quot;</pre><p>Now what we have left is just calling the API. Here I will demonstrate both the Open AI API and with Google PaLM API.</p><pre>llm_openai = OpenAI()<br>llm_palm = GooglePalm()<br><br>recipe = &#39;Fish and chips&#39;<br><br>formated_prompt = prompt.format(**{&quot;recipe&quot;:recipe, &quot;format_instructions&quot;:output_parser.get_format_instructions()})<br><br>response_palm = llm_palm(formated_prompt)<br>response_openai = llm_openai(formated_prompt)<br><br>print(&quot;PaLM:&quot;)<br>print(response_palm)<br>print(output_parser.parse(response_palm))<br><br>print(&quot;Open AI:&quot;)<br>print(response_openai)<br>print(output_parser.parse(response_openai))</pre><p>As you can see it is really easy to change between models. The whole structure defined before can be used in the exact same way for any models supported by LangChain. We used also the same parser for both models.</p><p>This generated the following output:</p><pre># PaLM:<br>{<br>&#39;ingredients&#39;: &#39;&#39;&#39;- 1 cup all-purpose flour\n<br>- 1 teaspoon baking powder\n<br>- 1/2 teaspoon salt\n<br>- 1/2 cup cold water\n<br>- 1 egg\n<br>- 1 pound white fish fillets, such as cod or haddock\n<br>- Vegetable oil for frying\n- 1 cup tartar sauce\n<br>- 1/2 cup malt vinegar\n- Lemon wedges&#39;&#39;&#39;,<br> &#39;steps&#39;: &#39;&#39;&#39;1. In a large bowl, whisk together the flour, baking powder, and salt.\n<br>2. In a separate bowl, whisk together the egg and water.\n<br>3. Dip the fish fillets into the egg mixture, then coat them in the flour mixture.\n<br>4. Heat the oil in a deep fryer or large skillet to 375 degrees F (190 degrees C).\n<br>5. Fry the fish fillets for 3-5 minutes per side, or until golden brown and cooked through.\n<br>6. Drain the fish fillets on paper towels.\n<br>7. Serve the fish fillets immediately with tartar sauce, malt vinegar, and lemon wedges.<br>&#39;&#39;&#39;<br>}<br><br># Open AI<br>{<br>&#39;ingredients&#39;: &#39;1 ½ pounds cod fillet, cut into 4 pieces,<br> 2 cups all-purpose flour,<br> 2 teaspoons baking powder,<br> 1 teaspoon salt,<br> 1 teaspoon freshly ground black pepper,<br> ½ teaspoon garlic powder,<br> 1 cup beer (or water),<br> vegetable oil, for frying, <br>Tartar sauce, for serving&#39;,<br> &#39;steps&#39;: &#39;1. Preheat the oven to 400°F (200°C) and line a baking sheet with parchment paper.<br> 2. In a medium bowl, mix together the flour, baking powder, salt, pepper and garlic powder. <br>3. Pour in the beer and whisk until a thick batter forms.<br> 4. Dip the cod in the batter, coating it on all sides. <br>5. Heat about 2 inches (5 cm) of oil in a large pot or skillet over medium-high heat.<br> 6. Fry the cod for 3 to 4 minutes per side, or until golden brown.<br> 7. Transfer the cod to the prepared baking sheet and bake for 5 to 7 minutes. <br>8. Serve warm with tartar sauce.&#39;<br>}<br></pre><h4>Conclusion: LangChain Output parsing</h4><p>This method is really good as well and has as its main characteristic flexibility. We create a couple of structures such as Response Schema, Output Parser, and Prompt Templates that can be pieced together easily and used with different models. Another good advantage of this is the support for multiple output formats.</p><p>The main disadvantage comes from passing the format instructions via the prompt. This allows for random errors and hallucinations. One real example was from this specific case where I had to specify “ as a unique string” in the description of the response schema. If I did not specify this, the model was returning a list of strings with the steps and instructions and this caused an error of parsing in the Output Parser.</p><h3>Conclusion</h3><p>There are multiple ways of using an output parser for your LLM-powered application. However, your choice may change depending on the problem at hand. For myself, I like to follow this idea:</p><p>I always use an output parser, even if I have only one output from the LLM. This allows me to control and specify my outputs. If I am working with Open AI, Function Calling is my choice because it has the most control and will avoid random errors in a production application. However, if I am using a different LLM or need a different output format, my choice is LangChain, but with a lot of testing on the outputs, in order to craft the prompt with the least mistakes.</p><p>Thanks for reading.</p><p>The full code can be found <a href="https://github.com/gabrielcassimiro17/llm-output-parsing">here</a>.</p><p>If you like the content and want to support me, you can buy me a coffee:</p><p><a href="https://www.buymeacoffee.com/cassimiro">Gabriel Cassimiro is a Data Scientist sharing free content to the community</a></p><p>Here are a few other articles you might be interested in:</p><ul><li><a href="https://towardsdatascience.com/async-calls-for-chains-with-langchain-3818c16062ed">Async calls for Chains with Langchain</a></li><li><a href="https://towardsdatascience.com/solving-unity-environment-with-deep-reinforcement-learning-836dc181ee3b">Solving Unity Environment with Deep Reinforcement Learning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63b80545b3a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/llm-output-parsing-function-calling-vs-langchain-63b80545b3a7">LLM Output Parsing Function Calling vs. LangChain</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async calls for Chains with Langchain]]></title>
            <link>https://medium.com/data-science/async-calls-for-chains-with-langchain-3818c16062ed?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3818c16062ed</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 15:34:52 GMT</pubDate>
            <atom:updated>2023-07-10T15:34:52.266Z</atom:updated>
            <content:encoded><![CDATA[<h3>Async for LangChain and LLMs</h3><h4>How to make LangChain chains work with Async calls to LLMs, speeding up the time it takes to run a sequential long chain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzO4ieMtSEVhJqLkuy6Gng.jpeg" /><figcaption>Image by<a href="https://unsplash.com/@iggii?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">hp koch</a> on <a href="https://unsplash.com/pt-br/fotografias/2OuTr9_VaUg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this article, I will cover how to use asynchronous calls to LLMs for long workflows using LangChain. We will go through an example with the full code and compare Sequential execution with the Async calls.</p><p>Here is the overview of the content. If you’d like you can jump to the section of your interest:</p><ol><li>Basics: What is LangChain</li><li>How to run a Synchronous chain with LangChain</li><li>How to run a single Asynchronous chain with LangChain</li><li>Real-world tips for long workflows with Async Chains.</li></ol><p>So let’s start!</p><h3>Basics: What is Langchain</h3><p>LangChain is a framework for developing applications powered by language models. That is the official definition of LangChain. This framework was created recently and is already used as the industry standard for building tools powered by LLMs.</p><p>It is open-source and well-maintained, with new features being released in a very fast time frame.</p><p>The official documentation can be found <a href="https://python.langchain.com/docs/get_started/introduction.html">here</a> and the GitHub repository <a href="https://github.com/hwchase17/langchain">here</a>.</p><p>One downside that we have in this library is that since the features are new we cannot use Chat GPT to help effectively to build new code. So this means that we have to work in the “Ancient” way of reading documentation, forums, and tutorials.</p><p>The documentation for LangChain.is really good however there are not a lot of examples of some specific things.</p><p>I ran into this problem with Async for long chains.</p><p>Here are the main resources I used to learn more about the framework:</p><ol><li>Deep Learning AI course: <a href="https://www.deeplearning.ai/short-courses/langchain-chat-with-your-data/">LangChain Chat with your data</a>;</li><li><a href="https://python.langchain.com/docs/get_started/introduction.html">Official Documentation</a>;</li><li><a href="https://www.youtube.com/watch?v=_v_fgW2SkkQ&amp;list=PLqZXAkvF1bPNQER9mLmDbntNfSpzdDIU5">Youtube channel</a>.</li></ol><p>(ps. They are all free)</p><h3>How to run a Synchronous chain with LangChain</h3><p>So let me set up the problem I had: I have a data frame with a lot of rows and for each of those rows I need to run multiple prompts (chains) to an LLM and return the result to my data frame.</p><p>When you have multiple rows, let’s say 10K, running 3 prompts for each and each response (if the server is not overloaded) taking about 3–5 seconds you end up waiting for days for the workflow to be completed.</p><p>Bellow I am going to show the main steps and code to build a synchronous chain and time it on a subset of data.</p><p>For this example, I am going to use the dataset <a href="https://www.kaggle.com/datasets/zynicide/wine-reviews">Wine Reviews</a>, <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">license</a>. The goal here is to extract some information from the written reviews.</p><p>I want to extract a Summary of the review, the main sentiment, and the top 5 characteristics of each wine.</p><p>For that, I created two chains, one for the summary and sentiment and another that takes the summary as input to extract the characteristics.</p><p>Here is the code to run it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9898eb355870bc136b8d78374ff507ec/href">https://medium.com/media/9898eb355870bc136b8d78374ff507ec/href</a></iframe><p>Run time (10 examples):</p><blockquote>Summary Chain (Sequential) executed in 22.59 seconds.<br>Characteristics Chain (Sequential) executed in 22.85 seconds.</blockquote><p>If you want to understand more about the components I am using I really recommend watching the <a href="https://www.deeplearning.ai/short-courses/langchain-chat-with-your-data/">Deep Learning AI Course</a>.</p><p>The main takeaways from this code are the building blocks for a chain, how to run it in a sequential way, and the time it took to finish this loop. It is important to remember that it was about 45 seconds for 10 examples and the full dataset contains 130K rows. So the Async implementation is the New Hope to run this in a reasonable time.</p><p>So with the problem set up and the baseline established, let&#39;s see how we can optimize this code to run much faster.</p><h3>How to run a single Asynchronous chain with LangChain</h3><p>So for this, we are going to use a resource called Asynchronous calls. To explain this, first I will explain briefly what the code is doing and where the time is taking too long.</p><p>In our example, we go through each row of the data frame, extract some information from the rows, add them to our prompt, and call the GPT API to get a response. After the response, we just parse it and add it back to the data frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTKsctmPb8Xoi90jwtNyaA.jpeg" /><figcaption>Image by Author</figcaption></figure><p>The main bottleneck here is when we call the GPT API because our computer has to wait idly for the response from that API (about 3 seconds). The rest of the steps are fast and can still be optimized but that is not the focus of this article.</p><p>So instead of waiting Idly for the response, what if we sent all the calls to the API at the same time? This way we would only have to wait for a single response and then process them. This is called Asynchronous calls to the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2M2pom0rTfxurGl1cKzLHQ.jpeg" /><figcaption>Image by Author</figcaption></figure><p>This way we do the pre-process and post-process sequentially but the calls to the API do not have to wait for the last response to come back before sending the next one.</p><p>So here is the code for the Async chains:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bba9cc4c59a1dcf4f1741b90bdc2278c/href">https://medium.com/media/bba9cc4c59a1dcf4f1741b90bdc2278c/href</a></iframe><p>In this code, we use the Python syntax of async and await. LangChain also gives us the code to run the chain async, with the arun() function. So in the beginning we first process each row sequentially (can be optimized) and create multiple “tasks” that will await the response from the API in parallel and then we process the response to the final desired format sequentially (can also be optimized).</p><p>Run time (10 examples):</p><blockquote>Summary Chain (Async) executed in 3.35 seconds.<br>Characteristics Chain (Async) executed in 2.49 seconds.</blockquote><p>Compared to the sequential:</p><blockquote>Summary Chain (Sequential) executed in 22.59 seconds.<br>Characteristics Chain (Sequential) executed in 22.85 seconds.</blockquote><p>We can see almost a 10x improvement in the run time. So for big workloads, I highly recommend using this method. Also my code is full of for loops that can also be optimized further to improve performance.</p><p>The full code to this tutorial can be found in this <a href="https://github.com/gabrielcassimiro17/async-langchain">Github Repo</a>.</p><h3>Real-world tips for long workflows with Async Chains.</h3><p>When I had to run this, I ran into some limitations and a few roadblocks, that I want to share with you.</p><h4>Notebooks are not Async Friendly</h4><p>When running async calls on Jupyter Notebooks you may encounter some issues. However, just ask Chat GPT and it can probably help you out with that. The code I built is to run big workloads in a .py file, so it may need some changes to run in a notebook.</p><h4>Too many output keys</h4><p>The First one was that my chain had multiple keys as outputs and at the time the arun() only accepted chains that had one key as the output. So to fix this I had to break my chain into two separate ones.</p><h4>Not all chains can be async</h4><p>I had a logic of using a vector database for examples and comparisons in my prompt and that required that the examples were sequentially compared and added to the database. This rendered unfeasible the use of async for this link in the full chain.</p><h4>Lack of content</h4><p>For this specific matter, the best content I could find was the <a href="https://python.langchain.com/docs/modules/chains/how_to/async_chain">official documentation for async </a>and build from there to my use case. So if you run it and find new things out share it with the world!</p><h3>Conclusion</h3><p>LangChain is a very powerful tool to create LLM-based applications. I highly recommend learning this framework and doing the courses cited above.</p><p>For the specific topic of running chains, for high workloads we saw the potential improvement that Async calls have, so my recommendation is to take the time to understand what the code is doing and have a boilerplate class (such as the one provided in my code) and run it Asynchronously!</p><p>For small workloads or applications that require only one call to an API it is not necessary to do it async, but if you have a boilerplate class just add a sync function so you can easily use one or the other.</p><p>Thanks for reading.</p><p>The full code can be found <a href="https://github.com/gabrielcassimiro17/async-langchain">here</a>.</p><p>If you like the content and want to support me, you can buy me a coffee:</p><p><a href="https://www.buymeacoffee.com/cassimiro">Gabriel Cassimiro is a Data Scientist sharing free content to the community</a></p><p>Here are a few other articles you might be interested in:</p><ul><li><a href="https://towardsdatascience.com/solving-unity-environment-with-deep-reinforcement-learning-836dc181ee3b">Solving Unity Environment with Deep Reinforcement Learning</a></li><li><a href="https://towardsdatascience.com/object-detection-with-tensorflow-model-and-opencv-d839f3e42849">Object detection with Tensorflow model and OpenCV</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3818c16062ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/async-calls-for-chains-with-langchain-3818c16062ed">Async calls for Chains with Langchain</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into the DDPG Algorithm for Continuous Control]]></title>
            <link>https://medium.com/geekculture/a-deep-dive-into-the-ddpg-algorithm-for-continuous-control-2718222c333e?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2718222c333e</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[unity-ml-agents]]></category>
            <category><![CDATA[continuous-control]]></category>
            <category><![CDATA[ddpg]]></category>
            <category><![CDATA[actor-critic]]></category>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 19:01:43 GMT</pubDate>
            <atom:updated>2023-04-14T19:01:43.398Z</atom:updated>
            <content:encoded><![CDATA[<h2>A Deep Dive into Actor-Critic methods with the DDPG Algorithm</h2><h4>Full project walkthrough with the implementation of the DDPG algorithm for the Continuous Control problem of the Reacher environment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjP0HhP0_sw1V3G5VCR4ZA.png" /><figcaption>Image by Author</figcaption></figure><p>Welcome to a fascinating exploration of reinforcement learning in the context of continuous control! In this article, we will dive into a challenging problem: teaching an intelligent agent to control a double-jointed robotic arm in the Reacher environment, a Unity-based simulation developed using the Unity ML-Agents toolkit. Our goal is to reach target locations with high precision, and to accomplish this, we have employed the state-of-the-art Deep Deterministic Policy Gradient (DDPG) algorithm, specifically designed for continuous state and action spaces.</p><figure><img alt="Sharing experience can accelerate learning." src="https://cdn-images-1.medium.com/max/640/1*kLXIqEdxFCEguwKGrwhgTg.gif" /><figcaption>Robots Sharing Experience (<a href="https://ai.googleblog.com/2018/06/scalable-deep-reinforcement-learning.html"><strong>Source</strong></a>)</figcaption></figure><p>Join me on this journey as we discuss the environment, the algorithm, the neural network architecture, and the training process that led the agent to achieve the average score of 30 in about 50 episodes, maintaining that performance for over 150 episodes. I will also share insights into future work and potential improvements that could improve this agent’s performance. Let’s dive in!</p><p>This article provides a comprehensive project walkthrough and complete code, but you can also access the code in the following GitHub repository:</p><p><a href="https://github.com/gabrielcassimiro17/rl-robot-movement">GitHub - gabrielcassimiro17/rl-robot-movement: This repository contains the implementation of a Deep Deterministic Policy Gradient (DDPG) algorithm applied to solve the Reacher environment in Unity ML-Agents.</a></p><h3>Real-world applications</h3><p>The Reacher environment might be an artificial simulation, but its underlying problem of learning to control a robotic arm to reach target locations has significant real-world implications, particularly in the field of robotics. Robotic arms play a critical role in manufacturing, production facilities, space exploration, and search and rescue operations. In these contexts, the ability to control robotic arms with high precision and dexterity is really important. By employing reinforcement learning techniques it is possible to enable these robotic systems to learn and adapt their behaviour in real time, leading to improved performance and flexibility. As a result, advancements in reinforcement learning not only contribute to our understanding of artificial intelligence but also have the potential to revolutionize industries and make a meaningful impact on society.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*br1VXPprVkieH0-ThcdmkQ.gif" /><figcaption>Training robotic arm to reach target locations in the real world. (<a href="https://www.youtube.com/watch?v=ZVIxt2rt1_4"><strong>Source</strong></a>)</figcaption></figure><h3>Environment</h3><p>The Reacher environment is a captivating and complex simulation, offering an excellent opportunity to showcase the power of reinforcement learning techniques in continuous control tasks. In this section, we will dive deeper into the environment’s characteristics and the problem our intelligent agent needs to solve.</p><h4>A Glimpse into the Reacher Environment</h4><p>Built using the <a href="https://github.com/Unity-Technologies/ml-agents">Unity ML-Agents</a> toolkit, the Reacher environment is a visually engaging simulation that requires our agent to control a double-jointed robotic arm. The objective is to guide the arm toward a target location and maintain its position within the target area for as long as possible. The environment features 20 simultaneous agents, each operating independently, which facilitates an efficient collection of experiences during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*8-NXPwKsxg5QYfzaRqKeYg.gif" /><figcaption>Image by Author</figcaption></figure><h4>State and Action Spaces</h4><p>Understanding the state and action spaces is crucial for designing an effective reinforcement learning algorithm. In the Reacher environment, the state space consists of 33 continuous variables that provide information about the robotic arm, such as its position, rotation, velocity, and angular velocities. The action space is also continuous, with four variables corresponding to the torque applied to the two joints of the robotic arm. Each action variable is a real number ranging between -1 and 1.</p><h4>Task Type and Success Criterion</h4><p>The Reacher task is considered episodic, with each episode consisting of a fixed number of time steps. The agent’s goal is to maximize its total reward throughout these steps. A reward of +0.1 is granted for each step the arm’s end effector remains in the target location. The environment is considered solved when the agent achieves an average score of 30 or more over 100 consecutive episodes.</p><p>In the next sections, we will explore the DDPG algorithm, its implementation, and how it effectively tackles the continuous control problem in this environment.</p><h3>Harnessing the Power of DDPG: Algorithm Choice for Continuous Control</h3><p>When it comes to continuous control tasks like the Reacher problem, the choice of algorithm is crucial for achieving optimal performance. In this project, we opted for the <a href="https://arxiv.org/abs/1509.02971">Deep Deterministic Policy Gradient (DDPG)</a> algorithm, an actor-critic method specifically designed to handle continuous state and action spaces. Let’s take a closer look at the DDPG algorithm and why it is well-suited for our task.</p><h4>Deep Deterministic Policy Gradient (DDPG) Explained</h4><p>The DDPG algorithm combines the strengths of policy-based and value-based methods by incorporating two neural networks: the Actor network, which determines the optimal actions given the current state, and the Critic network, which estimates the state-action value function (Q-function). Both networks have target networks, used to stabilize the learning process by providing a fixed target during updates.</p><p>By using the Critic network to estimate the Q-function and the Actor network to determine the optimal actions, the DDPG algorithm efficiently merges the benefits of <strong>policy gradient methods</strong> and <strong>deep Q-networks</strong>. This hybrid approach allows the agent to learn effectively and efficiently in continuous control environments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28cfe4b5da0545e244ecd3f8321ac1d9/href">https://medium.com/media/28cfe4b5da0545e244ecd3f8321ac1d9/href</a></iframe><p>The implementation also makes use of a <strong>Replay Buffer</strong>, being a crucial component to improve learning efficiency and stability. A replay buffer is essentially a memory data structure that stores a fixed number of past experiences or transitions, consisting of state, action, reward, next state, and done information. The main advantage of using it is that it enables the agent to <strong>break the correlation</strong> between consecutive experiences, thereby reducing the impact of <strong>harmful temporal correlations</strong>.</p><p>By sampling random mini-batches of experiences from the buffer, the agent can learn from a diverse set of transitions, which helps to stabilize and generalize the learning process. Moreover, the replay buffer allows the agent to reuse past experiences multiple times, thereby increasing data efficiency and promoting more effective learning from limited interaction with the environment.</p><h4>Why DDPG for the Reacher Problem?</h4><p>The DDPG algorithm is an excellent choice for the Reacher problem due to its ability to effectively handle continuous action spaces, a critical aspect of this environment. Furthermore, the algorithm’s design allows for the efficient use of parallel experiences collected by multiple agents, leading to faster learning and better convergence. In our project, the 20 agents operating simultaneously share experiences and learn collectively, ultimately achieving the desired performance in the Reacher task.</p><p>In the following sections, we will discuss the neural network architecture, hyperparameter selection, and the training process that enabled our agent to successfully learn and adapt its behavior within the Reacher environment using the DDPG algorithm.</p><h3>How the DDPG Algorithm Works in the Reacher Environment</h3><p>To better understand the effectiveness of the algorithm in the environment, let’s take a closer look at the key components and steps involved in the learning process.</p><h4>Neural Networks Architecture</h4><p>The DDPG algorithm employs two neural networks, the Actor and the Critic. Both networks consist of two hidden layers, each containing 400 nodes. The hidden layers use the ReLU (Rectified Linear Unit) activation function, while the output layer of the Actor network employs a tanh activation function to produce actions in the range of -1 to 1. The Critic network’s output layer does not have an activation function, as it directly estimates the Q-function.</p><p>This is the code implementing the networks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86018119f8aa32478c5ffe63acb7fe5f/href">https://medium.com/media/86018119f8aa32478c5ffe63acb7fe5f/href</a></iframe><h4>Hyperparameters Selection</h4><p>Carefully chosen hyperparameters are crucial for efficient learning. In this project, we used a <strong>buffer size</strong> of 200,000 to store experiences for replay, a <strong>batch size</strong> of 256 for learning updates, an <strong>actor learning rate</strong> of 5e-4, a <strong>critic learning rate</strong> of 1e-3, a s<strong>oft update parameter (tau) </strong>of 5e-3, and a <strong>discount factor (gamma)</strong> of 0.995. Additionally, we incorporated <strong>action noise</strong> to facilitate exploration, with an initial noise scale of 0.5 and a noise decay rate of 0.998.</p><h4>Training Process</h4><p>The training process involves continuous interaction between the Actor and Critic networks, with 20 parallel agents sharing the same networks and learning collectively from the experiences gathered by all agents. This setup speeds up the learning process and enhances efficiency.</p><p>The code used for training:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd94609b08876d334e934ef8741c82b7/href">https://medium.com/media/bd94609b08876d334e934ef8741c82b7/href</a></iframe><p>Here we create an agent based on the DDPG class and make it interact with the environment on a loop.</p><p>The key steps in the training process are depicted below:</p><ol><li><strong>Initialize the networks:</strong> The agents initialize the shared Actor and Critic networks and their respective target networks with random weights. The target networks provide a stable learning target during updates.</li><li><strong>Interact with the environment:</strong> Each agent, using the shared Actor network, interacts with the environment by choosing actions based on its current state. To encourage exploration, a noise term is added to the actions during the initial stages of training. After taking the action, each agent observes the resulting reward and the next state.</li><li><strong>Store experiences:</strong> Each agent stores the observed experience (state, action, reward, next_state) in a shared replay buffer. This buffer holds a fixed number of recent experiences, enabling the agents to learn from diverse transitions collected by all agents.</li><li><strong>Learn from experiences:</strong> Periodically, a batch of experiences is sampled from the shared replay buffer. The shared Critic network is updated using the sampled experiences by minimizing the mean squared error between the predicted and target Q-values. The target Q-values are calculated using the shared Critic target network and the shared Actor target network.</li><li><strong>Update the Actor network:</strong> The shared Actor network is updated using the policy gradient, computed by taking the gradient of the output of the shared Critic network with respect to the chosen actions. The shared Actor network learns to choose actions that maximize the expected Q-values.</li><li><strong>Update target networks:</strong> The shared Actor and Critic target networks are softly updated using a mix of the current and target network weights. This ensures a stable learning process.</li></ol><p>The DDPG algorithm’s design, combined with the chosen hyperparameters and neural network architecture, allows the agents to learn and adapt their behavior effectively in the continuous control environment, ultimately achieving the desired performance in the Reacher task.</p><h3>Results and Future Directions</h3><p>In this project, our agent successfully learned to control the double-jointed robotic arm in the Reacher environment using the DDPG algorithm. Throughout the training process, we monitored the agent’s performance based on the average score across all 20 agents. As the agent explored the environment and gathered experiences, its ability to predict optimal actions for maximizing rewards improved significantly.</p><p>Here we can see the trained agents performing the task:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UbaEWTe_sYr_LpZnRxj7Ow.gif" /><figcaption>Image by Author</figcaption></figure><h4>Training Results</h4><p>After about 50 episodes, the agent demonstrated a remarkable level of proficiency in the task, achieving an average score that surpassed the threshold required to consider the environment solved (30+) and maintained that level of performance for 150 episodes. Although the agent’s performance varied throughout the training process, the general trend showed an upward trajectory, indicating that the learning process was successful.</p><p>This plot shows the average score per episode of the 20 agents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ba7kzEtWeh1l15bt-PAKhA.png" /><figcaption>Image by Author</figcaption></figure><p>In conclusion, our implementation of the DDPG algorithm, combined with carefully chosen hyperparameters and neural network architecture, effectively solved the Reacher environment. By sharing experiences and learning collectively, the agents were able to adapt their behavior and achieve the desired performance in the task. This project showcases the potential of reinforcement learning algorithms in continuous control problems and opens up exciting possibilities for future research and development.</p><h4>Ideas for future work</h4><p>Despite the success in solving the Reacher environment, there is still room for further improvement and optimization. Here are some ideas for future work:</p><ol><li><strong>Hyperparameter tuning:</strong> The hyperparameters in this project were chosen based on a combination of recommendations from the literature and empirical testing. Further optimization through systematic hyperparameter tuning could lead to even better performance.</li><li><strong>Parallel training with more agents:</strong> In this project, we used 20 agents to collect experiences simultaneously. Investigating the impact of using more agents on the overall learning process could potentially lead to faster convergence or improved performance.</li><li><strong>Batch normalization:</strong> To further enhance the learning process, it is worth exploring the implementation of batch normalization in the neural network architecture. By normalizing the input features at each layer during training, batch normalization can help reduce internal covariate shift, accelerate learning, and potentially improve generalization. Incorporating batch normalization into the Actor and Critic networks may lead to more stable and efficient training, allowing the agent to reach even higher levels of performance in the Reacher environment.</li></ol><h3>References</h3><ol><li>Lillicrap, T. P., Hunt, J. J., Pritzel, A., Heess, N., Erez, T., Tassa, Y., Silver, D., &amp; Wierstra, D. (2015). Continuous control with deep reinforcement learning. <a href="https://arxiv.org/abs/1509.02971">link</a></li><li>Sutton, R. S., &amp; Barto, A. G. (2018). Reinforcement learning: An introduction. MIT press. <a href="http://incompleteideas.net/book/RLbook2018.pdf">link</a></li><li>Mnih, V., Kavukcuoglu, K., Silver, D., Rusu, A. A., Veness, J., Bellemare, M. G., … &amp; Hassabis, D. (2015). Human-level control through deep reinforcement learning. Nature, 518(7540), 529–533. <a href="https://www.nature.com/articles/nature14236">link</a></li><li>Udacity Deep Reinforcement Learning Nanodegree. <a href="https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893">link</a></li><li>Barth-Maron, G., Hoffman, M. W., Budden, D., Dabney, W., Horgan, D., TB, D., &amp; Lillicrap, T. (2018). Distributed Distributional Deterministic Policy Gradients. arXiv preprint arXiv:1804.08617. <a href="https://arxiv.org/pdf/1804.08617.pdf">link</a></li></ol><p>Thanks for Reading!</p><p>If you like the content and want to support me, you can buy me a coffee:</p><p><a href="https://www.buymeacoffee.com/cassimiro">Gabriel Cassimiro is a Data Scientist sharing free content to the community</a></p><p>Here are a few other articles you might be interested in:</p><ul><li><a href="https://towardsdatascience.com/solving-unity-environment-with-deep-reinforcement-learning-836dc181ee3b">Solving Unity Environment with Deep Reinforcement Learning</a></li><li><a href="https://towardsdatascience.com/object-detection-with-tensorflow-model-and-opencv-d839f3e42849">Object detection with Tensorflow model and OpenCV</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2718222c333e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/a-deep-dive-into-the-ddpg-algorithm-for-continuous-control-2718222c333e">A Deep Dive into the DDPG Algorithm for Continuous Control</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Unity Environment with Deep Reinforcement Learning]]></title>
            <link>https://medium.com/data-science/solving-unity-environment-with-deep-reinforcement-learning-836dc181ee3b?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/836dc181ee3b</guid>
            <category><![CDATA[dqn]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-reinforcement]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 18:19:49 GMT</pubDate>
            <atom:updated>2023-02-20T18:19:49.394Z</atom:updated>
            <content:encoded><![CDATA[<h4>End to End Project with code of a PyTorch implementation of Deep Reinforcement Learning Agent</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W93bKVDeFPuL793doDZlZQ.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@tetrakiss?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Arseny Togulev</a> on <a href="https://unsplash.com/pt-br/s/fotografias/robot?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Unity is a popular game development engine that allows developers to create games with stunning graphics and immersive gameplay. It is widely used for developing games across various platforms, including mobile, PC, and consoles. However, creating intelligent and challenging game environments is a challenging task for game developers. This is where Deep Reinforcement Learning (DRL) comes into play.</p><p>DRL is a subset of machine learning that combines deep learning and reinforcement learning. It is a powerful technique that has been used to solve complex tasks in various domains, including robotics, finance, and gaming. In recent years, DRL has become a popular approach to building intelligent game agents that can learn from experience and adapt to new situations.</p><p>In this post, we will explore how DRL can be used to solve Unity game environments. We will go through an implementation of DRL in the Unity environment to collect Bananas. We will also explore some of the challenges associated with using DRL in game development and how these challenges can be overcome.</p><p>This was a project for the Deep Reinforcement Learning specialization from Udacity. The full project and code can be found on this <a href="https://github.com/gabrielcassimiro17/rl-dqn-collect-bananas">Github repo</a>.</p><h4>Objective</h4><p>This project has the objective to train an Agent using Deep Q Learning. The agent will be trained to collect yellow bananas while avoiding blue bananas from Unity’s Banana Collector environment.</p><p>More information about the Unix environment can be found <a href="https://github.com/Unity-Technologies/ml-agents/blob/main/docs/Learning-Environment-Examples.md#banana-collector">here</a>. The agent was trained using a Deep Q Learning algorithm and was able to solve the environment in 775 episodes.</p><h4>Enviroment &amp; Task</h4><p>The environment consists in a square world with yellow and blue bananas. The agent has the objective to collect as many yellow bananas as possible while avoiding the blue ones. The agent has 4 possible actions: move forward, move backward, turn left and turn right.</p><p>The state space has 37 dimensions and contains the agent’s velocity, along with ray-based perception of objects around the agent’s forward direction. A reward of +1 is provided for collecting a yellow banana, and a reward of -1 is provided for collecting a blue banana.</p><p>The task is episodic, and in order to solve the environment, the agent must get an average score of +13 over 100 consecutive episodes.</p><p>The env looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ZJezBP0mdDudLtgtbbuJuA.gif" /><figcaption>Image by author</figcaption></figure><h4><strong>The Agent</strong></h4><p>To solve the problem given by the environment it was implemented a Deep Q Learning algorithm. The algorithm is based on the paper <a href="https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf">Human-level control through deep reinforcement learning</a> by DeepMind.</p><p>The algorithm works by using a neural network to approximate the Q-Function. The neural network receives the state as input and outputs the Q-Value for each action. Then it uses the Q-Value to select the best action to be taken by the agent. The algorithm learns by using the Q-Learning algorithm to train the neural network. There are also two problems with a simple implementation of the algorithm: correlated experiences and correlated targets. The algorithm uses two techniques to solve these problems: Experience Replay and Fixed Q-Targets.</p><p><strong>Correlated experiences</strong></p><p>Correlated experiences refer to a situation where the experiences (or transitions) of an agent are correlated with each other, meaning they are not independent and identically distributed. This can lead to an overestimation of the expected reward of a particular state or action, resulting in poor performance or convergence to suboptimal policies.</p><p>To solve this problem it is used a technique called <strong>Experience Replay</strong>. The technique consists in storing the experiences of the agent in a replay buffer and sampling randomly from it to train the neural network.</p><p><strong>Correlated targets</strong></p><p>Correlated targets refer to a situation where the target values used to update the policy are not independent of each other, leading to correlation in the learning signal. This can slow down or prevent convergence to the optimal policy.</p><p>To solve this problem it is used a technique called <strong>Fixed Q-Targets</strong>. The technique consists in using two neural networks: the local network and the target network. The local network is used to select the best action to be taken by the agent while the target network is used to calculate the target value for the Q-Learning algorithm. The target network is updated every 4 steps with the weights of the local network.</p><p>This is the implementation in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb8c697678a3ef4f8ad579b0503d2140/href">https://medium.com/media/bb8c697678a3ef4f8ad579b0503d2140/href</a></iframe><h4><strong>Neural network architecture</strong></h4><p>The neural network architecture used in the algorithm is a simple fully connected neural network with 2 hidden layers. The input layer has 37 neurons, the output layer has 4 neurons and the hidden layers have 64 neurons each. The activation function used in the hidden layers is ReLU and the activation function used in the output layer is the identity function.</p><p>The optimizer used for this implementation is Adam with a learning rate of 0.0005.</p><p>The library used to implement the neural network was PyTorch.</p><p>This was the implementation of the neural network:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3586476d0309506f9937b9664ec2ea9/href">https://medium.com/media/a3586476d0309506f9937b9664ec2ea9/href</a></iframe><h4>Training Task</h4><p>To train the agent we used a loop to interact with the environment, collect and learn from the experiences. One of the hyperparameters used in the training task was the number of episodes. This first hyperparameter was tuned manually trying to optimize the training time and the performance of the agent. The number of episodes used in the final implementation was 1200 however the env was solved in 775.</p><p>The second hyperparameter used in the training task was the number of steps per episode. This hyperparameter was also tuned manually trying to optimize the training time and the performance of the agent. The bigger the number of steps the more the agent can explore the environment but it increases a lot the training time. The number of steps per episode used in the final implementation was 1000.</p><p>Some other hyperparameters used:</p><ul><li>Replay buffer size: 1000</li><li>Batch size: 32</li><li>Update every: 4</li><li>Gamma: 0.99</li><li>Tau: 1e-3</li><li>Learning rate: 0.0005</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a221a65a5f5b8c225821646f018b558c/href">https://medium.com/media/a221a65a5f5b8c225821646f018b558c/href</a></iframe><p>With this, we were able to solve the environment in 775 episodes. The plot below shows the progress of the agent in obtaining higher rewards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*rUY3MMIG2JvCucu8QgRhqQ.png" /><figcaption>Image by Author</figcaption></figure><p>Here we can see the rewards increase as the agent improves. The tradeoff between <strong>exploration and exploitation</strong> is also visible in the plot, where the agent explores more in the first 200 episodes and then starts to exploit the environment and get higher rewards.</p><p>The full implementation can be found on this <a href="https://github.com/gabrielcassimiro17/rl-dqn-collect-bananas">GitHub repo</a>.</p><p>While we were able to solve the environment, there are a few improvements that can be applied to speed up the solution.</p><h4><strong>Future improvements</strong></h4><p>The algorithm can be improved by using the following techniques:</p><ul><li>Dueling DQN — <a href="https://arxiv.org/pdf/1511.06581.pdf">paper</a></li><li>Prioritized Experience Replay — <a href="https://arxiv.org/pdf/1511.05952.pdf">paper</a></li></ul><p>Another possible improvement is to work with pixel data from the environment. These improvements will likely be a topic for a new article, and I intend on going deeper into the core concepts and implementing the NN with TensorFlow.</p><p>Thanks for Reading!</p><p>Here are a few other articles you might be interested:</p><ul><li><a href="https://towardsdatascience.com/object-detection-with-tensorflow-model-and-opencv-d839f3e42849">Object detection with Tensorflow model and OpenCV</a></li><li><a href="https://towardsdatascience.com/how-to-prepare-for-the-gcp-professional-machine-learning-engineer-exam-b1c59967355f">How to prepare for the GCP Professional Machine Learning Engineer exam</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=836dc181ee3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/solving-unity-environment-with-deep-reinforcement-learning-836dc181ee3b">Solving Unity Environment with Deep Reinforcement Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting my Next Workout with Machine Learning- Part 1]]></title>
            <link>https://medium.com/data-science/predicting-my-next-workout-with-machine-learning-part-1-2fdb07f9ded2?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fdb07f9ded2</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[apple-health]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[apple-watch]]></category>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Tue, 12 Jul 2022 05:58:35 GMT</pubDate>
            <atom:updated>2022-07-30T17:14:34.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>Predicting My Next Workout with Machine Learning | Part 1: The Data</h3><h4>End-to-end phyton project looking at exercise data from an Apple Watch, from data collection to model deployment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kvjfEqW3rKMOuibxHJOUA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@blocksfletcher?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Blocks Fletcher</a> on <a href="https://unsplash.com/s/photos/apple-watch-exercise?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this series of posts, I will go through all steps of an end-to-end machine learning project. From data extraction and preparation to the deployment of the model using an API and finally to the creation of a front end to actually solve the problem helping with decisions. The main topics of each one are:</p><ol><li>Project setup, Data Processing, and Data Exploration</li><li>Model Experimenting</li><li>Model Deployment</li><li>Data App creation</li></ol><p>So let’s begin with the first part:</p><h3>Project setup, data exploration &amp; data processing</h3><p>The first and most crucial part of any project is clearly defining what problem you are solving. If you don’t have a clear definition of it, you should probably go back and brainstorm why you came up with that idea and if this is really a problem not only for you. There are a lot of methodologies in the product area that I won’t enter in this article to help in this step. For now, we will only focus on defining the current problem.</p><h4>The Problem</h4><p>Just like most people, I hope, I have a hard time staying fully motivated to work out every day. A tool that helps me sometimes is having a smartwatch to track my progress and help with features such as seeing friends&#39; workouts and competitions. However, they are not enough and I still have ups and downs in my motivation. That’s why I, as a Data Scientist, want to study my past workouts to figure out what the main variables that have motivated me in the past are, and to predict my probability of reaching my exercise goals in the future.</p><p>Defining it in one sentence we have:</p><blockquote>My problem is maintaining motivation to work out for a long period of time</blockquote><p>Now that we have defined what problem we want to solve, we can start setting up our project and our solution.</p><h4>Project Setup</h4><p>In a regular Data Science project, there are a couple of initial steps that we must follow.</p><ol><li>Git repository setup</li><li>Infrastructure provisioning</li><li>Environment setup</li></ol><p>Being able to create versions of your project and your code is very important in any software project. So our first step will be creating a GitHub Repository in order to store and create versions of your code. Another interesting feature of GitHub is the capability of sharing and contributing to other people&#39;s code.</p><p>I will not go step by step on how to create a repository; just type “How to create a Github Repository” and you’ll be good to go. For this project, I am using <a href="https://github.com/gabrielcassimiro17/apple-health-project">this repository</a>.</p><p>The second part is provisioning infrastructure on the cloud to develop and later deploy your solution. For now, I will not need a cloud infrastructure because the data volume fits nicely in my laptop for this initial analysis. When we dive into creating experiments and tuning our Hyper Parameters I will show you how to do this on Google Cloud Platform, specifically using Vertex AI.</p><p>The last part is creating a virtual environment to develop. I like to use pyenv for this job. To install pyenv <a href="https://github.com/pyenv/pyenv#installation">look here</a>. Lastly, there are a lot of OS that you can use, but I personally prefer using a Unix based such as MacOS or if you have Windows you can install a<a href="https://docs.microsoft.com/en-us/windows/wsl/install"> windows subsystem for Linux</a>. Another part of the environment is keeping track of your libraries via the requirements.txt file. There is an example in the <a href="https://github.com/gabrielcassimiro17/apple-health-project">GitHub repository of the project</a>.</p><h4>The data</h4><p>Now, to get the data that we need we have to export the data from the Health App on an iPhone. This is really easy to do, so just<a href="https://support.apple.com/guide/iphone/share-your-health-data-iph5ede58c3d/ios#:~:text=data%20between%20apps.-,Tap%20your%20profile%20picture%20or%20initials%20at%20the%20top%20right,method%20for%20sharing%20your%20data."> look here</a> at how to do it.</p><p>Now we can (finally) start coding.</p><p>The export file comes as a zip containing a folder inside with routes, electrocardiograms, and an XML with all your health data. The code below will unzip the folder, parse the XML and save it as a CSV.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fcdffddb4031e5a41b9465280245d37/href">https://medium.com/media/5fcdffddb4031e5a41b9465280245d37/href</a></iframe><p>This is the first part of our data processing pipeline. If we wish to share this functionality or simply add newer data, having a code structured to process the data is essential. Note that the code is structured as a function. This will give us flexibility and modularity in our pipeline.</p><p>Now we have the following data frame <strong>ready to be modeled</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDy8JTUNdgJNVAqiOfTYBQ.png" /><figcaption>Image by Author</figcaption></figure><p>Haha, just kidding.</p><p>In real life, the data is almost never ready to use like a Kaggle Dataset. In this case, we have problems with data formats, metadata entries are stored inside lists, and dates have to be converted, just to name a few of the things we have to deal with this first.</p><p>What was done:</p><ol><li>Filter only Exercise minutes data</li><li>Transform dates to DateTime format</li><li>Transform values to float</li><li>Create a date column without time, only with days</li><li>Group the value for Exercise minutes for each day</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae91eda68658115f81bbb1fb70eb7bc8/href">https://medium.com/media/ae91eda68658115f81bbb1fb70eb7bc8/href</a></iframe><p>Now we have a time series of our Exercise Minutes for each day. I selected Exercise Minutes instead of Burned Calories because this measures the days that I worked out instead of the calories spent. This is what we call a premise of the project. It is very important to keep track of these premises documenting them along with the problem statement.</p><p>Ok, we are making some progress now. So now we can begin creating models, right?</p><p>We have just a couple more things to do before that. First, we need to check the quality of the data, then we will create some features and do some exploratory plots to generate some insights before the modeling.</p><h4>Data Quality check</h4><p>When we talk about data quality we should go as deep as how the data is collected and think of some problems that can happen in the process. Since this data is collected on my Apple Watch, the first thing we should explore is what happens on the days I did not wear my watch?</p><p>This boils down to two things we always have to check in our data:</p><ol><li>Missing data</li><li>Outliers</li></ol><p>There is no missing data in terms of NAs. However, there are 167 observations with 0 as the number of exercise minutes, this appears to be the way they register days without the watch. We can clearly see it in this histogram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*3B3-jBOSp0pLTqeSGnFKzA.png" /><figcaption>Image by Author</figcaption></figure><p>Searching for outliers we can see that there is a couple of them, but we will keep them because they are accurate to the reality, not anomalies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Sn6bBePdu9Fr_QwDbVJV-A.png" /><figcaption>Image by Author</figcaption></figure><p>There are a lot of other checks we can do to verify data quality, but for this case, we will not go into them because this data source is standardized and pretty reliable.</p><p>Some important information we gathered from the data:</p><ol><li>There are 1.737 observations (days);</li><li>167 observations have 0 as the exercise minutes of that day;</li><li>The dates go from 2017–09–25 to 2022–06–27;</li><li>There are no missing dates in this range.</li></ol><h4>Feature Engineering</h4><p>Now we can get on some fun stuff. The feature engineering step is where we create hypotheses of what features can be useful to the model. This is an iterative process so we will create some here, validate them later and add or remove features.</p><p>Some guesses that I have came from classic time-series features. They are:</p><ol><li>Date attributes (day, weekday, month, year, season)</li><li>Lag features (how many calories were spent in the last period)</li><li>Rolling Window features (moving average, standard deviation, max, min)</li></ol><p>In the next part, we will add some other data such as sleep quality.</p><p>Here&#39;s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38212ca8304e9eee7881f96c5febea23/href">https://medium.com/media/38212ca8304e9eee7881f96c5febea23/href</a></iframe><p>Another important transformation was creating a circular encoding of the month feature. This is a great trick to encode time features that have a cycle. This works by getting the sine and cosine for each month and in the end, we have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uTAjR7eeP0Cnpa133qYSA.jpeg" /><figcaption>Image by Author</figcaption></figure><p>We can see that December and January are much closer to each other instead of being 1 and 12 which are farther apart.</p><h4>Exploratory Analysis</h4><p>Now we’ll go into some simple, but powerful analysis. This step can and often should be performed before the feature engineering, but in this case, I needed some features for the plots.</p><blockquote>Remember: This is an iterative process</blockquote><p>In a long project, you&#39;ll go into these steps in many cycles before arriving at the final solution.</p><p>We already looked at the distribution of our data in a previous step, so now we can see how the minutes of exercise vary with some temporal features.</p><p>Let’s start with the years:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*YOiq-oSsub5p_2UHiDx6EA.png" /><figcaption>Image by Author</figcaption></figure><p>We can see that 2020 stopped my trend mainly because of lockdowns from the COVID pandemic.</p><p>We can compare the distribution of the data by each month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFoVWcvfY5-fFi7Mw1fzPQ.png" /><figcaption>Image by Author</figcaption></figure><p>Here we can clearly see that December is not my best friend. The main causes are easy to identify: end-of-year parties, holidays, Christmas, and I usually go on vacation.</p><p>One more nice thing to look at is how my workouts vary across different days of the week. For this analysis, we consider Monday as label 0 and Sunday as label 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZewKzAljBOTKQBBjuoncxA.png" /><figcaption>Image by Author</figcaption></figure><p>The median of exercise minutes is not that far from the other days of the week however, it is rarer to have big workouts on the weekend.</p><p>There are literally infinite visualizations you can create with your data. For now, we will stop at those above. The important thing here is to understand your data, the distributions, and how it behaves in different aggregations.</p><p>You can also create <strong>decisions</strong> based on those analyses. One example here is looking at the weekend data trend to be lower. A possible decision is to create a rule that I can only drink on the weekends if I work out.</p><p>The last thing we’ll do before the modeling is decomposing our time series. Oh, I forgot to mention but what we have here is a time series. Here&#39;s the definition:</p><blockquote>A Time Series is a series of repeated observations considered within a certain time interval that are taken at equal (regular/evenly spaced) time intervals</blockquote><p>We can decompose a time series to understand two very useful things:</p><ol><li>Trend</li><li>Seasonality</li></ol><p>A time series consists of the joining of those two with some residuals. There are a couple of methods to decompose it, here we will use the additive method. Time series is a huge subject, so if you want to go deeper <a href="https://www.machinelearningplus.com/time-series/time-series-analysis-python/">go here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-Isy2Z2HFxjA5yVkui5uA.png" /><figcaption>Image by Author</figcaption></figure><p>So that&#39;s a lot of information, let’s dig into it.</p><p>The first plot is the original time series. The second one is the trend component, the third is the seasonality and the last one is the residuals.</p><p>The important information that we get from her is:</p><ol><li>We can identify a seasonality that can be related to the weeks, but not so much between months;</li><li>The residuals appear to be uniformly distributed.</li></ol><p>That helps us with two things. In the feature engineering step, we created features to capture the correct seasonality and if we wanted to apply classic time series models we would have to insert that seasonality in the parameters.</p><p>That is it for now.</p><h4>Key Takeaways</h4><p>The main takeaways of this part are:</p><ol><li><strong>DEFINE THE PROBLEM</strong>;</li><li>Set your environment up not forgetting to record your packages versions;</li><li>Record your project <strong>premisses</strong>;</li><li>Structure your data processing into <strong>functions</strong> that can be reused further down the road with new data;</li><li>Understand and clean your data;</li><li>If possible create some descriptive analysis that can already generate decisions.</li></ol><h4>In the next part:</h4><ol><li>We will set up an experimenting framework with MLFlow to record and compare our models</li><li>We will create multiple models and compare them</li><li>We will choose a model and optimize its hyperparameters</li></ol><p>Thanks for reading!</p><p>If you liked this article you can take a look at some other projects I’ve done <a href="https://gabrielcassimiro17.medium.com/">here</a>.</p><p>Also, consider subscribing to get all the parts of this series when they come out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fdb07f9ded2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/predicting-my-next-workout-with-machine-learning-part-1-2fdb07f9ded2">Predicting my Next Workout with Machine Learning- Part 1</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to prepare for the GCP Professional Machine Learning Engineer exam]]></title>
            <link>https://medium.com/data-science/how-to-prepare-for-the-gcp-professional-machine-learning-engineer-exam-b1c59967355f?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1c59967355f</guid>
            <category><![CDATA[gcp-certification]]></category>
            <category><![CDATA[certification]]></category>
            <category><![CDATA[exam-preparation]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[machine-learning-engineer]]></category>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 16:58:36 GMT</pubDate>
            <atom:updated>2022-01-10T16:58:36.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yY3Fdrn68ooXww9NE1JuQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Thought Catalog</a> on <a href="https://unsplash.com/s/photos/study?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Courses review, study tips, and how I did it</h4><p>So I decided to take the GCP Professional Machine Learning Engineering (PMLE) test but I had only 2 months to do it in order to attain enough certifications to my company be a GCP partner. I knew this was going to be a hard challenge but I jumped at it anyway.</p><p>In this post, I will share what helped me study and prepare for the test and also stuff you should not waste your time with. Also reading feedbacks like this one helps get different perspectives about the exam, so I will start with <a href="https://github.com/sathishvj/awesome-gcp-certifications/blob/master/professional-machine-learning-engineer.md">this great repository</a> that has posts about a lot of GCP and other certifications. I recommend reading it before beginning your studies.</p><p>As is usual in this kind of post, this is my certification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5km_w0xv9itkXsrRZx0DNA.png" /></figure><h3>Test Feedback</h3><p>The certification exam for Professional Machine Learning Engineer is considered one of the hardest GCP certifications because of two main reasons: The content is very extensive and most questions have more than one correct answer but only one best possible answer.</p><p>The test covers how to solve real-world business problems using Machine Learning techniques and how to use the best available solutions (offered by GCP obviously) in the correct context.</p><p>Knowing what the test covers is the most important part of the study because with this information you can focus on what matters when watching courses. So the first thing you should do is read carefully the <a href="https://cloud.google.com/certification/machine-learning-engineer">official GCP certification site</a>. There you’ll find information on what is covered on the exam, rules, where to take your exam and other important stuff.</p><p>Another great starting point is to do these <a href="https://docs.google.com/forms/d/e/1FAIpQLSeYmkCANE81qSBqLW0g2X7RoskBX9yGYQu-m1TtsjMvHabGqg/viewform">sample questions provided by Google</a> to see without any study how you would perform in the test. From there you can focus on studying and paying more attention to what you don&#39;t know.</p><h3>Previous experience recommendation</h3><p>The <a href="https://cloud.google.com/certification/machine-learning-engineer">official exam</a> guide doesn&#39;t demand any prerequisites however, it recommends:</p><blockquote>3+ years of industry experience including 1 or more years designing and managing solutions using Google Cloud.</blockquote><p>That is far from my case. By the time I took the exam, I had almost one year of cloud experience (AWS) and less than one month of experience with GCP. So I will give my opinion here about that recommendation:</p><p>Years don&#39;t dictate how much you know about something, but having a meaningful experience does. In my opinion, if you have some experience with any cloud and understand the basics of the concept and products you&#39;re good to go.</p><p>Being a machine learning engineer requires you to solve problems using ML models, serving data to that model, and creating the means to generate value with that solution consistently.</p><p>In terms of machine learning, you will have to study a lot less if you have experience building models. If you know how to differentiate problems that need classification, recommendation, or regression models and know which cases you need a DNN or a basic Linear Regression, you will be able to focus your studies on the serving data to your model and predictions to users using GCP solutions part.</p><h4>Wrapping up the <strong>previous experience</strong> part:</h4><ul><li>You don&#39;t need 3+ years of experience, but having some experience with any cloud provider will save you time studying.</li><li>Having experience with machine learning is needed but just enough that you&#39;re able to create solutions using ML to business problems.</li><li>Hands-on experience using GCP is possible to obtain with some courses provided by Google, and is enough for you to take the test.</li></ul><h3>How to Study</h3><p>The main source of knowledge for this exam is a group of courses designed by Google and available on Coursera. However, not all courses have the same relevance regarding the exam content. That is why I will rank them and comment on each one below.</p><p>First, there are some techniques that I used for my preparation that are worth mentioning before starting on the courses. If you only care about the courses feel free to skip ahead, but this helped me a lot to absorb more of the relevant stuff.</p><p>The main thing you have to have on your head while doing the courses are:</p><blockquote>How to use GCP solutions and ML models to solve real business problems</blockquote><p>You need to know all GCP&#39;s ML and Data solutions, what they do, what are their strengths and weaknesses, and the use cases for each one.</p><p><strong>Remember:</strong> A lot of problems can be solved in different ways with a good result however, the test will ask you always for the <strong>best solution</strong>.</p><p>So I have two methods that helped me learn these characteristics while watching the courses:</p><h4>Flashcards</h4><p>I used flashcards to remember what each solution does, its characteristics, and use cases. Then I tried to study them a couple of times until I could explain all without looking at the answer.</p><p>This is a very rich technique because you write in the flashcard a brief explanation, exercising your ability to summarise. Then you try to do them with intervals of days, exercising your long-term memory, and lastly, try to explain it to someone to really see if you learned that concept.</p><p>I used and recommend using <a href="https://ankiweb.net/">Anki</a>, a free flashcard app.</p><h4>Mindmaps</h4><p>Another great method to organize the main concepts is creating mindmaps. This way you can easily link products and solutions with business problems and advantages.</p><p>Particularly I used <a href="https://mindmeister.com/">mind meister</a>, but there are a lot of great solutions for free.</p><h4>Courses</h4><p>Finally, we’ll take a look at the courses offered by Google and their content.</p><p><a href="https://www.coursera.org/professional-certificates/preparing-for-google-cloud-machine-learning-engineer-professional-certificate?"><strong><em>Preparing for Google Cloud Machine Learning Engineer Professional Certificate</em></strong></a></p><p>This is the main course for preparing and is of the utmost importance to watch them with your full attention.</p><p>It starts with some basics of cloud in <a href="https://www.coursera.org/learn/gcp-big-data-ml-fundamentals?specialization=preparing-for-google-cloud-machine-learning-engineer-professional-certificate"><em>Google Cloud Big Data and Machine Learning Fundamentals</em></a><em> </em>that you can skip if you have already worked with data solutions in GCP otherwise, you should do it because it gives a first view of the GCP data solutions. This is also one of the only courses of the bunch that shows data engineering solutions, so if you do not know them, just do it.</p><p>The second and third courses show some ML solutions and APIs offered by GCP. It is very important to remember what they do and their use cases.</p><p>The fifth, sixth, and seventh courses will dive deeper into ML solutions, Feature Engineering, and modeling products.</p><p>The last three courses will cover how to deploy and create effective ML pipelines with all the best practices. In my opinion, these are the most important courses (<a href="https://www.coursera.org/learn/gcp-production-ml-systems?specialization=preparing-for-google-cloud-machine-learning-engineer-professional-certificate">Production Machine Learning Systems</a>, <a href="https://www.coursera.org/learn/mlops-fundamentals?specialization=preparing-for-google-cloud-machine-learning-engineer-professional-certificate">MLOps Fundamentals</a>, and<a href="https://www.coursera.org/learn/ml-pipelines-google-cloud?specialization=preparing-for-google-cloud-machine-learning-engineer-professional-certificate"> ML Pipelines on Google Cloud</a>).</p><p>All of these courses offer Labs to implement the solutions in a real GCP environment. They are a great way of learning how things work and how to set them up.</p><p>Some Labs will have big Jupyter Notebooks with tons of code. In these situations, my tip is to focus on what is the code doing and <strong>don&#39;t worry about understanding and learning how to code it yourself.</strong> If in the future you need to implement the code yourself, just go to the open <a href="https://github.com/GoogleCloudPlatform/training-data-analyst">GitHub repository</a> provided by Google and remember the syntax.</p><h4>Wrapping up courses:</h4><ul><li>You should use Flashcards, Mindmaps, or other techniques to remember a lot of details about solutions.</li><li>The main focus of the test is MLOps and ML pipelines, however, do not discard data engineering knowledge and Machine Learning model-specific questions.</li><li>Do not focus on the code syntax, focus on what it does and its benefits.</li></ul><h3>Mock Tests</h3><p>Finally, you <strong>HAVE </strong>to do mock tests. This is crucial to check your knowledge and to learn how to read the questions.</p><h4>Answering questions</h4><p>This last part is what defines if you&#39;ll pass or not. The test is huge, with 60 questions and 120 minutes to do them, meaning you have 2 minutes per question. You have to read the questions looking for characteristics of the problem that will help you find the right solution. I will do an example here:</p><p><em>You work for a public transportation company and need to build a model to </em><strong><em>estimate delay times for multiple transportation routes</em></strong><em>. Predictions are</em><strong><em> served directly to users in an app in real-time.</em></strong><em> Because different seasons and population increases impact the data relevance, you will </em><strong><em>retrain the model every month</em></strong><em>. You want to follow Google-recommended best practices. How should you </em><strong><em>configure the end-to-end architecture</em></strong><em> of the predictive model?</em></p><ul><li><em>A. Configure Kubeflow Pipelines to schedule your multi-step workflow from training to deploying your model.</em></li><li><em>B. Use a model trained and deployed on BigQuery ML, and trigger retraining with the scheduled query feature in BigQuery.</em></li><li><em>C. Write a Cloud Functions script that launches a training and deploying job on AI Platform that is triggered by Cloud Scheduler.</em></li><li><em>D. Use Cloud Composer to programmatically schedule a Dataflow job that executes the workflow from training to deploying your model.</em></li></ul><p>In bold are the most relevant parts of the question. You have to pay attention to details like batch ou real-time, retraining, deploying, and the architecture. The last one is one of the most important because often they&#39;ll ask for No-code solutions, serverless, or even complete control over the infrastructure. This will define what is the best offering to resolve that specific request.</p><p>In this case, Kubeflow is the only answer with the ability to do end-to-end with deploying and retraining capabilities. So the answer is A.</p><p>Another good tip is after finding the most relevant information in the question, eliminate answers that are clearly wrong, so you can have fewer options to compare.</p><h4>Mock tests links</h4><p>I did a couple of mock tests, but they are not perfect. There are a lot of wrong answers in all of them, but here is the link and comment on each one:</p><p><a href="https://www.examtopics.com/exams/google/professional-machine-learning-engineer/">Exam Topics</a>: This was the best mock test I did. It does not have the correct answers given by the website however, all questions have a discussion where people present arguments for each possibility. This was a great source of new knowledge and helped me deeply.</p><p><a href="https://docs.google.com/forms/d/e/1FAIpQLSeYmkCANE81qSBqLW0g2X7RoskBX9yGYQu-m1TtsjMvHabGqg/viewform">Google Sample questions:</a> Now that you finished studying, you should revisit the first sample questions that you did at the beginning of your studies.</p><p>There are other paid preparation exams, but I cannot review them because I only did the free ones. These sites usually offer a couple of free sample questions, but the ones I did had weird answers which I did not agree with. So do them at your own risk.</p><p>If I had to do it again I would pay for the rest of the Exam Topics questions and focus only on the discussion when checking the correct answer.</p><p>Thanks for reading and good luck on your journey to become a GCP Certified Professional Machine Learning Engineer!</p><p>If you want to support my work you can Buy Me a Coffe:</p><p><a href="https://www.buymeacoffee.com/cassimiro">Gabriel Cassimiro is a Data Scientist sharing free content to the community</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1c59967355f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-prepare-for-the-gcp-professional-machine-learning-engineer-exam-b1c59967355f">How to prepare for the GCP Professional Machine Learning Engineer exam</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object detection with Tensorflow model and OpenCV]]></title>
            <link>https://medium.com/data-science/object-detection-with-tensorflow-model-and-opencv-d839f3e42849?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d839f3e42849</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Thu, 15 Jul 2021 20:44:12 GMT</pubDate>
            <atom:updated>2021-07-16T12:29:52.740Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Using a trained model to identify objects on static images and live video</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhW153TqnV7gndCsaDlu4w.jpeg" /><figcaption><a href="https://www.pexels.com/photo/close-up-photography-of-magnifying-glass-906055/">source</a></figcaption></figure><p>In this article, I’m going to demonstrate how to use a trained model to detect objects in images and videos using two of the best libraries for this kind of problem. For the detection, we need a model capable of predicting multiple classes in an image and returning the location of those objects so that we can place boxes on the image.</p><h3>The Model</h3><p>We are going to use a model from the <a href="https://tfhub.dev/">Tensorflow Hub</a> library, which has multiple ready to deploy models trained in all kinds of datasets and to solve all kinds of problems. For our use, I filtered models trained for object detection tasks and models in the TFLite format. This format is usually used for IoT applications, for its small size and faster performance than bigger models. I choose this format because I intend to use this model on a Rasberry Pi on future projects.</p><p>The chosen model was the <a href="https://tfhub.dev/tensorflow/efficientdet/lite2/detection/1">EfficientDet-Lite2 Object detection model</a>. It was trained on the COCO17 dataset with 91 different labels and optimized for the TFLite application. This model returns:</p><ol><li>The box boundaries of the detection;</li><li>The detection scores (probabilities of a given class);</li><li>The detection classes;</li><li>The number of detections.</li></ol><h3>Detecting Objects</h3><p>I’m going to divide this section into two parts: Detections on static images and detection on live webcam video.</p><h4>Static Images</h4><p>We will start by detecting objects in this image from Unsplash:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZCWfdsfcBIxMGtFphzzVg.jpeg" /><figcaption><a href="https://unsplash.com/photos/cckf4TsHAuw">source</a></figcaption></figure><p>So the first thing we have to do is load this image and process it to the expected format for the TensorFlow model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5c7cb8c0f935cc4036cce99b77b9084/href">https://medium.com/media/b5c7cb8c0f935cc4036cce99b77b9084/href</a></iframe><p>Basically, we used OpenCV to load and do a couple of transformations on the raw image to an RGB tensor in the model format.</p><p>Now we can load the model and the labels:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e94bcc8f707bf70a9aa389091a111766/href">https://medium.com/media/e94bcc8f707bf70a9aa389091a111766/href</a></iframe><p>The model is being loaded directly from the website however, you can download it to your computer for better performance on the loading. The text labels CSV is available on the <a href="https://github.com/gabrielcassimiro17/raspberry-pi-tensorflow">project repo</a>.</p><p>Now we can create the predictions and put in the image the boxes and labels found:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40b217f00b1287892ccb56ff48d257e0/href">https://medium.com/media/40b217f00b1287892ccb56ff48d257e0/href</a></iframe><p>Now if we run <em>plt.imshow(img_boxes) </em>we get the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*r5oiStcXbvdQprXTY9ocfQ.jpeg" /><figcaption><a href="https://unsplash.com/photos/cckf4TsHAuw">source</a> with modifications</figcaption></figure><h4>Live Webcam Video</h4><p>Now we can move on to detecting objects live using the webcam on your pc.</p><p>This part is not as hard as it seems, we just have to insert the code we used for one image in a loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a39aa1dc870cc4c37024b58fd50bee3c/href">https://medium.com/media/a39aa1dc870cc4c37024b58fd50bee3c/href</a></iframe><p>Then we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*RBAfSYHuSTJHpsx-rx9wrA.gif" /><figcaption>GIF by Author</figcaption></figure><p>We used VideoCapture from open cv to load the video from the computer webcam. Then we did the same processing that we used on the static image and predicted the labels and positions. The main difference is that the image input is continuous so we inserted the code inside a while loop.</p><p>All the code and notebooks used are in this repository:</p><p><a href="https://github.com/gabrielcassimiro17/raspberry-pi-tensorflow">gabrielcassimiro17/raspberry-pi-tensorflow</a></p><p>In the near future, I will load this into a raspberry pi to create some interactions using a model capable of detecting objects, and post the results here.</p><p>If you like the content and want to support me, you can buy me a coffee:</p><p><a href="https://www.buymeacoffee.com/cassimiro">Gabriel Cassimiro is a Data Scientist sharing free content to the community</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d839f3e42849" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/object-detection-with-tensorflow-model-and-opencv-d839f3e42849">Object detection with Tensorflow model and OpenCV</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transfer Learning with VGG16 and Keras]]></title>
            <link>https://medium.com/data-science/transfer-learning-with-vgg16-and-keras-50ea161580b4?source=rss-3692fb93d7e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ea161580b4</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[vgg16]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Gabriel Cassimiro]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 21:55:37 GMT</pubDate>
            <atom:updated>2021-06-17T20:02:36.128Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use a state-of-the-art trained NN to solve your image classification problem</h4><p>The main goal of this article is to demonstrate with code and examples how can you use an already trained CNN (convolutional neural network) to solve your specific problem.</p><p>Convolutional Networks are great for image problems however, they are computationally expensive if you use a big architecture and don’t have a GPU. For that, we have two solutions:</p><h4>GPUs</h4><p>GPUs are much more efficient to train NNs but they are not that common on regular computers. So that is where<strong> </strong><a href="https://research.google.com/colaboratory/"><strong><em>google colab</em></strong></a> come to save us. They offer virtual machines with GPUs up to 16 GB of RAM and the best part of it all: <strong>It is Free</strong>.</p><p>But even with those upgraded specs, you can still struggle when training a brand new CNN. That’s where Transfer Learning can help you achieve great results with less expensive computation.</p><h4>Transfer Learning</h4><p>So what is transfer learning?</p><p>To better explain that we must first understand the basic architecture of a CNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWkXtlUfhmIdIEZLAnoZ0g.png" /><figcaption>Image by Author</figcaption></figure><p>A CNN can be divided into two main parts: Feature learning and classification.</p><p><strong>Feature Learning</strong></p><p>In this part, the main goal of the NN is to find patterns in the pixels of the images that can be useful to identify the targets of the classification. That happens in the convolution layers of the network that specializes in those patterns for the problem at hand.</p><p>I’m not going deep into how this works underneath the hood, but if you want to dig deeper I highly recommend <a href="https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53"><strong><em>this article</em></strong></a> and<strong><em> </em></strong><a href="https://youtu.be/HGwBXDKFk9I"><strong><em>this amazing video</em></strong></a><strong><em>.</em></strong></p><p><strong>Classification</strong></p><p>Now we want to use those patterns to classify our images to their correct label. This part of the network does exactly that job, it uses the inputs from the previous layers to find the best class to your matched patterns in the new image.</p><p><strong>Definition</strong></p><p>So now we can define Transfer Learning in our context as utilizing the feature learning layers of a trained CNN to classify a different problem than the one it was created for.</p><p>In other words, we use the patterns that the NN found to be useful to classify images of a given problem to classify a completely different problem without retraining that part of the network.</p><p>Now I am going to demonstrate how you can do that with Keras, and prove that for a lot of cases this gives better results than training a new network.</p><h3>Transfer Learning With Keras</h3><p>I will use for this demonstration a famous NN called VGG16. This is its architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTuQrB_uw_xr2jzBqg2GUw.png" /><figcaption>Image by Author</figcaption></figure><p>This network was trained on the ImageNet dataset, containing more than 14 million high-resolution images belonging to 1000 different labels.</p><p>If you want to dig deeper into this specific model you can study <a href="https://arxiv.org/abs/1505.06798"><strong><em>this paper.</em></strong></a></p><h4>Dataset</h4><p>For this demonstration, I will use the <a href="https://www.tensorflow.org/datasets/catalog/tf_flowers">tf_flowers dataset</a>. Just as a reminder: The VGG16 network was not trained to classify different kinds of flowers.</p><p>This is what the data looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*5IUj-C5CSCAad4ptrH1ddA.png" /><figcaption>Image by Author</figcaption></figure><p>Finally…</p><h4>The Code</h4><p>First, we have to load the dataset from TensorFlow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1162af5f640b53efb4718309ab44d45/href">https://medium.com/media/d1162af5f640b53efb4718309ab44d45/href</a></iframe><p>Now we can load the VGG16 model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/758810859a173edcc91d1f893573e4d0/href">https://medium.com/media/758810859a173edcc91d1f893573e4d0/href</a></iframe><p>We use <em>Include_top=</em><strong><em>False </em></strong>to remove the classification layer that was trained on the ImageNet dataset and set the model as not trainable. Also, we used the preprocess_input function from VGG16 to normalize the input data.</p><p>We can run this code to check the model summary.</p><pre>base_model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*ygjmUShTBQvUkybf6woSSg.png" /><figcaption>Image by Author</figcaption></figure><p>Two main points: the model has over 14 Million trained parameters and ends with a maxpooling layer that belongs to the Feature Learning part of the network.</p><p>Now we add the last layers for our specific problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaf49eb09af8195fc3922be9e96152e1/href">https://medium.com/media/eaf49eb09af8195fc3922be9e96152e1/href</a></iframe><p>And compile and fit the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbb220cf759aaa352bc1d81bcd9aa8c7/href">https://medium.com/media/cbb220cf759aaa352bc1d81bcd9aa8c7/href</a></iframe><p>Evaluating this model on the test set we got a 96% Accuracy!</p><p>That’s it!</p><p>It is this simple. And it is kind of beautiful right?</p><p>How we can find some patterns in the world that can be used to identify completely different things.</p><p>If you want to check out the complete code and a jupyter notebook, here’s the GitHubrepo:</p><p><a href="https://github.com/gabrielcassimiro17/object-detection">gabrielcassimiro17/object-detection</a></p><h3>Extra: comparing to hand-made model</h3><p>To be sure that this approach can be better in both computational resources and precision I created a hand-made simple model for this problem.</p><p>This is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f6bb6572315e6f85c84fe61026cdf52/href">https://medium.com/media/1f6bb6572315e6f85c84fe61026cdf52/href</a></iframe><p>I used the same final layers and fit parameters to be able to compare the impact of the convolutions.</p><p>The accuracy of the hand-made model was 83%. Much worse than the 96% that we got from the VGG16 model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ea161580b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/transfer-learning-with-vgg16-and-keras-50ea161580b4">Transfer Learning with VGG16 and Keras</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>