<?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 Lucas Suryana on Medium]]></title>
        <description><![CDATA[Stories by Lucas Suryana on Medium]]></description>
        <link>https://medium.com/@lucaselbert?source=rss-10aa14045a3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zIzkd1_RlqY8iV7sBEfaXg.jpeg</url>
            <title>Stories by Lucas Suryana on Medium</title>
            <link>https://medium.com/@lucaselbert?source=rss-10aa14045a3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:25:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucaselbert/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[How to Run Debug in Visual Studio for C++]]></title>
            <link>https://lucaselbert.medium.com/how-to-run-debug-in-visual-studio-for-c-7ec660d4e985?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ec660d4e985</guid>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[cplusplus]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 21:22:42 GMT</pubDate>
            <atom:updated>2024-03-20T21:26:02.792Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>What is a debugger?</blockquote><p>Debugging plays a crucial role in software development. Debugger is a tool that allows us to stop the execution of our code in the preselected location, inspect the program’s state, and step through the code line by line.</p><p>In this article, I will use Visual Code Studio’s debugger with my C++ file.</p><blockquote>Steps to perform debugging in Visual Code Studio</blockquote><ol><li>Install C+/C++ Extension in your own Visual Code Studio</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbOVvHgoTpEDwYUZ1rG1LQ.png" /><figcaption>C/C++ Extension</figcaption></figure><p>2. Create a new folder, for instance, INTRO_CPP, and create a CPP file called test.cpp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_80oh6q36oKGHyLynMvWdw.png" /><figcaption>test.cpp</figcaption></figure><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>#include &lt;vector&gt;<br><br>int main() {<br>    std::vector&lt;std::string&gt; brothers;<br>    brothers.push_back(&quot;David&quot;);<br>    brothers.push_back(&quot;Ethan&quot;);<br>    brothers.push_back(&quot;Adam&quot;);<br><br>    for (int i = 0; i &lt; brothers.size(); i++) {<br>        std::string const&amp; brother = brothers[i];<br>        std::cout &lt;&lt; &quot;Hello &quot; &lt;&lt; brother &lt;&lt; &quot;!\n&quot;;<br>    }<br>}</pre><p>3. Run the code by executing ‘g++ test.cpp&quot; and then ‘./a.out’ on your terminal. If the code runs well, you will get the result as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDpsAiWBW70AEZKYXxPBiQ.png" /><figcaption>result of test.cpp</figcaption></figure><p>4. Now, we will select a part of the code that we want to inspect. To do this, click on the left side of the line number in the test.cpp file. For instance, if I want to evaluate line 13, click the left side until it shows the red dot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjBFh4DagvCm241xvtcB2Q.png" /><figcaption>red dot indicates line of code to inspect</figcaption></figure><p>5. Click Debug C/C++ file and choose “C/C++ g++ build and debug active file” to start the debugging process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPjLTtvFZhNOeGnwsFOTBg.png" /><figcaption>debug c/c++ file</figcaption></figure><p>6. If you do all the steps correctly, you will get the results as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBKXaHSqjiUqBqMhzJAIqQ.png" /><figcaption>debugging result</figcaption></figure><p>Below Variables, you can see that a variable called ‘brothers’ is created that consists of three strings: “David”, “Ethan”, and “Adam”. We can also see the values of ‘i: 0’ and ‘brother: ‘David’’ that indicate the first value of the loop. If we click the ‘Continue’ button, then it will continue the iteration process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3QzsXv3cy4tmHblya16kg.png" /><figcaption>continue button</figcaption></figure><p>You can also watch the video tutorial here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3zerBU_HGC8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3zerBU_HGC8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3zerBU_HGC8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/88ba008e9ff6f1d606aafffd694740ae/href">https://medium.com/media/88ba008e9ff6f1d606aafffd694740ae/href</a></iframe><p>Thanks for reading/watching!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ec660d4e985" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Steps of A*: A Step-by-Step Guide + Python code (part 2)]]></title>
            <link>https://lucaselbert.medium.com/unlocking-the-steps-of-a-a-step-by-step-guide-python-code-part-2-aa6fc191481d?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa6fc191481d</guid>
            <category><![CDATA[pyth]]></category>
            <category><![CDATA[shortest-path]]></category>
            <category><![CDATA[a-star-algorithm]]></category>
            <category><![CDATA[heuristic-function]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 23:16:08 GMT</pubDate>
            <atom:updated>2023-03-19T23:21:17.960Z</atom:updated>
            <content:encoded><![CDATA[<p>You can access Part 1 <a href="https://medium.com/@lucaselbert/unlocking-the-steps-of-dijkstra-a-step-by-step-guide-python-code-part-1-674f445f4580">here</a>. The first part explains how to solve the shortest path problem using the popular Dijkstra algorithm and provides code examples.</p><p><strong>A*</strong></p><p>Unlike Dijkstra’s algorithm, which explores all possible paths from the start node, the A* algorithm estimates the cost of the remaining path from the current node to the goal node using <strong><em>a heuristic function</em></strong>. The heuristic function is a way to make an educated guess about how far a current node is from the goal node, based on some known or estimated information. For example, if you are trying to find the shortest path between two cities, you might estimate the distance based on the straight-line distance between them or the average time it takes to travel between them.</p><p>By using a heuristic function, the A* algorithm can prioritize exploring the most promising paths toward the goal node instead of exploring all possible paths. This makes the algorithm faster and more efficient, especially when dealing with large or complex maps or graphs. We will see more detail about a heuristic function with the same example as <a href="https://medium.com/@lucaselbert/unlocking-the-steps-of-dijkstra-a-step-by-step-guide-python-code-part-1-674f445f4580">Part 1</a>.</p><p>Example:<br>We have a starting node A, depicted by the color yellow, and we want to find the shortest path to the goal node H, depicted in the color green.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vLfx6d2ccBAXWtFs.png" /><figcaption>Figure 1. Example of the graph</figcaption></figure><p>To solve this example with the A* algorithm, we need to define the heuristic function. In this case, we choose <strong>the total of the remaining edges from the starting node to the goal node</strong> as <strong>the heuristic function</strong>. Now, we will solve the problem with the following steps:</p><p><strong>Step 1 -&gt; | A<br></strong><em>Explanation:</em> Start with initial node A.</p><p><strong>Step 2 -&gt; A | B(A,1+3) C(A,2+2)<br></strong><em>Explanation:</em> We find the unvisited neighbors of node A, which are B and C, and put them to the right of the vertical line ‘|’. The values inside the parentheses represent the previous node and the cost to the neighbor node from initial node A plus the remaining edges from the neighbor node to the goal node. For example, if we have three remaining edges from node B to node H, which are B-&gt;D, D-&gt;G, and G-&gt;H, we add the total of the remaining edges inside node B. Similarly, if we have two remaining edges from node C to node H, which are C-&gt;E and E-&gt;H, we add the fewest remaining edges from the chosen node to the goal node. Finally, we put the previous node, which is A, to the left of ‘|’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4FtAx95LDByBBdml.png" /><figcaption>Figure 2. Illustration of <strong>A | B(A,1+3) C(A,2+2)</strong></figcaption></figure><p><strong>Step 3 -&gt; A B | C(A,2+2) D(B,3+2)<br></strong><em>Explanation:</em> Even though nodes B and C have the same cost value, we will choose node B as the next node because it has a lower cost to the neighbor compared to node C. Then we check the unvisited neighbor of node B, which is D, and put it to the right of the vertical line ‘|’. We have two remaining edges from node D to node H, which are D-&gt;G and G-&gt;H. Then we add the total of the remaining edges inside node D. Finally, we move the previous node, B, to the left of the &#39;|&#39; symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLQ37Ap62798MJyCTGFWcg.png" /><figcaption>Figure 3. Illustration of <strong>A B | C(A,2+2) D(B,3+2)</strong></figcaption></figure><p><strong>Step 3 -&gt; A B C | D(B,3+2) E(C,3+1) F(C,4+1)<br></strong><em>Explanation:</em> We will choose node C as the next node because it has the lowest cost compared to the other nodes. Next, we locate node C&#39;s unvisited neighbors, E and F, and place them to the right of the vertical line &#39;|&#39;. Calculate the remaining edges from nodes E and F to node H, and add them inside the parentheses of both nodes. Finally, we move the previous node, C, to the left of the ‘|’ symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_G7X6gHMfPLMnSwY1lc6w.png" /><figcaption>Figure 4. Illustration of <strong>A B C | E(C,3+1) D(B,3+2) F(C,4+1)</strong></figcaption></figure><p><strong>Step 4 -&gt; A B C E | D(B,3+2) F(C,4+1) H(E,6+0)<br></strong><em>Explanation:</em> We will choose node E as the next node because it has the lowest cost compared to the other nodes. Next, we locate node E’s unvisited neighbors, G and H. Drop G because we can directly reach to the goal from node E. Then, place H to the right of the vertical line ‘|’. We don’t need to calculate the remaining edge from node E to node H because the value is absolutely zero. Finally, we move the previous node, E, to the left of the ‘|’ symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyXe4b5ghoj3Zubn9Bw2hA.png" /><figcaption>Figure 5. Illustration of <strong>A B C E | D(B,3+2) F(C,4+1) H(E,6+0)</strong></figcaption></figure><p><strong>Step 5 -&gt; A B C E F | D(B,3+2) H(F,5)<br></strong><em>Explanation:</em> Omit node H because it is the goal. Then we will choose node F as the next node because it has the lowest cost compared to the other nodes. Next, we locate node F’s unvisited neighbor, H. Then, place H to the right of the vertical line ‘|’. We don’t need to calculate the remaining edge from node E to node H because the value is absolutely zero. Finally, we move the previous node, F, to the left of the ‘|’ symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZBK6eIyI6TmYmhCvLwEFQ.png" /><figcaption>Figure 6. Illustration of <strong>A B C E F | D(B,3+2) H(F,5)</strong></figcaption></figure><p><strong>Step 6-&gt; </strong>Choose the shortest path<br>We know that the shortest path to node H comes from node F because it has a lower cost compared to node E. We don’t need to calculate the cost from node D to node H because the cost will be at least 5, which means it will not give a more optimal solution. Last, we can trace back the previous nodes of node F until we reach the initial node A. The shortest path is A -&gt; C -&gt; F -&gt; H.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*FUFZfIgZwqAZ70yh.png" /><figcaption>Figure 6. The shortest path</figcaption></figure><p><strong>The advantages of A* over Dijkstra<br></strong><em>Do you realize how many steps we need to take to solve the shortest distance problem with A*?</em></p><p>In fact, the A* algorithm can solve this problem in as few as six steps, while Dijkstra’s algorithm requires nine steps to solve the same problem. This efficiency is made possible by the heuristic function used in A*, which allows for a guided-search approach that can quickly identify the most promising paths to explore. This makes A* a highly effective algorithm for solving a wide range of shortest-path problems, from navigation to logistics and beyond.</p><p><strong>Python Code</strong></p><p>In order to use the A* algorithm in Python, the initial step is to establish the graph. To accomplish this, a file named graph.csv can be utilized, which is displayed in Figure 3 and contains the representation of the graph. The file contains rows that display a specific edge, including the starting node, its neighbor node, and the cost associated with traveling from the starting node to the neighbor node.</p><pre>A,B,1<br>A,C,2<br>B,D,2<br>C,D,1<br>C,E,1<br>C,F,2<br>D,G,1<br>F,E,1<br>F,H,1<br>E,G,1<br>E,H,3<br>G,H,3</pre><p>To obtain the representation of the graph shown in graph.csv, a function called read_graph_from_csv() needs to be created. If we run the code below, we will get the representation of the graph as follows:</p><pre>import csv<br><br>def read_graph_from_csv(filename):<br>    graph = {}<br>    with open(filename) as f:<br>        reader = csv.reader(f)<br>        for u, v, w in reader:<br>            if u not in graph:<br>                graph[u] = []<br>            if v not in graph:<br>                graph[v] = []<br>            graph[u].append((v, int(w)))<br>            graph[v].append((u, int(w)))<br>    return graph<br><br>graph = read_graph_from_csv(&#39;graph.csv&#39;)<br>graph</pre><pre>Output:<br>{&#39;A&#39;: [(&#39;B&#39;, 1), (&#39;C&#39;, 2)],<br> &#39;B&#39;: [(&#39;A&#39;, 1), (&#39;D&#39;, 2)],<br> &#39;C&#39;: [(&#39;A&#39;, 2), (&#39;D&#39;, 1), (&#39;E&#39;, 1), (&#39;F&#39;, 2)],<br> &#39;D&#39;: [(&#39;B&#39;, 2), (&#39;C&#39;, 1), (&#39;G&#39;, 1)],<br> &#39;E&#39;: [(&#39;C&#39;, 1), (&#39;F&#39;, 1), (&#39;G&#39;, 1), (&#39;H&#39;, 3)],<br> &#39;F&#39;: [(&#39;C&#39;, 2), (&#39;E&#39;, 1), (&#39;H&#39;, 1)],<br> &#39;G&#39;: [(&#39;D&#39;, 1), (&#39;E&#39;, 1), (&#39;H&#39;, 3)],<br> &#39;H&#39;: [(&#39;F&#39;, 1), (&#39;E&#39;, 3), (&#39;G&#39;, 3)]}</pre><p>Create a function A_star() with the input of the graph, the starting node, and the goal node. This function will produce the travel distances with the nodes it visits.</p><pre>def heuristic(node, goal, graph):<br>    remaining_edges = 0<br>    for neighbor, weight in graph[node]:<br>        if neighbor != goal:<br>            remaining_edges += 1<br>    return remaining_edges<br><br>def a_star(graph, start, goal, heuristic):<br>    distances = {node: float(&#39;inf&#39;) for node in graph}<br>    distances[start] = 0<br>    unvisited = set(graph.keys())<br>    previous = {node: None for node in graph}<br>    current = start<br>    while unvisited:<br>        for neighbor, weight in graph[current]:<br>            new_dist = distances[current] + weight<br>            if new_dist &lt; distances[neighbor]:<br>                distances[neighbor] = new_dist<br>                previous[neighbor] = current<br>        unvisited.remove(current)<br>        if current == goal:<br>            break<br>        candidates = {node: distances[node] + heuristic(node, goal, graph) for node in unvisited}<br>        current = min(candidates, key=candidates.get)<br>    return distances, previous<br><br>def shortest_path(previous, start, goal):<br>    node = goal<br>    path = [node]<br>    while node != start:<br>        node = previous[node]<br>        path.append(node)<br>    path.reverse()<br>    return path<br><br>graph = read_graph_from_csv(&#39;graph.csv&#39;)<br><br>start = &#39;A&#39;<br>goal = &#39;H&#39;<br><br>distances, previous = a_star(graph, start, goal, heuristic=lambda node, goal=goal, graph=graph: heuristic(node, goal, graph))<br>path = shortest_path(previous, start, goal)<br>print(&quot;Shortest path from node {} to node {}: {}&quot;.format(start, goal, path))</pre><pre>Shortest path from node A to node H: [&#39;A&#39;, &#39;C&#39;, &#39;F&#39;, &#39;H&#39;]</pre><p>If you have read this sentence, it means that you have successfully used A*’s algorithm to find the shortest path! Congratulations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa6fc191481d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Steps of Dijkstra: A Step-by-Step Guide + Python code (part 1)]]></title>
            <link>https://lucaselbert.medium.com/unlocking-the-steps-of-dijkstra-a-step-by-step-guide-python-code-part-1-674f445f4580?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/674f445f4580</guid>
            <category><![CDATA[dijkstra]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[easy]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 18:08:07 GMT</pubDate>
            <atom:updated>2023-02-09T18:08:07.124Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Have you ever wondered how a mapping platform like Google Maps is able to return the shortest routes to your destination? Or how do automated vehicles find the best routes to avoid obstacles?</blockquote><p>The secret lies in the power of graph search algorithms. A graph search algorithm is a method used in mathematics to traverse a graph and understand the relationships between its nodes. A graph is a data structure that consists of nodes and edges, where each edge may have a weight. An illustration of a graph with nodes and edges is shown in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vk9G24fHgz775FwASI55A.png" /><figcaption>Figure 1. A graph consists of several nodes and edges</figcaption></figure><p>If the concept of a graph is still too abstract, we can imagine the graph as a road network. This network consists of cities and connecting roads that represent nodes and edges. The length of the road between cities can be assumed as the weight of the edges. See Figure 2 to see the illustration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VjGr37W-dLVfgt3pQoDhw.png" /><figcaption>Figure 2. A road network connecting Semarang city and the surrounding cities</figcaption></figure><p>Given the task of finding the shortest path between two nodes, we need a search algorithm. In this article, we will learn how to solve the shortest path problem with two search algorithms: Dijkstra (part 1) and A* (part 2). I guarantee the reader of this article can solve the shortest path problem without fancy mathematical skills.</p><p><strong>Dijkstra</strong></p><p>In a nutshell, the Dijkstra algorithm starts at a specified starting node (in Figure 3, node “A” which is represented by the yellow node) and then iteratively selects the unvisited node with the lowest accumulated cost, which is defined as the sum of the edge weights along the path from the starting node to the current node. The algorithm continues this process until it reaches the goal node (in the example, node “H” which is represented by the green node).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oD2ctQ2WhCVcf7zYLXvKQg.png" /><figcaption>Figure 3. Example of graph</figcaption></figure><p>To solve this example, we will take several steps:</p><p><strong>Step 1 -&gt; | A<br></strong><em>Explanation:</em> Start with initial node A</p><p><strong>Step 2 -&gt; A | B(A,1) C(A,2)</strong><br><em>Explanation:</em> Find the unvisited neighbors of node A, which are B and C, then put them to the right of “|”. The values inside ( ) are respectively the previous node and the cost to the neighbor node from initial node A. Put the previous node, which is A, to the left of “|”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qK0WNNmxmP1okF5bvnbtkQ.png" /><figcaption>Figure 4. Illustration of <strong>A | B(A,1) C(A,2)</strong></figcaption></figure><p><strong>Step 3 -&gt; A B | C(A,2) D(B,3)</strong><br><em>Explanation:</em> Always start with the node from the right of “|” that has the lowest cost from initial node A, which is B. Find the unvisited neighbors of node B, which is D, then put it to the right of “|”. Put the previous node, which is B, to the left of “|”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NjipxwmQq11EiWyjBc6dCw.png" /><figcaption>Figure 5. Illustration of <strong>A B | C(A,2) D(B,3)</strong></figcaption></figure><p><strong>Step 4 -&gt; A B C | D(B,3) E(C,3) F(C,4)<br></strong><em>Explanation:</em> Always start with the node from the right of “|” that has the lowest cost from initial node A, which is C. Find the unvisited neighbors of node C, which are E and F, then put it to the right of “|”. We don’t choose D as the neighbor of C because we already visit D as the neighbor of B. Put the previous node, which is B, to the left of “|”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSvS87w_79U1pd8t1zmXOA.png" /><figcaption>Figure 6. Illustration of <strong>A B C | D(B,3) E(C,3) F(C,4)</strong></figcaption></figure><p><strong>Step 5 -&gt; A B C D | E(C,3) F(C,4) G(D,4)<br></strong><em>Explanation:</em> Always start with the node from the right of “|” that has the lowest cost from initial node A. In this case, both node D and node E have the same cost from the initial node A, so we can randomly pick one of them. Find the unvisited neighbors of node D, which is G, then put it to the right of “|”. Put the previous node, which is D, to the left of “|”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaGWS-dF-ppMqEsA1mWkBQ.png" /><figcaption>Figure 7. Illustration of <strong>A B C D | E(C,3) F(C,4) G(D,4)</strong></figcaption></figure><p><strong>Step 6 -&gt; A B C D E | F(C,4) G(D,4) H(E,6)<br></strong><em>Explanation:</em> Always start with the node from the right of “|” that has the lowest cost from initial node A, which is E. Find the unvisited neighbors of node E, which is H, then put it to the right of “|”. Put the previous node, which is E, to the left of “|”. In this situation, we have reached node H, but, we still have two uncovered nodes, which are F and G. Continue the step until we have no other nodes left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sh9LLz3Sr5lgJ2AuQRFvYw.png" /><figcaption>Figure 8. Illustration of <strong>A B C D E | F(C,4) G(D,4) H(E,6)</strong></figcaption></figure><p><strong>Step 7 -&gt; A B C D E F |G(D,4) H(F,5)<br></strong><em>Explanation:</em> Always start with the node from the right of “|” that has the lowest cost from initial node A. In this case, both node F and node G has the same cost from the initial node A, so we can randomly pick one of them. Find the unvisited neighbors of node F, which is H, then put it to the right of “|”. Put the previous node, which is F, to the left of “|”. In this situation, we have reached node H from two different nodes. Remove node H(E,6) because it has a higher cost compared to H(F,5). As we still have the last uncovered node, which is G, continue the step until we have no other nodes left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDI1vg5kOfg5jsWo-9cp6w.png" /><figcaption>Figure 9. Illustration of <strong>A B C D E F |G(D,4) H(E,6) H(F,5)</strong></figcaption></figure><p><strong>Step 8 -&gt; A B C D E F G | H(F,5)<br></strong><em>Explanation:</em> Always start with the node from the right of “|” that has the lowest cost from initial node A. Find the neighbors of node G, which is H, then put it to the right of “|”. Put the previous node, which is G, to the left of “|”. In this situation, we have reached node H and we have no uncovered node left. Choose the pair of nodes that has the lowest cost, which is H(F,5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpjEDJ8fTOWWlIVNK4tGIA.png" /><figcaption>Figure 10. Illustration of <strong>A B C D E F G | H(G,7) H(E,6) H(F,5)</strong></figcaption></figure><p><strong>Step 9 -&gt; </strong>Choose the shortest path<br>As we know that the shortest path comes from node H(F,5), we can trace back the previous node until we reach the initial node A. The shortest path is A -&gt; C -&gt; F -&gt; H.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5h_zs7b2wCqIvYqbTdVHA.png" /><figcaption>Figure 11. The shortest path</figcaption></figure><p>To implement the Dijkstra algorithm in Python, we first need to define the graph. We can use a graph.csv file, shown below, to save the graph representation in Figure 3. Each row shows one edge with the following information: a starting node, a neighbor node, and the cost to travel from starting node to the neighbor node.</p><pre>A,B,1<br>A,C,2<br>B,D,2<br>C,D,1<br>C,E,1<br>C,F,2<br>D,G,1<br>F,E,1<br>F,H,1<br>E,G,1<br>E,H,3<br>G,H,3</pre><p>Create a function read_graph_from_csv() to read graph.csv and convert it to the graph representation. If we run the code below, we will get the representation of the graph as follows:</p><pre>import csv<br><br>def read_graph_from_csv(filename):<br>    graph = {}<br>    with open(filename) as f:<br>        reader = csv.reader(f)<br>        for u, v, w in reader:<br>            if u not in graph:<br>                graph[u] = []<br>            if v not in graph:<br>                graph[v] = []<br>            graph[u].append((v, int(w)))<br>            graph[v].append((u, int(w)))<br>    return graph<br><br>graph = read_graph_from_csv(&#39;graph.csv&#39;)<br>graph</pre><pre>Output:<br>{&#39;A&#39;: [(&#39;B&#39;, 1), (&#39;C&#39;, 2)],<br> &#39;B&#39;: [(&#39;A&#39;, 1), (&#39;D&#39;, 2)],<br> &#39;C&#39;: [(&#39;A&#39;, 2), (&#39;D&#39;, 1), (&#39;E&#39;, 1), (&#39;F&#39;, 2)],<br> &#39;D&#39;: [(&#39;B&#39;, 2), (&#39;C&#39;, 1), (&#39;G&#39;, 1)],<br> &#39;E&#39;: [(&#39;C&#39;, 1), (&#39;F&#39;, 1), (&#39;G&#39;, 1), (&#39;H&#39;, 3)],<br> &#39;F&#39;: [(&#39;C&#39;, 2), (&#39;E&#39;, 1), (&#39;H&#39;, 1)],<br> &#39;G&#39;: [(&#39;D&#39;, 1), (&#39;E&#39;, 1), (&#39;H&#39;, 3)],<br> &#39;H&#39;: [(&#39;F&#39;, 1), (&#39;E&#39;, 3), (&#39;G&#39;, 3)]}</pre><p>Create a function dijkstra() with the input of the graph, the starting node, and the goal node. This function will produce the travel distances with the nodes it visits.</p><pre>def dijkstra(graph, start, goal):<br>    distances = {node: float(&#39;inf&#39;) for node in graph}<br>    distances[start] = 0<br>    unvisited = set(graph.keys())<br>    previous = {node: None for node in graph}<br>    current = start<br>    while unvisited:<br>        for neighbor, weight in graph[current]:<br>            if neighbor in unvisited:<br>                new_dist = distances[current] + weight<br>                if new_dist &lt; distances[neighbor]:<br>                    distances[neighbor] = new_dist<br>                    previous[neighbor] = current<br>        unvisited.remove(current)<br>        if current == goal:<br>            break<br>        candidates = {node: distances[node] for node in unvisited}<br>        current = min(candidates, key=candidates.get)<br>    return distances, previous<br><br>def shortest_path(previous, start, goal):<br>    node = goal<br>    path = [node]<br>    while node != start:<br>        node = previous[node]<br>        path.append(node)<br>    path.reverse()<br>    return path<br><br>graph = read_graph_from_csv(&#39;graph.csv&#39;)<br>start = &#39;A&#39;<br>goal = &#39;H&#39;<br>distances, previous = dijkstra(graph, start, goal)<br><br>path = shortest_path(previous, start, goal)<br>print(&quot;Shortest path from node {} to node {}: {}&quot;.format(start, goal, path))</pre><pre>Output:<br>Shortest path from node A to node H: [&#39;A&#39;, &#39;C&#39;, &#39;F&#39;, &#39;H&#39;]</pre><p>If you have read this sentence, it means that you have successfully used Dijkstra’s algorithm to find the shortest path! Congratulations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=674f445f4580" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fundamental of Databases — part 2]]></title>
            <link>https://lucaselbert.medium.com/fundamental-of-databases-part-2-caf89ad19b88?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/caf89ad19b88</guid>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Fri, 22 Jul 2022 21:56:18 GMT</pubDate>
            <atom:updated>2022-07-23T07:18:26.907Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fundamental of Databases — part 2</h3><p>This is a summary of Databases System Concepts and Designs taught by Leo Mark from Georgia Tech</p><h4><strong>5. Outline major topics</strong></h4><p>Based on the definition of database and database management systems (DMS) from <a href="https://lucaselbert.medium.com/fundamental-of-databases-part-1-c5a7b576daf2">Fundamental of Databases — part 1</a> we will look at three major topics:</p><ul><li>Data Modeling</li><li>Process modeling</li><li>Database efficiency</li></ul><h4>6. Data modeling</h4><p>The model represents a perception of structures of reality. The data modeling process has two steps. <strong>First</strong>, to fix the perception of structures of reality. <strong>Second, </strong>to represent that perception. Database people use different languages for this. One language is the extended entity-relationship model, which is good for fixing a perception of structures of reality. And the other one is the relational model which is good for representing this perception inside a database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVTi5T0V6V_AxFs1fpLH3Q.png" /><figcaption>Data modeling</figcaption></figure><p>In the data modeling process, we select aspects of reality that are important to us while ignoring others and we use abstraction to organize these aspects.</p><h4>7. Process Modeling</h4><p>In process modeling, the aim is to fix and represent the perception of the process of reality. As opposed to the structured process which is not represented inside the database, they are reflected in the way we use the database through the database management systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxxOBegUyavJ1zkGYnw0Ww.png" /><figcaption>Process modeling</figcaption></figure><p>There are two ways in which we can use databases through database management systems. One is to embed data manipulation language code inside a program. The other one is to use the data manipulation language directly to issue ad-hoc (special for a certain purpose) queries on the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPkkkW4rTuOQ7QliX9y78w.png" /><figcaption>Embed DML code inside a program</figcaption></figure><p>Let’s look at the figure above. If we have a program that builds, for example, a user interface for an application, then inside of that program it is possible to have a data manipulation link (DML) with statements that access databases, either to update the data or to retrieve the data and to display it back through the interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ejbhBzwNcSj68eRm9WZMw.png" /><figcaption>Direct DML for querying</figcaption></figure><p>Alternatively, it is possible to use the data manipulation language directly which directly does ad hoc queries on the database or ad hoc updates and maintenance of the database.</p><h4>8. Data Models-Architecture DBMS Architecture</h4><ul><li><strong>Data models</strong><br>In order to do data modeling, we need to talk about a tool called a data model. Data models contain formulations to allow us to express data structures, constraints, and operations. Two major data models we’re going to talk about, namely, the extended entity-relationship model and the relational model.</li><li><strong>Database architecture<br></strong>And another important aspect I want to briefly talk about is database architecture. So, it turns out that a database and mode of the structure of reality act has several layers to it. We want to look at what are those layers. We also want to take a look at what the architecture of a database management system, to allow us to create such a database, would be. Specifically, we will look at ANSI/SPARC 3-Level database architecture and the corresponding database management system architecture.</li><li><strong>Metadata<br></strong>Finally, I want to mention metadata. What it is. Why it is so important to make everything else happen in a database. And now on a data structures.</li></ul><h4><strong>9. Examples of data models</strong></h4><p>A data model is not the same as a model of data. We define the database to be a model of structures of reality. A data model is a tool or the formulas that we use to create such a model. We should always be talking about the following three elements when talking about a data model: data structures, integrity constraints, and operations. Let me mention three examples of data models.</p><ul><li>The entity-relationship model. We will use this model to fix the perception of reality.</li><li>The relational model. We will implement this model in a database management system.</li><li>Hierarchical model. It was implemented in the first database system IBMIMS database system back in 1967. Interestingly the hierarchical model is also the fundamental model on XML databases today.</li></ul><h4><strong>10. Relational Model — Data Structures</strong></h4><p>A relational model is an example of a data model. With this, we can illustrate what data structures and constraints, and operations look like in that model. In the relational model, data is represented in tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ef-FcaX2P4E5fhTCVsGRpQ.png" /><figcaption>Example of the relational model</figcaption></figure><p>Look at the table above! The table name is RegularUser. Each column has the name: Email, BirthDate, Hometown, and Salary. Each of the columns has a data type. In this case, Email are represented by varchar(50), variable length character strings maximum length 50. BirthDate is represented over data time. Hometown, again in varchar(50). Salary is represented over the data type integer.</p><p>A table is set to have columns. In this case, there are four columns. The number of columns is also called the degree of the table. A relation also has a number of rows, in this case, seven rows in the table. The table name, column names, and data types together constitute the scheme of this table.</p><p>The schema represents aspects of the data that are stable over time. In other words, the schema is not expected to change. The state of the database represented by the rows in the table reflects aspect that is dynamic and change over time. So the idea is that whereas the scheme, in general, represents the structure of data, the rows will represent what is the current state of reality that’s modeled by this table.</p><h4>11. Relational Models — Constraints</h4><p>Constraints represent rules that cannot be expressed by the data structures we just looked at. For example:</p><ul><li><strong>We might want emails to be unique</strong>, as they are in this example. That would allow us to think about emails as representing unique regular users. So for each user out in the real world, there’s a corresponding row in this table here. It wouldn’t make sense if the email were null because that really doesn’t represent anything.</li><li><strong>We also need to constrain the birth data</strong> to be after 1/1/1900.</li><li>Finally, <strong>we might have a constraint</strong> that says that <strong>Hometown must be a city</strong> in the United States.</li></ul><p>Notice that none of these constraints are expressed by the table structure or the data types that the column values are pulled from. That’s why constraints express rules that are not expressed by the data structures alone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caf89ad19b88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fundamental of Databases — part 1]]></title>
            <link>https://lucaselbert.medium.com/fundamental-of-databases-part-1-c5a7b576daf2?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5a7b576daf2</guid>
            <category><![CDATA[dummies]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Thu, 21 Jul 2022 22:00:54 GMT</pubDate>
            <atom:updated>2022-07-23T07:29:52.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fundamental of Databases — part 1</h3><p>This is a summary of Databases System Concepts and Designs taught by Leo Mark from Georgia Tech.</p><h4>1. What is a database?</h4><p>A database is a model of reality. This definition raises two questions for us. <strong>First</strong>, why do we need to use models? <br><strong>Second</strong>, when is the exact time to use Database Management System to use such a model?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*9BhwePu42Y7ysdlkZBaLZw.png" /><figcaption>Database illustration</figcaption></figure><p>The answer to the first question is that we need a model as a representation of reality.</p><h4>2. A map is a model of reality</h4><p>Look at the wrong map of Indonesia on the left and the correct map of Indonesia on the right. What do you notice? The wrong map has the wrong color for islands in Indonesia (usually we use green to draw an island), the wrong size for several islands, and last, the wrong direction. The correct map has all the correct properties of a map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOgQpOjtQX0uwUVTYgIwFA.jpeg" /><figcaption>Wrong map: left and Correct map: right</figcaption></figure><h4>3. A Message to Model Makers</h4><p><strong>First</strong>, a model is a means of communication. <strong>Second</strong>, users of a model must have certain knowledge in common. To be remembered a model:</p><ul><li><strong>only emphasizes selected aspects of reality</strong><em><br></em>We only care about aspects that are useful to our purpose</li><li><strong>is described in some language</strong><em><br></em>We need to agree and understand the language we use in order to be able to communicate through the model</li><li><strong>can be erroneous</strong><em><br></em>We need to remember that model is never perfect.</li><li><strong>may have features that do not exist in reality</strong></li></ul><h4>4. What is Database Management System (DMS)?</h4><p>Database Management System is a software system that allows users to create and maintain a database.</p><h4>5. When to use and to not use DMS?</h4><p>Use DMS when the databases:</p><ul><li>have<strong> data-intensive applications,</strong><br>Some applications are data-intensive applications and some are process-intensive applications. Use DMS for data-intensive applications. It is a situation when applications have a lot of data that may flow between memory and secondary storage and may be communicated between the users and the database.</li><li>provide <strong>persistent storage of data<br></strong>Even if our application is shut down our database is still going to be there the day after.</li><li>provide <strong>centralized control of data<br></strong>It is important because it is possible to enforce policies across a database, even when it’s distributed.</li><li>allow <strong>control of redundancy<br></strong>It is important because we don’t want to waste space on having data represented in many different locations. By controlling the redundancy we get some other advantages. Some of those advantages are we can control consistency and integrity. Consistency is the question of whether we can derive contradictions from within the database itself which is not possible if we have redundancy.</li><li>provide <strong>multi-user support<br></strong>Think about a system that allows tens or hundreds of users to use the database at the same time. For example flight reservation system.</li><li>allow <strong>sharing of data<br></strong>The key behind supporting communication is sharing of data. When we operate from many different places on the same data, and we share data, then we are communicating.</li><li>contain <strong>data communication<br></strong>Databases contain their own documentation of the structures of the data and cannot run without that</li><li>has <strong>data independence<br></strong>It is an ability to change the implementation of a database to be more efficient without affecting the user interface.</li><li>has <strong>control access and security</strong></li><li>provide <strong>backup and recovery</strong></li></ul><p>Do not use DMS when:</p><ul><li><strong>the initial investment in hardware, software, and training is too high<br></strong>Some DMSs are as big as operating systems. The hardware needed to run such software systems is expensive. The amount of time you need to learn the databases also needs to be considered.</li><li><strong>the generality is not needed<br></strong>There’s a substantial overhead for security, concurrency control, and recovery in the database systems. Maybe we don’t need such high-level security, many users&#39; access, and recovery.</li><li><strong>data and applications are simple</strong></li><li><strong>real-time requirements that cannot be met<br></strong>If we need an application with real-time requirements and our DMS cannot run fast enough to meet those requirements.</li><li><strong>multiple user access is not needed</strong></li></ul><p>Access the continuation of this material in <a href="https://lucaselbert.medium.com/fundamental-of-databases-part-2-caf89ad19b88">Fundamental of Databases — part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5a7b576daf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parameter Identification with Neural Network — Grey-Box Approach]]></title>
            <link>https://medium.com/analytics-vidhya/parameter-identification-with-neural-network-grey-box-approach-41e72d76151?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/41e72d76151</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[parameter-estimation]]></category>
            <category><![CDATA[grey-box]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 20:32:09 GMT</pubDate>
            <atom:updated>2022-07-06T20:32:09.692Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parameter Identification with Neural Network — Gray-Box Approach</h3><h3><strong>INTRODUCTION</strong></h3><p>With the rise of computation power and the development of learning algorithms, people pivot from white-box models to black-box models when they need to model something. A black-box model is one that uses an algorithm to select the model that best captures the relationship between two input-output pairs of data. A white-box model, on the other hand, uses a physical equation to determine the relationship between input-output data.</p><p>Below is the illustration of how black-box models and white-box models work for a train system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZw6_Vb36wwiTKZ4k_hxzQ.png" /><figcaption>Train system</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_DjN44oRy1L8Jyp4WF7SQ.png" /><figcaption>Black-box model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJ6VafRVbdNmC3UhqemyfA.png" /><figcaption>White-box model</figcaption></figure><h3>PROBLEM</h3><p>There are a lot of pros and cons when we choose either white-box or black-box models. The advantages of black-box models are we don’t need to know the system (physical equations) and we can let the learning algorithm find the input-output relation for us. On the other hand, the white-box models have an advantage in the better representation of the system because it has a higher level of intuitiveness of the system due to the physical equations. But, sometimes it is not easy to find those parameter values.</p><h3><strong>QUESTION</strong></h3><p>This problem raises the question of whether we can use the advantage of the learning process and the advantage of the physical equation. To answer that question, we can try to do a parameter estimation with neural networks. This way is called gray-box models (a combination between black-box models and white-box models)</p><h3>ANSWER</h3><p>In this article, I will show you how to use neural networks which can be used to represent the physical system<strong>*</strong>. To be noted, this is not implementable in all cases. Only if the neural network equation can represent the real physical system. Let us see the equation (<strong>Eq.1</strong>) below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NI7siAe8u5gYyRjxUc0W4g.png" /><figcaption>White-box system</figcaption></figure><p>*) I assume the reader has a basic understanding of a neural network concept :)</p><h4>Call Data</h4><p>Given a physical equation of a certain system with y as the output and A as the input, we need to know the value of x1, x2, and x3. We assume the values are not known and we find it is not easy to guess. However, we have a pair of input-output data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hArcGj51DdRxvAKWHI334A.png" /><figcaption>Pair of input-output data</figcaption></figure><h4>Build neural network</h4><p>With this data, we will try to build a neural network that will have the same representation as <strong>Eq.1</strong>. Create a neural network with a schema below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4RMqK1lXtkyjiO4Kt0_gg.png" /><figcaption>Neural network with 1 neuron in the input layer, 2 neurons in the hidden layer, and 1 neuron in the output layer</figcaption></figure><h4>Forward propagation</h4><p>Next, we will apply forward propagation to the neural network where the input layer is a log function, the hidden layer is a linear function, and the output layer is a predefined equation. Below is the representation of the equation in the hidden and output layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94eaeONM-nrkrzvBdsh3HQ.png" /><figcaption>Equations in the hidden and output layer</figcaption></figure><p>If we write the equation in more detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKsQXnXKGvciWuIF9hd85w.png" /></figure><p>By substituting the value of z from the hidden layer to the output layer we will have a new equation that has the same representation as <strong>Eq.1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTt7Bn2hiYbG31tGBruTsg.png" /><figcaption>The neural network output has the same representation as <strong>Eq.1</strong></figcaption></figure><h4>Calculate cost</h4><p>After calculating the end result of the output layer we need to calculate the cost function that needs to be minimized as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*f9L7BiZ-YmkKYzDj9jTJ-A.png" /><figcaption>Cost function</figcaption></figure><h4><strong>Implement backpropagation</strong></h4><p>The purpose of backpropagation is to find the gradient values of each equation in neurons. These gradient values can be used to update the parameter values which minimizes the cost function.</p><h4>Learning process</h4><p>Do forward propagation, calculate the cost, and implement backpropagation repeatedly until the cost converges to zero or at least no significant difference if we add more iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*COBzSM_rLJANArNH4Lr4FA.png" /><figcaption>Learning process</figcaption></figure><h4>Compare the model result with the output result</h4><p>To make sure that our model works well, we need to compare the output of the neural network with the pair input-output data. In this case, we get a good result with a cost value of 0.019716.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*Pzgeh8wb6KkfP8n6UEBDhw.png" /><figcaption>Comparison</figcaption></figure><h4>Get parameter value</h4><p>Last, we need to finish the parameter estimation task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*0y02utZWDNjqEpIvmEOPPg.png" /><figcaption>Parameter estimation result</figcaption></figure><p>Congrats! We have done a parameter estimation with a neural network. I will not put a lot of detail on the result because the main purpose of this article is only to show how to do parameter identification with the gray-box approach. If you want to know more about the code, please visit my Github: <a href="https://github.com/lucassuryana/graybox_nn">https://github.com/lucassuryana/graybox_nn</a>. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41e72d76151" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/parameter-identification-with-neural-network-grey-box-approach-41e72d76151">Parameter Identification with Neural Network — Grey-Box Approach</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The derivation of the Linear Regression coefficient]]></title>
            <link>https://medium.com/codex/the-derivation-of-the-linear-regression-coefficient-c801771a9322?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c801771a9322</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 17:22:20 GMT</pubDate>
            <atom:updated>2021-03-21T12:53:28.499Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="http://medium.com/codex">CODEX</a></h4><h4>This article is inspired by the physics lab that I did 8 years ago</h4><p>One of the university subjects that require regression that I remember the most is the Physics laboratory. I remember that I was asked to make data acquisition and then did the scatter plot where the x-axis is the input variable I changed and the y-axis is the output. After that, I was asked by the lab assistant to find the b and m coefficients of the linear equation y = theta_0*x + theta_x by entering the results of the data collection into a formula that I didn’t know where it came from.</p><h3><strong>Linear Regression Example</strong></h3><p>To make it easy to grasp the regression concept, I will take an example I found on Google (I believe it comes from the Economist) according to the university’s admission rate versus the 20-year average annual return on the degree.</p><p>The figure below shows a difference between the red and blue lines where the red line is quite flat compared to the blue line, which has a downtrend with the university admission rate increase. Those lines represent the result of the regression process, which help us to gain an understanding that there is almost no difference to study at a good or bad university in the US (by comparing the university admission rate with the time needed to return the degree)</p><p>Furthermore, we can see that the lines follow the spreading trend of the orange and the blue dot. So our objective is to learn how to build those lines.</p><figure><img alt="asdasd" src="https://cdn-images-1.medium.com/max/1024/1*5dRRofS5O7QrIIFqvt9KYg.png" /><figcaption>University admission rate vs. 20-year average annual return on the degree in the US</figcaption></figure><h3><strong>Linear Regression Derivation</strong></h3><p>Having understood the idea of linear regression would help us to derive the equation. It always starts that linear regression is an optimization process. Before doing optimization, we need to have the linear equation first, where the y_hat informs us that this is the output of the linear regression process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*M9r32l-ni2vcWE_bvtNN6w.png" /><figcaption>Linear Equation</figcaption></figure><p>After we get the linear equation, we need to determine the objective function that we need to minimize the error between the observed value with the output of the linear regression process by changing the parameter value of theta_0 and theta_1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*I7ZM0v19qdyjjTO3T0r6Ww.png" /><figcaption>The error equation is the objective function that needs to be minimized.</figcaption></figure><p>Remember, when we derive the Error equation with theta_0 and set its result to zero, it will give us the optimum value of theta_0 that will bring the Error to minimum/maximum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*W5I9Kp1XD97MVU2KphsdCg.png" /></figure><p>Since we get the theta_0 value, we will substitute it to find the optimum theta_1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*OQIINFg32GEFFZQnPffO5w.png" /></figure><p>With the theta_0 and theta_1 equation, we will find those values with Excel to give more intuition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQlL3hh7b1P0jVQ7jzX1fw.png" /><figcaption>Linear Regression calculation on Excel</figcaption></figure><h3>Conclusion</h3><p>Congratulation if you have read the article to this part. If you follow my instructions step by step, you will build your own linear regression model. I have to admit that we can do this easily in machine learning in Python by the scikit-learn library. Still, I believe that it is also important to understand the basic mathematics of the library we use. Hopefully, this article will have a benefit for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c801771a9322" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/the-derivation-of-the-linear-regression-coefficient-c801771a9322">The derivation of the Linear Regression coefficient</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building footprint extraction in a dense area with MaskRCNN — Jakarta, Indonesia]]></title>
            <link>https://lucaselbert.medium.com/building-footprint-extraction-in-a-dense-area-with-maskrcnn-jakarta-indonesia-3bc529d141b5?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bc529d141b5</guid>
            <category><![CDATA[building-footprint]]></category>
            <category><![CDATA[mask-rcnn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Thu, 10 Sep 2020 03:28:29 GMT</pubDate>
            <atom:updated>2020-09-10T03:29:33.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWyzmZnr0D9Yp_yx6F0YHg.jpeg" /><figcaption>Densely Populated Area in Jakarta</figcaption></figure><h3>Building footprint extraction in a dense area with MaskRCNN — Jakarta, Indonesia</h3><blockquote>Building footprint is a good indicator to see people density across an area.</blockquote><p><strong>Background story</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*-6hhrJSPrWpJkKKVJn6Ncg.jpeg" /><figcaption>Market Potential Map [1]</figcaption></figure><p>If you own a telecommunication company, and you’re trying to find areas to promote your products, which area suites the best? Surely this is a market sizing problem. Having a customer’s location data, you can map the spread of your customers. But how do you know if there are, still, potential customers in that area?</p><p>To do this, commonly people use data provided by the Central Bureau of Statistics (BPS) in a specific area like Kabupaten/Kota (district) or Kecamatan (sub-district) to know whether there are still potential customers.</p><figure><img alt="asd" src="https://cdn-images-1.medium.com/max/1024/1*KdyUArY_Ng0wxx8xEgOutQ.jpeg" /><figcaption>Central Bureau of Statistics in Indonesia [2]</figcaption></figure><p>For example: If we have 1000 customers in district A, and we have additional information that there are 6000 people live in district A from BPS, you can approximate the number of potential customers by doing simple math. Assume one house equals to one customer. In Indonesia, it’s common that one house consists of 4 people or more. By dividing 6000 by 4 we get 1500 which means there are 500 potential customers that have not subscribed to our products.</p><p><strong>Building footprint extraction</strong></p><p>As the prediction above still too rough, we can find a better estimation by using building footprints. A building footprint is simply a polygon that surrounds a building. To have building footprints we need to digitize a polygon over building from satellite imagery and to repeat the process for all visible buildings in the target areas. As a result, we know the number of houses in a specific area. Frankly speaking, this consumes a lot of time. A normal human could only digitize a coverage area around 0.15 squared kilometers in 3 hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WW42YU9_zVsMWNbFexUUtQ.jpeg" /><figcaption>Building Footprint in Canada [3]</figcaption></figure><blockquote>Building footprint is a polygon that surrounds the building.</blockquote><p><strong>Mask R-CNN</strong></p><p>Based on the fact that manual digitation consumes a lot of time, in this article, we propose a way that will boost up the digitation process. We will learn how deep learning models can help to solve this problem with the Mask R-CNN model.</p><p>Actually, it is common to use object detection algorithms like Single Shot Detection (SSD) to detect building footprint. But it has disadvantages in a dense area like Jakarta, as there’s a probability that some buildings could be detected as one object. Surely this will hamper the accuracy. So, in this article, we propose the Mask R-CNN algorithm.</p><p>Mask R-CNN is a state of the art model for instance segmentation. This model is built on top of Faster R-CNN, which is a region-based CNN. As the output, it returns bounding boxes for each detected object, class label, and confidence score. This algorithm is proven could distinguish objects that are attached to each other. [4]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ig9E7kmJOd_tkQQbFZzdA.jpeg" /><figcaption>Mask R-CNN results [5]</figcaption></figure><p>We will implement the algorithm with arcgis.learn Python library and ArcGIS Pro.</p><p><strong>Step 1: Create training Sample</strong><br>Creating training samples means we need to manually digitize the building footprints in a certain area. As an addition, we need to add a column (classvalue column in Fig.1) that indicates the class of the building footprint. In this case, we have one class that represents a building footprint, and we give value 1. The area size of the ground truth is known 0.3 km squared kilometers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jVnDd1rsqyCS8x6l0zyjA.jpeg" /><figcaption>Training Sample</figcaption></figure><p><strong>Step 2: Export training data<br></strong>We will use the World Imagery template from Esri to generate the training data. With the help of the “Export Training Data for Deep Learning” geoprocessing tool, we will have the following items inside the destination folder:</p><ul><li>images -&gt; a collection of image chips from raster which is cut as tile size XY in the geoprocessing tool</li><li>labels -&gt; a collection of the image chips’ label from raster which is cut as tile size XY in the geoprocessing tool</li><li>esri_accumulated_stats.json</li><li>esri_model_definition.emd</li><li>map.txt</li><li>stats.txt.</li><li>models →this is not the part of this step and will be explained in <strong>step 3</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*96bOJo2mMyPigCRdfXGQsQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6GbsvUpJ7PACL1FVlLRrg.jpeg" /><figcaption>Geoprocessing tool with its destination folder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcX31upfSDBXXK9BF8v8Sw.jpeg" /><figcaption>Image chips inside the images folder</figcaption></figure><p><strong>Step 3: Train model</strong><br>Afterward, we will train a model with generated images and labels from the previous step. Set the chip_size the same size as the tile size. To reduce the amount of VRAM consumed by the GPU, tune the size of the batch_size until we get the optimal one. If the batch_size set too high the process won’t work as it will ask for a number of VRAM that cannot be provided by the GPU.*</p><p>*We use RTX2080Ti, it has 12Gb VRAM.</p><p>For the library used, we will use arcgis Python library. This is an open-source library managed by Esri that is intended to manage/automate the ArcGIS workflow with Python. With the additional deep learning model, we can train our deep learning model here. This library has some advantages as the way we use it is very simple. The code below shows how we can train a MaskRCNN model within 8 steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-gY5vn073kyZb_OFMFQgg.jpeg" /><figcaption>Python code for training Mask R-CNN model (1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*KoVNY49JHADhnwEKw3xRaw.jpeg" /><figcaption>Python code for training Mask-RCNN model (2)</figcaption></figure><p>The model that has been build from the Python code above will be saved on the folder named ‘models’ in the <strong>step 2</strong> destination folder. From the figure below, E40_Jakarta_World_Imagery.pth indicates that the framework used by arcgis Python library is PyTorch. To see more detail of the model, we can open E40_Jakarta_World_Imagery.emd. If we open it with Notepad++, it is clear that the backbone used is ResNet50, and the optimal learning rate for training the model is automatically determined by the library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gH6c4pU38F3r7DXIQUY22g.png" /><figcaption>Mask R-CNN model</figcaption></figure><p><strong>Step 4: Detect object deep learning<br></strong>Since we get the model, with the help of “Detect Objects Using Deep Learning” geoprocessing tools, the model could be tested to the imagery data. In this case, the densely populated area is the target area. From the figure below, we can see that our model successfully detects the building footprint across Jakarta. The time needed to detect the whole area is 1.5 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RtvWDCht38173ThMc14Ow.jpeg" /><figcaption>Detection results</figcaption></figure><p><strong>Step 5: Accuracy Assessment<br></strong>To get the accuracy we can simply count the number of the ground truth by dividing the number of detected building footprints with its ground truth. From the figure below, the number of ground truth is 925 and the number of detected building footprints is 689, so the accuracy is 689/925 * 100% = 76.13%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3B0orW7LPSEYOmRW0V-Pag.png" /><figcaption>Accuracy assessment</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRqK5HNWYBI4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRqK5HNWYBI4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRqK5HNWYBI4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/089b1e4db87ba23e38594229713c8c6e/href">https://medium.com/media/089b1e4db87ba23e38594229713c8c6e/href</a></iframe><p><strong>Conclusion<br></strong>Finishing <strong>step 5 </strong>means we have learned how to build a deep learning model with Mask R-CNN algorithm, to test the model, and to assess the result. The accuracy result is quite satisfying for imagery with a 30 cm resolution.</p><p>With the aforementioned steps above, we learn how deep learning could help companies to automatically digitize building footprints. This algorithm converts digitizing time from 6 hours to 1.5 minutes. Surely, this is really a great improvement in term of time optimization. This will help them to do market sizing by counting the number of building in a specific area.</p><p>Hopefully, this article could broaden our eyes about the capability of ArcGIS Pro and its arcgis Python library to help the non-IT backgrounds to build their own deep learning model.</p><p><strong>References</strong></p><p><em>[1]</em><a href="https://www.caliper.com/graphics/maptitude-sample-market-potential-map.jpg"><em>https://www.caliper.com/graphics/maptitude-sample-market-potential-map.jpg</em></a><em><br>[2]</em><a href="https://cdn.ayobandung.com/images-bandung/post/articles/2019/02/12/44916/logo-bps-bps.go.id_ratio-16x9.jpg"><em>https://cdn.ayobandung.com/images-bandung/post/articles/2019/02/12/44916/logo-bps-bps.go.id_ratio-16x9.jpg</em></a><em><br>[3] </em><a href="https://buildingfootprintusa.com/wp-content/uploads/2019/09/Canada_Montreal.jpg"><em>https://buildingfootprintusa.com/wp-content/uploads/2019/09/Canada_Montreal.jpg</em></a><em><br>[4] </em><a href="https://developers.arcgis.com/python/guide/how-maskrcnn-works/">https://developers.arcgis.com/python/guide/how-maskrcnn-works/</a><br><em>[5] </em><a href="https://arxiv.org/pdf/1703.06870.pdf"><em>https://arxiv.org/pdf/1703.06870.pdf</em></a><em><br>[6]</em><a href="https://developers.arcgis.com/python/api-reference/arcgis.learn.html?highlight=unet#"><em>https://developers.arcgis.com/python/api-reference/arcgis.learn.html?highlight=unet#</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bc529d141b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which one is better: Reinforcement Learning or Model Predictive Control? Inverted Pendulum — Case*]]></title>
            <link>https://medium.com/analytics-vidhya/which-one-is-better-reinforcement-learning-or-model-predictive-control-inverted-pendulum-case-7fc29e52bbfb?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fc29e52bbfb</guid>
            <category><![CDATA[model-predictive-control]]></category>
            <category><![CDATA[openai-gym]]></category>
            <category><![CDATA[control]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[inverted-pendulum]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Sat, 23 May 2020 16:05:28 GMT</pubDate>
            <atom:updated>2020-05-26T08:00:16.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>Which one is better: Reinforcement Learning or Model Predictive Control? Inverted Pendulum — Case*</h3><p><strong><em>“Have you ever thought about that? If so, then which one is better?”</em></strong></p><p>*Disclaimer: This post is written based on my experience and knowledge. So if you think something’s not written properly here feel free to contact me.</p><p>If you came from a control engineering background, surely that’s a tough question. As a control engineering student in the past, before designing a controller for a system I always do a system modeling by implementing the mathematical model that best represents the system. With the gathered model of the system, we can design a control system in which we can assure 100% that the system will act according to our design to follow its reference point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWNygeXuy5a1vOis1YnLAg.png" /><figcaption>The mathematical model represents: Electric, Fluid, Mechanical systems</figcaption></figure><p>When designing a control system, there’s a lot of frameworks and methods that we can use, ranging from classical control to modern control theory. In classical control where we deal with Single-Input Single-Output (SISO) system and transfer function, we can use bang-bang control, PID control, pole placement, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZxtFkdJytSyAf6W76UDMQ.png" /><figcaption>Classical Control</figcaption></figure><p>In modern control where we deal with Multi-Input Multi-Output (MIMO) system, we need to convert the system into state-space, which breaks multiple order systems into a set of one order systems. There’s a lot of methods to control this case like Model Predictive Control (MPC), Linear Quadratic Regulator (LQR), Robust Control, Pontryagin Max/Min Principle (PMP), Kalman Filter, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ztalahwj5OVKOb0jcFhMdQ.png" /><figcaption>Modern Control</figcaption></figure><p>In recent days, many people deal with Artificial Intelligence (AI) and Machine Learning (ML) try to implement this to control theory. Actually this is not a new thing, because some researchers had tried a neural network to control a system but it still has a limitation as a neural network can handle a control task on a specific condition only where it’s trained. If we have other condition we need to retrain it. Surely this very differs from classical/modern control where we can set control system robustness to tackle this case.</p><p>Later, scientists try to use PID control framework where the PID parameters were tuned with a neural network. Since then, AI application in control is growing fast and many new methods are used to control a system like an ant colony optimization, genetic algorithm, fuzzy control, etc. And now as the AI and ML world are growing fast, there’s a method called reinforcement learning.</p><blockquote>In general, we can divide control world into a <strong>conservative control system</strong> <strong>(classical and modern control) </strong>and <strong>intelligent control system (AI and ML)</strong>.</blockquote><p>And now, we will try to answer the aforementioned question above about which one is better for controlling inverted pendulum, model predictive control, or reinforcement learning?</p><blockquote><strong>REINFORCEMENT LEARNING</strong></blockquote><p><strong>Reinforcement learning</strong> (RL) is an area of <strong>machine learning</strong> which has two components: agents and environments. It is considered as one of three basic machine learning paradigms, alongside supervised learning and unsupervised learning.</p><blockquote>How it works?</blockquote><p>This agent will give actions into environments in order to maximize the notion of cumulative reward. When the agents give action to the environment, then the environment will update its state as the input to the agents to calculate the reward and update the action. In the control term, we can imagine agents as the controller and environments as the system we want to control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*dF2iro7UEMwNmYhANDZrFA.png" /><figcaption>Reinforcement Learning Workflow</figcaption></figure><p>In order to model the environment for inverted pendulum tasks, we’ll be using a toolkit developed by OpenAI called <a href="https://gym.openai.com/">OpenAI Gym</a>. The OpenAI Gym is a toolkit for developing and comparing reinforcement learning algorithms and it provides several pre-defined environments for training and testing reinforcement learning agents, including those for classic physics control tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZDPIU8ARez28GdXPy1mWQ.png" /><figcaption>OpenAI Gym</figcaption></figure><p>So here are the steps to implement RL with OpenAI Gym in Python [1]:</p><p>Step1: Install OpenAI Gym &amp; Call the libraries</p><pre>!pip install gym</pre><pre>import tensorflow as tf<br>import numpy as np<br>import base64, io, time, gym<br>import IPython, functools<br>import matplotlib.pyplot as plt<br>from tqdm import tqdm</pre><p>Step2: Initiate the environment, we will use the cart pole environment as it best represents the inverted pendulum case</p><pre>env = gym.make(“CartPole-v0”)<br>env.seed(1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*-bDl63U-9yCNlOj0uuGn3w.png" /><figcaption>Cart Pole System in OpenAI Gym</figcaption></figure><p>Step3: Define cart pole agent</p><pre>### Define the Cartpole agent ###<br># Defines a feed-forward neural network</pre><pre>def create_cartpole_model():<br>model = tf.keras.models.Sequential([</pre><pre># First Dense layer<br>tf.keras.layers.Dense(units=32, activation=’relu’),</pre><pre># Define the last Dense layer, which will provide the network’s output.<br>tf.keras.layers.Dense(units=n_actions, activation=None) # TODO])</pre><pre>return model<br>cartpole_model = create_cartpole_model()</pre><p>This cart pole agent is described as a feed-forward neural network with 32 hidden dense units and 2 outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*3FfBW0GmxtLFGMZ2gGCZ9A.png" /><figcaption>Cart Pole Agent description</figcaption></figure><p>Step4: Define the agent’s action</p><pre>### Define the agent’s action function #### <br># Function that takes observations as input, executes a forward pass through model, and outputs a sampled action.</pre><pre># Arguments:<br># model: the network that defines our agent<br># observation: observation which is fed as input to the model</pre><pre># Returns:<br># action: choice of agent action</pre><pre>def choose_action(model, observation):<br>   # add batch dimension to the observation<br>   observation = np.expand_dims(observation, axis=0)</pre><pre>   # Feed the observations through the model to predict the log      probabilities of each possible action<br>   logits = model.predict(observation)</pre><pre>   # pass the log probabilities through a softmax to compute true probabilities<br>   prob_weights = tf.nn.softmax(logits).numpy()</pre><pre>   # Randomly sample from the prob_weights to pick an action.<br>   action = np.random.choice(n_actions, size=1,   p=prob_weights.flatten())[0] # TODO</pre><pre>return action</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*7c-3vtybcQHmBqS0mOZtRA.png" /><figcaption>The agent’s action</figcaption></figure><p>Step5: Define the agent’s memory</p><pre>### Agent Memory ###</pre><pre>class Memory:<br>   def __init__(self):<br>      self.clear()</pre><pre># Resets/restarts the memory buffer<br>   def clear(self):<br>      self.observations = []<br>      self.actions = []<br>      self.rewards = []</pre><pre># Add observations, actions, rewards to memory</pre><pre>   def add_to_memory(self, new_observation, new_action, new_reward):<br>      self.observations.append(new_observation)<br>      self.actions.append(new_action) <br>      # Update the list of rewards with new reward<br>      self.rewards.append(new_reward)</pre><pre>memory = Memory()</pre><p>Step6: Define reward function</p><pre>### Reward function ###<br># Helper function that normalizes an np.array x</pre><pre>def normalize(x):<br>   x -= np.mean(x)<br>   x /= np.std(x)<br>   return x.astype(np.float32)</pre><pre># Compute normalized, discounted, cumulative rewards (i.e., return)<br># Arguments:<br># rewards: reward at timesteps in episode<br># gamma: discounting factor</pre><pre># Returns:<br># normalized discounted reward<br>def discount_rewards(rewards, gamma=0.95):<br>   discounted_rewards = np.zeros_like(rewards)<br>   R = 0<br>   for t in reversed(range(0, len(rewards))):<br>      # update the total discounted reward<br>      R = R * gamma + rewards[t]<br>      discounted_rewards[t] = R</pre><pre>   return normalize(discounted_rewards)</pre><p>Step7: Define loss function</p><pre>### Loss function ###<br># Arguments:<br># logits: network’s predictions for actions to take<br># actions: the actions the agent took in an episode<br># rewards: the rewards the agent received in an episode</pre><pre># Returns:<br># loss</pre><pre>def compute_loss(logits, actions, rewards):<br>   # Compute the negative log probabilities<br>   neg_logprob = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=actions</pre><pre>   # Scale the negative log probability by the rewards<br>   loss = tf.reduce_mean( neg_logprob * rewards ) # TODO<br>   return loss</pre><p>Step8: Use loss function to define a training step for the learning algorithm</p><pre>### Training step (forward and backpropagation) ###</pre><pre>def train_step(model, optimizer, observations, actions, discounted_rewards):</pre><pre>   with tf.GradientTape() as tape:<br>      # Forward propagate through the agent network<br>      logits = model(observations)<br>      # Call the compute_loss function to compute the loss’’’<br>      loss = compute_loss(logits, actions, discounted_rewards)<br>      # Run backpropagation to minimize the loss using the    tape.gradient method</pre><pre>   grads = tape.gradient(loss, model.trainable_variables)<br>   optimizer.apply_gradients(zip(grads, model.trainable_variables))</pre><p>Step9: Run the cart pole</p><pre>### Cartpole training! ###</pre><pre># Learning rate and optimizer<br>learning_rate = 1e-3<br>optimizer = tf.keras.optimizers.Adam(learning_rate)</pre><pre># instantiate cartpole agent<br>cartpole_model = create_cartpole_model()</pre><pre># to track our progress<br>smoothed_reward = mdl.util.LossHistory(smoothing_factor=0.9)<br>plotter = mdl.util.PeriodicPlotter(sec=2, xlabel=’Iterations’, ylabel=’Rewards’)<br>if hasattr(tqdm, ‘_instances’): tqdm._instances.clear() # clear if it exists</pre><pre>for i_episode in range(500):<br>   plotter.plot(smoothed_reward.get())<br>   # Restart the environment<br>   observation = env.reset()<br>   memory.clear()<br>   while True:<br>   # using our observation, choose an action and take it in the environment<br>   action = choose_action(cartpole_model, observation)<br>   next_observation, reward, done, info = env.step(action)<br>   # add to memory<br>   memory.add_to_memory(observation, action, reward)<br>   # is the episode over? did you crash or do so well that you’re done?<br>   if done:<br>      # determine total reward and keep a record of this<br>      total_reward = sum(memory.rewards)<br>      smoothed_reward.append(total_reward)<br>      # initiate training — remember we don’t know anything about how the<br>      # agent is doing until it has crashed!<br>      train_step(cartpole_model, optimizer, observations=np.vstack(memory.observations),actions=np.array(memory.actions),discounted_rewards = discount_rewards(memory.rewards))</pre><pre>      # reset the memory<br>      memory.clear()<br>      break</pre><pre>   # update our observatons<br>   observation = next_observation</pre><p>In general, the below chart conclude all the workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*VRs3hBh6szrFBTSA6NWZPQ.png" /><figcaption>Reinforcement Learning Workflow</figcaption></figure><blockquote><strong>MODEL PREDICTIVE CONTROL</strong></blockquote><p><strong>Model Predictive Control </strong>(MPC) is widely known as a process control’s advanced method that is used to control a process while satisfying a set of constraints. But in recent years it has also been used in controlling electrical and mechanical systems.</p><blockquote>How it works?</blockquote><p>MPC uses a model of the system to make predictions about the system’s future behavior. MPC solves an online optimization algorithm to find the optimal control action that drives the predicted output to the reference. MPC can handle multi-input multi-output systems that may have interactions between their inputs and outputs. It can also handle input and output constraints [3].</p><p>In a nutshell, MPC is an optimization method where you iterate the optimization input for every finite-time horizon. It is called online because the optimization is done iteratively until the system reaches its set point. This differs from other optimization methods where the calculation of the control gain only once before the process starts.</p><p>So here are the steps to implement MPC with OpenAI Gym in Python [2]:</p><p>Step1: Determine the mathematical model of cart pole</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*ThUBNdqUCOZU4ct3wC4Vdw.png" /><figcaption>Cart pole mathematical model</figcaption></figure><p>Actually there’s a lot of cart pole mathematical models that we can use, it depends on the assumption because there’s a model that ignores the moment inertia of the pole. So we need wisely choose the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*EiijhAabjmmXUfOnY74VBw.png" /><figcaption>Other cart poles mathematical model in state-space <a href="https://apmonitor.com/do/index.php/Main/InvertedPendulum">https://apmonitor.com/do/index.php/Main/InvertedPendulum</a></figcaption></figure><p>Step2: Determine the cost function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*HzfpQ24ok6AJrfytE1ynYA.png" /><figcaption>Quadratic cost function</figcaption></figure><p>Step3: Call the libraries</p><pre>import matplotlib.animation as animation<br>import numpy as np<br>from mpc import MPC<br>import numpy as np<br>import gym<br>import mitdeeplearning as mdl</pre><p>Step4: Run the MPC models</p><pre>env = gym.make(‘CartPole-v0’)<br>env.seed(1)<br> <br>start_theta = 0 <br>mpc = MPC(0.5,0,start_theta,0) <br>action = 0<br>for i_episode in range(1):<br>   observation = env.reset()<br>    for t in range(500):<br>    env.render()<br>    observation, reward, done, info = env.step(action)<br>    a = mpc.update(observation[0] + 0.5, observation[1],     observation[2]+np.pi, observation[3])<br>    env.env.force_mag = abs(a)<br>    #print(a)<br>    if a &lt; 0:<br>       action = 0<br>    else:<br>       action = 1<br>    if done:<br>       pass</pre><blockquote>RESULTS</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*MRzlsk2BMKicHN2SK3dKcw.gif" /><figcaption>Simulation result</figcaption></figure><p>From the results above, given an objective to keep the pole straight with a maximum deviation of 15 degrees, we can see that RL gives more satisfying results qualitatively rather than MPC. RL successes to keep the pole straight since the beginning and MPC fails at the beginning even though it starts to keep the pole straight after that.</p><p>Surely this results astonishing us as there’s a lot of effort that we spend doing MPC calculation as we need to have a mathematical model of the system that tends to be a pain point for control engineer. Of course we can overcome the problem by finding another mathematical model or MPC parameters. But the most important thing here is RL gives us better results even we don’t know the mathematical model of the cart pole, by using a policy-based strategy this algorithm success to control the cart to keep the pole straight.</p><blockquote>DISCUSSION</blockquote><p>For sure, from a control background, I cannot say that RL overcomes MPC completely so that we don’t need any control theory in the future. The model of the system is still important as with it we can check the stability of the system with Lyapunov’s theorem [4]. If you can guarantee the stability of the system than you can sure that your controller will not fail in the future if there are unexpected things happens.</p><p>Even though RL gives us a satisfactory result, there’s still some constraint as we cannot prove the success of the RL algorithm until we simulate it. The good part is now the research on interpretable machine learning is being developed. Hopefully, this will be an answer for the skeptical conservative control engineer about the implementation of RL in real cases, especially in industrial cases which is very strict with safety [5].</p><blockquote>REFERENCE</blockquote><p>[1] The code is adapted from MIT Deep Learning Bootcamp: <a href="https://github.com/aamini/introtodeeplearning">https://github.com/aamini/introtodeeplearning</a></p><p>[2] The code is adapted from Philip Zucker’s blog: <a href="http://www.philipzucker.com/model-predictive-control-of-cartpole-in-openai-gym-using-osqp/">http://www.philipzucker.com/model-predictive-control-of-cartpole-in-openai-gym-using-osqp/</a></p><p>[3] <a href="https://en.wikipedia.org/wiki/Model_predictive_control">https://en.wikipedia.org/wiki/Model_predictive_control</a></p><p>[4] <a href="https://en.wikipedia.org/wiki/Lyapunov_stability">https://en.wikipedia.org/wiki/Lyapunov_stability</a></p><p>[5] <a href="https://arxiv.org/pdf/1901.04592.pdf">https://arxiv.org/pdf/1901.04592.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fc29e52bbfb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/which-one-is-better-reinforcement-learning-or-model-predictive-control-inverted-pendulum-case-7fc29e52bbfb">Which one is better: Reinforcement Learning or Model Predictive Control? Inverted Pendulum — Case*</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updating Service — ArcGIS API for Python]]></title>
            <link>https://lucaselbert.medium.com/updating-service-arcgis-api-for-python-d858b00d2ec1?source=rss-10aa14045a3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d858b00d2ec1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[arcgis]]></category>
            <category><![CDATA[update-layer]]></category>
            <dc:creator><![CDATA[Lucas Suryana]]></dc:creator>
            <pubDate>Thu, 07 May 2020 12:45:11 GMT</pubDate>
            <atom:updated>2020-05-07T13:18:38.512Z</atom:updated>
            <content:encoded><![CDATA[<h3>Updating Service — ArcGIS API for Python</h3><p>On this occasion, we will learn how to update a feature service by using ArcGIS API for Python. For you, who’s still new in ArcGIS, this is really a powerful API that will help you to manage your tasks with Python. Especially if we are used to programming.</p><p>Before we start, make sure that you have an account and access to publish a service on the following (you can choose one)*:<br>1. ArcGIS Enterprise <br>2. ArcGIS Online<br><em>*) For the next part, I will use Portal term for ArcGIS Enterprise and AGOL for ArcGIS Online</em></p><p>Next, we first need to publish a service to our Portal/AGOL. The service could be either a table or a feature layer. We will learn how to update the data for both the table and the feature layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yq6VerUXZfEuqzJOzkhkXw.jpeg" /><figcaption>Table and Feature Layer in My Content</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLWzVJDmiRWHAgVOUEkqEg.jpeg" /><figcaption>Table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQ_Mbl4dDxQZETsJoH9kQQ.jpeg" /><figcaption>Feature Layer</figcaption></figure><p>Before we start, we need to install ArcGIS API for Python in your Python environment. This is simply a Python library.</p><pre>pip install arcgis</pre><p>After we install the ArcGIS API for Python, we need to connect to our Portal/AGOL in Python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa5733377b58902a8681cebd6c7713fc/href">https://medium.com/media/aa5733377b58902a8681cebd6c7713fc/href</a></iframe><p>Now we will start by updating the feature layer then the table</p><p><strong>Updating feature layer</strong></p><p>In this case, we will update the location and the contractor name of well</p><p>STEP 1: Connect to our editable feature layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04e14e7719a266df13fe60088c105a62/href">https://medium.com/media/04e14e7719a266df13fe60088c105a62/href</a></iframe><p>We can get the item id on our layer’s URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*-AUUXqla52X3acpjpuSuRg.png" /></figure><p>STEP 2: Create a JSON file that will update the feature layer. We will change the Abab field location into a new location and change the contractor’s name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adf04a57a85c53cec3e627873975b387/href">https://medium.com/media/adf04a57a85c53cec3e627873975b387/href</a></iframe><p>STEP 3: Push updates</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd54b359f694e6c90a546ccc333c1381/href">https://medium.com/media/dd54b359f694e6c90a546ccc333c1381/href</a></iframe><p>Now we can see the well location has been moved from Lat: -6.59 Long 106.00 into Lat: -6.70 Long 107.00. The contractor also has been changed from Schlumberger into Baker Hughes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIkdbgsQ_79sjIUMN4BA3Q.png" /></figure><p><strong>Updating the table layer</strong></p><p>In this case, we will change the updated date. Actually this step is exactly the same as the previous step, but the difference is on # access the item’s feature layers part.</p><p>STEP 1: Connect to editable table</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31f46a408204c4e7b83e2a8810680e45/href">https://medium.com/media/31f46a408204c4e7b83e2a8810680e45/href</a></iframe><p>If we see at the # Access the item’s table layers, instead of using .layers we use .tables as we are not accessing layers but the table.</p><p>STEP 2: Create a JSON file that will update the table. We will change the date from 2020–05–02 to 2020–05–03. And if we see closely, we don’t need to create a geometry in the JSON file as table doesn’t have any geometries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/228f67aada489f11127f7e8003a30133/href">https://medium.com/media/228f67aada489f11127f7e8003a30133/href</a></iframe><p>STEP 3: Push updates</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b42edaae6b77fc5c5554a5c03913d4d4/href">https://medium.com/media/b42edaae6b77fc5c5554a5c03913d4d4/href</a></iframe><p>Now we can see the table’s date has been updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*W8kl0Zu6wDDTiJXETVCFyQ.png" /></figure><p><strong>CONCLUSION</strong></p><p>Finishing the step above means we have done an update for the table and the feature layer. And the most important part is that we did that in our Python environment. If we have hundreds or thousands of rows or columns when a manual update is not effective anymore we can use ArcGIS API for Python for doing that.</p><p>You can try it on your own by accessing my <a href="https://github.com/lucassuryana/Update-Feature-Service-ArcGIS">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d858b00d2ec1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>