<?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 Shu Ishida on Medium]]></title>
        <description><![CDATA[Stories by Shu Ishida on Medium]]></description>
        <link>https://medium.com/@alacreme?source=rss-53b23b891950------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VXuthQEpp1ZlLW6T29tC2Q.jpeg</url>
            <title>Stories by Shu Ishida on Medium</title>
            <link>https://medium.com/@alacreme?source=rss-53b23b891950------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:24:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alacreme/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[Making LLMs Write Better and Better Code for Self-Driving Using LangProp]]></title>
            <link>https://medium.com/data-science/making-llms-write-better-and-better-code-for-self-driving-using-langprop-99c6c3dc9508?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/99c6c3dc9508</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[self-driving-cars]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 17:34:10 GMT</pubDate>
            <atom:updated>2024-06-25T17:34:10.681Z</atom:updated>
            <content:encoded><![CDATA[<h4>Analogy from classical machine learning: LLM (Large Language Model) = optimizer; code = parameters; LangProp = PyTorch Lightning</h4><p>You have probably used ChatGPT to write your emails, summarize documents, find out information, or help you debug your code. But can we take a step further and make ChatGPT drive a car?</p><p>This was the question we wanted to answer when I started my internship at <a href="https://wayve.ai/">Wayve</a> in March last year. Wayve is an autonomous driving startup in London, applying end-to-end learning to the challenging problem of urban driving. At the time, the company was just about to launch its LLM research team, which has since successfully developed <a href="https://wayve.ai/thinking/lingo-natural-language-autonomous-driving/?doing_wp_cron=1718832390.6593759059906005859375">LINGO-1</a> and <a href="https://wayve.ai/thinking/lingo-2-driving-with-language/">LINGO-2</a>. <a href="https://github.com/Significant-Gravitas/AutoGPT">AutoGPT</a> had just come out, and <a href="https://github.com/MineDojo/Voyager">Voyager</a> had not come out yet. And yet, the disruption caused by LLMs was palpable. The question was, how can we use this new technology to driving, a domain where language isn’t the main modality?</p><p>In this blog post, I would like to give an overview of our paper <a href="https://arxiv.org/abs/2401.10314"><strong>LangProp</strong></a>, which we presented at the LLM Agents workshop at ICLR (the International Conference on Learning Representations) last month (May 2024).</p><ul><li><a href="https://github.com/shuishida/LangProp">GitHub - shuishida/LangProp</a></li><li><a href="https://arxiv.org/abs/2401.10314">LangProp: A code optimization framework using Large Language Models applied to driving</a></li></ul><h3>Motivation: Let’s apply ML to code writing, literally.</h3><p>The challenge of applying LLMs to driving comes in twofold: firstly, LLMs are, as the name says, very large models that require a lot of compute and can be slow to run, which makes them not-so-ideal for safety-critical real-time applications, such as autonomous driving; secondly, while language is good at high-level descriptions and serves as a sophisticated tool for logic, reasoning and planning, it doesn’t have the granularity and detail that is needed to describe observations and give spatial control actions.</p><p>We realised, however, that we don’t necessarily have to use LLMs for inferring driving actions. What we could do instead is to make LLMs write the code for driving itself.</p><p>If you have ever used ChatGPT to write code then this may sound like a terrible idea. The code that it writes seldom works out of the box, and often contains some errors. But what if we use LLMs to also detect bugs and automatically fix them, thereby iteratively improving the code quality?</p><p>We took this idea a step further — instead of just fixing bugs, we designed a training framework that allows us to improve the code that the LLM generates towards an objective function of your choice. You can “train” your code to improve on a training dataset and try to reduce the losses. The code improvements can be quantified by running it on a validation dataset.</p><p>Does this start to sound like Machine Learning? Because it essentially is! But are we fine-tuning the LLM? No — in fact, there is no neural network that is being fine-tuned. Instead, we are fine-tuning the code itself!</p><p>In LangProp, the “code” is the <em>parameters</em> of the model, and the LLM is the <em>optimizer</em> that guides the <em>parameters</em> to improve in the direction that reduces the loss. Why is this cool? Because by applying this thinking, we can now automate optimization of software themselves in a data-driven way! With deep learning, we witnessed the power of data-driven approaches to solving hard-to-describe problems. But so far, the application domain of machine learning has been constrained to models parametrized by numeric values. Now, they can deal with systems described in code, too.</p><p>If you have followed the history of Artificial Intelligence, this is an elegant way to unify the once popular approach of Symbolic AI with the more modern and successful Machine Learning approach. Symbolic AI was about having human experts describe a perfect model of the world in the form of logic and code. This had its limitations, as many complex tasks (e.g. object recognition) were beyond what human experts can feasibly describe with logic alone. Machine Learning, on the other hand, lets the data speak for itself and fits a model that best describes them in an automated way. This approach has been very successful in a wide range of disciplines, including pattern recognition, compression and function approximation. However, logic, reasoning, and long-term planning are fields where naively fitting a neural network on data often fails. This is because it is challenging to learn such complex operations in the modality of neural network parameter space. With LLMs and LangProp, we can finally apply the data-driven learning method to learn symbolic systems and automate their improvement.</p><h4>Disclaimer</h4><p>Before we dive in further, I feel that some disclaimers are in order.</p><ol><li>This work on LangProp was conducted as an internship project at Wayve, and does not directly reflect the company’s Research &amp; Development priorities or strategies. The purpose of this blog post is to describe LangProp as a paper, and everything in this blog post is written in the capacity of myself as an individual.</li><li>While we demonstrated LangProp primarily for the case of autonomous driving, we also would like to stress its limitations, such as (a) it requires perfect observation of the environment, (b) we only made it work in a simulated environment and it is far from real-world deployment, (c) the generated driving code is not perfect nor sophisticated, and has many issues to be suitable for real-world deployment. We see LangProp as a research prototype that showcases the potential of LLMs applied to data-driven software optimization, not as a product for deployment.</li></ol><p>If you need further information on the limitations of LangProp, please check out the limitation section in the appendix of <a href="https://arxiv.org/abs/2401.10314">our paper</a>.</p><p>With that said, let’s take a look at how LangProp works!</p><h3>How does LangProp work?</h3><h4>…we bring back Symbolic AI and Evolutionary Algorithms</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Usq9Rf_cmxOaAVeUOTxN5A.png" /><figcaption>An overview of the LangProp trainer. The LLM generates variations of code, which is then evaluated on the training dataset. Codes with high scores are kept. The LLM is provided with information about the failure modes of the code and rewrites them to achieve higher performance on the training metric. (image by the author)</figcaption></figure><p>LangProp is designed like PyTorch Lightning — a LangProp module keeps track of the <em>parameters</em> (collection of scripts) that are trained and used for inference. In the training mode, a policy tracker keeps a record of the inputs, outputs, and any exceptions during the forward pass. The performance of the code is evaluated by an objective function. Based on the scores, the policy tracker re-ranks the scripts that currently exist, and passes the top k scripts to the LLM for refinement. At inference time, making a prediction is as simple as calling the code with the best score.</p><p>The LangProp trainer takes a LangProp module to be trained, a training dataset, and a validation dataset. The dataset can be any iterable object, including a PyTorch Dataset object, which makes applying LangProp to existing tasks easier. Once the training is finished, we can save a <em>checkpoint</em>, which is the collection of refined code along with some statistics for ranking the code.</p><p>The mechanism we use to choose the best code and improve them is similar to evolutionary algorithms, in which samples are initially chosen randomly, but then the ones that are high-performing are kept and perturbed to spawn a new generation of fitter samples.</p><h3>Applying LangProp to driving</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgNgtvdqYjeyP6NkiyGEQw.png" /><figcaption>Overview of the LangProp driving agent in CARLA (image by the author)</figcaption></figure><p>Now let’s try using LangProp to drive in CARLA!</p><p><a href="https://carla.org/">CARLA</a> is an open-sourced driving simulator used for autonomous driving research. There is a <a href="https://leaderboard.carla.org/">leaderboard challenge</a> to benchmark your self-driving car agent. We tested LangProp on the standard routes and towns in this challenge.</p><p>The good thing about formulating LangProp as a Machine Learning framework is that, now we can apply not just classic supervised learning but also imitation learning and reinforcement learning techniques.</p><p>Specifically, we start our training on an offline dataset (driving demonstrations from an expert that contains state and action pairs), and then perform online rollouts. During online rollout, we employ DAgger [1], which is a dataset aggregation technique where samples collected by online rollouts are labelled with expert labels and aggregated with the current dataset.</p><p>The input to the model (the code) is a Python dictionary of the state of the environment, including the poses and velocities of the vehicle and surrounding actors, and the distances to the traffic light / stop sign. The output is the driving action, which is the speed and steering angle at which the vehicle should drive.</p><p>Whenever there is an infraction, e.g. ignoring a traffic light or stop sign, collision with another vehicle, pedestrian or cyclist, or being stationary for too long, there is a penality to the performance scores. The training objective is to maximize the combined score of imitation learning scores (how well can the agent match the ground truth action labels) and the reinforcement learning scores (reducing the infraction penalty).</p><h3>LangProp driving agent in action</h3><p>Now watch the LangProp agent drive!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2VKBZrSZVMg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2VKBZrSZVMg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2VKBZrSZVMg%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/1af69bd632d5e9b26e1d3405ac2936e2/href">https://medium.com/media/1af69bd632d5e9b26e1d3405ac2936e2/href</a></iframe><p>We saw during training that, the initial driving policy that ChatGPT generates is very faulty. In particular, it often learns a naive policy that copies the previous velocity. This is a well-known phenomenon called causal confusion [2] in the field of imitation learning. If we just train with behavioral cloning on the offline dataset, such naive but simple policies obtain a high score compared to other more complex policies. This is why we need to use techniques such as DAgger and reinforcement learning to make sure that the policy performs in online rollout.</p><p>After an iteration or two, the model stops copying the previous velocity and starts moving forward, but is either overly cautious (i.e. stops whenever there is an actor nearby, even if they are not in collision course), or reckless (driving forward until it collides into an actor). After a couple more iterations, the model learns to keep a distance from the vehicle in front and even calculates this distance dynamically based on the relative velocities of the vehicles. It also predicts whether other actors (e.g. J-walking pedestrians) are on collision course with the vehicle by looking at the velocity and position vectors.</p><p>In the experiments in <a href="https://arxiv.org/abs/2401.10314">our paper</a>, we show that the LangProp driving agent outperforms many of the previously implemented driving agents. We compare against both a PPO expert agent (Carla-Roach [3], TCP [4]) and researcher-implemented expert agents (TransFuser [5], InterFuser [6], TF++ [7]), and LangProp outperformed all expert agents except for TF++. All the expert agents were published after the GPT 3.5 training cutoff of September 2021, so this result is both surprising and exciting!</p><h3>Closing remark</h3><p>Thank you for joining me on the ride! While in this work we primarily explored the application of LangProp to autonomous driving in CARLA, we also showed that LangProp can be easily applied to more general problems, such as the typical RL environment of CartPole-v1. LangProp works best in environments or problems where feedback on the performance can be obtained in the form of text or code, giving the model a richer semantic signal that is more than just numerical scores.</p><p>There are endless possible applications of LangProp-like training to iteratively improve software based on data, and we are excited to see what will happen in this space!</p><p>If you liked our work, please consider building on top of it and citing our paper:</p><pre>@inproceedings{<br>ishida2024langprop,<br>title={LangProp: A code optimization framework using Large Language Models applied to driving},<br>author={Shu Ishida and Gianluca Corrado and George Fedoseev and Hudson Yeo and Lloyd Russell and Jamie Shotton and Joao F. Henriques and Anthony Hu},<br>booktitle={ICLR 2024 Workshop on Large Language Model (LLM) Agents},<br>year={2024},<br>url={https://openreview.net/forum?id=JQJJ9PkdYC}<br>}</pre><h3>References</h3><p>[1] Stéphane Ross, Geoffrey Gordon, and Drew Bagnell. “A reduction of imitation learning and structured prediction to no-regret online learning.” In <em>Proceedings of the fourteenth international conference on artificial intelligence and statistics</em>, <em>JMLR Workshop and Conference Proceedings</em>, 2011.</p><p>[2] Pim De Haan, Dinesh Jayaraman, and Sergey Levine. “Causal confusion in imitation learning”. <em>Advances in Neural Information Processing Systems</em>, 2019.</p><p>[3] Zhejun Zhang, Alexander Liniger, Dengxin Dai, Fisher Yu, and Luc Van Gool. “End-to-end urban driving by imitating a reinforcement learning coach.” In P<em>roceedings of the IEEE/CVF international Conference on Computer Vision</em>, pp. 15222–15232, 2021.</p><p>[4] Penghao Wu, Xiaosong Jia, Li Chen, Junchi Yan, Hongyang Li, and Yu Qiao. “Trajectory-guided control prediction for end-to-end autonomous driving: A simple yet strong baseline.” <em>Advances in Neural Information Processing Systems</em>, 35:6119–6132, 2022.</p><p>[5] Kashyap Chitta, Aditya Prakash, Bernhard Jaeger, Zehao Yu, Katrin Renz, and Andreas Geiger. “Transfuser: Imitation with transformer-based sensor fusion for autonomous driving.” <em>IEEE Transactions on Pattern Analysis and Machine Intelligence</em>, 2022.</p><p>[6] Hao Shao, Letian Wang, Ruobing Chen, Hongsheng Li, and Yu Liu. “Safety-enhanced autonomous driving using interpretable sensor fusion transformer.” In <em>Conference on Robot Learning</em>, pp. 726–737. PMLR, 2023.</p><p>[7] Jaeger, Bernhard, Kashyap Chitta, and Andreas Geiger. “Hidden biases of end-to-end driving models.” <em>Proceedings of the IEEE/CVF International Conference on Computer Vision</em>. 2023.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c6c3dc9508" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/making-llms-write-better-and-better-code-for-self-driving-using-langprop-99c6c3dc9508">Making LLMs Write Better and Better Code for Self-Driving Using LangProp</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CALVIN — a neural network that can learn to plan and navigate unknown environments]]></title>
            <link>https://medium.com/data-science/calvin-a-neural-network-that-can-learn-to-plan-and-navigate-unknown-environments-820a8444276f?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/820a8444276f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Wed, 01 Jun 2022 14:58:43 GMT</pubDate>
            <atom:updated>2022-06-02T20:25:04.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>CALVIN — a neural network that can learn to plan and navigate unknown environments</h3><h4>Collision Avoidance Long-term Value Iteration Network</h4><p><strong>Summary: </strong>CALVIN is a neural network that can plan, explore and navigate in novel 3D environments. It learns tasks such as solving mazes, by just learning from expert demonstrations. Our work builds upon Value Iteration Networks (VIN) [1], a type of recurrent convolutional neural network. While VINs only work well in fully-known environments, CALVIN works even in <em>unknown </em>environments where the agent has to explore the environment in order to find the target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzjGLtcmhOlrriCnyLpQ8Q.png" /><figcaption>The three environments CALVIN has been tested in (image by author)</figcaption></figure><p>In this article I would like to give a high level overview of a paper I published recently to CVPR 2022 (Conference on Computer Vision and Pattern Recognition). The motivation for this research was to come up with a more robust neural network architecture that can <strong><em>learn to plan</em></strong>, inspired by the work on Value Iteration Networks [1].</p><p><a href="https://arxiv.org/abs/2108.05713">Towards real-world navigation with deep differentiable planners</a></p><p><strong>Code:</strong> <a href="https://github.com/shuishida/calvin">https://github.com/shuishida/calvin</a></p><h3>The Problem</h3><p>The problem we address is visual navigation from demonstrations. A robotic agent must learn how to navigate, given a fixed amount of expert trajectories of RGB-D images and the actions taken. While it is easy to plan with a top-down map that defines what are obstacles and targets, it is more challenging if the agent has to learn the nature of obstacles and targets from the RGB-D images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4C44vacy7g_vAhBVGCoiuQ.png" /><figcaption>A sequence of images and actions that the agent sees as expert demonstrations (image by author)</figcaption></figure><p>Another important aspect of navigation is exploration. Our agent starts without any knowledge about the new environment, so it has to build a map of the environment as it navigates, and learn to explore areas that are most likely to lead to the target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZzU0K74Zr71CUFFTkInMw.png" /><figcaption>The agent learns to predict rewards that best explains expert demonstrations (image by author)</figcaption></figure><p>For the agent to be able to navigate in environments it hasn’t been trained on, it has to learn some general knowledge applicable across all environments. In particular, we focus on learning a shared transition model and reward model that best explain expert demonstrations, which can then be applied to new setups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlyjZe0xhRkQWWxMDH3ySw.png" /><figcaption>The agent learns motion dynamics that are reusable across all environments (image by author)</figcaption></figure><h3>Model Overview</h3><p>Our model consists of two parts — a learnt mapping component which we call Lattice PointNet, that aggregates past observations into a ground-projected map of embeddings, and CALVIN, which is a differentiable planner which models value iteration. Unlike more common approaches in reinforcement learning, where the agent sees an image and tries to reactively predict the best action, by having a proper spatial representation learnt by the Lattice PointNet and using CALVIN as a planning network, our agent is able to explore and navigate taking into account past observations in a spatially meaningful way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmeqsmlYDex4En8NSmBrFQ.png" /><figcaption>Overview of the model architecture (image by author)</figcaption></figure><p>CALVIN is an improved version of Value Iteration Networks or VIN in short, which use recurrent convolution as a form of value iteration for spatial tasks. It learns a reward map and a convolutional kernel that, applied following the value iteration update equation, produces a Q-value map, which is an estimate of the future rewards the agent can obtain. Once the value map is computed, the agent can take the action that yields the highest value to maximise its chances.</p><p>While the VIN is a simple architecture, it has several flaws, most notably that it doesn’t strictly learn value iteration in practice. As you can see in the figure below, the value map produced by the VIN is not what we would expect from value iteration, whereas our model CALVIN learns to produce a value map that is almost identical to the theoretical solution. We identified the mismatch to be because the VIN is not constrained enough to penalise obstacles, hence making suboptimal decisions such as repeatedly exploring dead-ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXShh8PAjyubwgLXfrcfEQ.png" /><figcaption>Comparison of value maps produced by the VIN and CALVIN. The VIN produces non-interpretable, brittle value maps. (image by author)</figcaption></figure><p>CALVIN, on the other hand, explicitly learns valid and invalid transitions. It decomposes the transition model into a shared agent motion model and an action availability model. CALVIN uses the action availability model to penalise the invalid actions, and to prevent values from propagating from unreachable states. In addition to these constraints on available actions, we also improved the training loss so that the model can leverage training signals across the entire trajectory, instead of just the current state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ygzlnbYWztK8pdb_860xlg.png" /><figcaption>Model diagram of CALVIN (image by author)</figcaption></figure><h3>Experiments</h3><p>We performed experiments, specifically on exploration of novel unknown environments, in three domains: a grid maze environment, MiniWorld [2], and the Active Vision Dataset [3]. CALVIN achieved a more robust navigation, even in unknown environments, demonstrating explorative behaviour which the VIN lacks.</p><p>In our grid maze setup, the agent can only view the maze locally. The agent can choose to either move forward, rotate left, right, or trigger done. We can see that the agent predicts higher values for places the agent hasn’t explored yet, and a high reward for the target location when the agent sees it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FmzcVGGOUxdc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DmzcVGGOUxdc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FmzcVGGOUxdc%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/6cfdf25ca14e8a78d4d54600bb9a048f/href">https://medium.com/media/6cfdf25ca14e8a78d4d54600bb9a048f/href</a></iframe><p>Next, we ran a similar experiment in a 3D maze environment called MiniWorld, but this time using RGB-D image sequences from the agent’s perspective rather than a top-down view. While the agent navigates, it builds up a map of embeddings with the Lattice PointNet, which is then fed into CALVIN. Here too, the agent has learned to assign lower values to walls and higher values to unexplored locations. We can observe that the agent manages to backtrack upon hitting a dead-end, and replan towards other unexplored cells. When the agent sees the target, it assigns a high reward to cells near the target.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCcKSlxHnwIY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCcKSlxHnwIY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCcKSlxHnwIY%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/5784c7733cf959a65f1e92576951c30a/href">https://medium.com/media/5784c7733cf959a65f1e92576951c30a/href</a></iframe><p>Finally, we tested the agent using the Active Vision Dataset, which is a collection of real-world images obtained by a robotic platform, from which we can create trajectories. For this task, we used pre-trained ResNet embeddings and fed them into the Lattice PointNet. The agent was trained to navigate towards a soda bottle in the room.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjbGrqiBsnGI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjbGrqiBsnGI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjbGrqiBsnGI%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/206829143894b278c9500a054411cea1/href">https://medium.com/media/206829143894b278c9500a054411cea1/href</a></iframe><h3>Conclusion</h3><p>CALVIN is able to explore and navigate unknown environments more robustly compared to other differentiable planners. This improvement from the VIN comes from explicitly modelling action availability, used to penalise invalid actions, together with an improved training loss that uses trajectory reweighting. We also introduced a Lattice PointNet backbone that efficiently fuses past observations in a spatially consistent way.</p><h3>References</h3><p>[1] Tamar et al., “<a href="https://arxiv.org/abs/1602.02867">Value Iteration Networks</a>”, NeurIPS 2016.</p><p>[2] M. Chevalier-Boisvert, <a href="https://github.com/maximecb/gym-miniworld,">https://github.com/maximecb/gym-miniworld,</a> 2018.</p><p>[3] Ammirato et al. “<a href="https://arxiv.org/abs/1702.08272">A dataset for developing and benchmarking active vision</a>”, ICRA 2017.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=820a8444276f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/calvin-a-neural-network-that-can-learn-to-plan-and-navigate-unknown-environments-820a8444276f">CALVIN — a neural network that can learn to plan and navigate unknown environments</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Linux (Ubuntu 20.04) on an external portable SSD and pitfalls to be aware of]]></title>
            <link>https://medium.com/geekculture/installing-linux-ubuntu-20-04-on-an-external-portable-ssd-and-pitfalls-to-be-aware-of-388294e701b5?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/388294e701b5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 00:03:32 GMT</pubDate>
            <atom:updated>2022-04-22T10:24:26.061Z</atom:updated>
            <content:encoded><![CDATA[<h4>Carry your Ubuntu OS anywhere without being limited by hardware</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i60DXC7Ssk7JVjPLshgtmw.jpeg" /><figcaption>Screenshot of Ubuntu with Samsung SSD</figcaption></figure><h4>TL;DR Skip to “Installation Process”</h4><h3>Choosing your Operating System is difficult</h3><p>If you are a software developer, you have probably come across the dilemma of choosing your operating system. This is a big decision to make, since each operating system comes with its own pros and cons, and you will be stuck with them for quite a while. For people who are just getting into coding, below is my personal opinion on pros and cons of each operating system.</p><p>Why programmers tend to prefer Linux is because a lot of open-source code (especially in the research stage) are developed on it. This doesn’t mean that it is better than Windows or Mac necessarily, but it is definitely more accessible because it is free and open-source, so many research labs, companies and cloud computing providers run Linux on their remote clusters. Therefore, the software they develop are most often tested on Linux distributions such as Ubuntu, but may not be tested on Windows or Mac OS, and you might have to spend a while to find a work around.</p><p>On the other hand, using Linux has its own drawbacks; many proprietary products such as business, gaming and industrial software do not support Linux because Windows and Mac OS have a larger share of the market. For instance, Microsoft Office and Adobe Products are only available on Windows and Mac OS, and in order to install it on Linux you would have to do a work around such as installing on top of PlayOnLinux. If you want to develop mobile apps, you need a Mac because iOS app development is only possible on a Mac. If you are a gamer, Windows is probably best suited. In terms of extending the laptop like we do in this article, a PC would be more suited than a Mac, since there are more ports and also configuring BIOS is difficult in Apple products.</p><p>Another issue I find is that, Ubuntu is less stable compared to Windows or Mac OS, especially when it comes to hardware compatibilities and drivers. While some problems are solvable given you have some familiarity with Linux, this can take a while. Also, since Linux’s primary strength is in its command line capabilities, its Graphical User Interface tends to be less developed, so Windows / Mac are definitely more user friendly in that sense.</p><h3>A solution that worked for me: Windows laptop + Ubuntu external SSD</h3><p>I credit my course mate for giving me this idea. Before this, I had a dual-booted Windows + Ubuntu laptop but I would not recommend this because my 500GB hard drive quickly filled up from hosting two operating systems, each with their own software. Despite moving out almost all personal files onto external drives, I barely had space left because some software can easily take up tens of GBs due to its cash. I was seriously considering buying a new laptop, but this external SSD idea saved me thousands of pounds.</p><p>The great thing about installing an Ubuntu OS on an external SSD drive is that, you can easily use and switch between both Windows and Ubuntu without sacrificing any storage space. What is more, you can now carry this SSD drive wherever you want, and plug it into any computer. As long as you know how to configure the BIOS/UEFL so that this will boot up, you can keep working with your familiar OS and software. The other good thing is that, in case you mess up the installation, you can always wipe the disk and try again. This can be a lot scarier if you are trying to install Ubuntu onto a partition sitting on your local storage.</p><h3>The installation process that worked for me</h3><p>This is not meant to be a comprehensive guide to installation, but I will try to outline what worked for me, and the pitfalls you should be aware of, because sometimes knowing what doesn’t work is just as important and saves an awful amount of time as knowing what works. I would suggest first trying this method out, and if this doesn’t work, read the “Helpful Resources” section.</p><h4>Step 0. Before you start</h4><p>What you would need:</p><ul><li>USB stick with 8G+ memory.</li><li>Laptop (I have tried with Dell XPS)</li><li>SSD drive* (e.g. I bought a Samsung T7 SSD with 1TB storage)<br>*Note: make sure that you have high read/write speed because your operating system performance can be bottle-necked by it. T7 has up to 1050MB/s. HDD, USB memory and SD are slower.</li></ul><p><strong>What you should be careful of:</strong></p><ul><li>Make sure you back up your computer (especially personal files, but also your OS) in case something bad happens, which can be the case since we are going to do a lot of formatting, partitioning, and changing BIOS/UEFL settings.</li><li>Wipe and format both the SSD drive and USB stick beforehand (they will be reformatted anyway but just to be sure)</li></ul><h4>Step 1. Create a bootable Ubuntu 20.04 LTS USB drive</h4><p>First, you have to download the Ubuntu Desktop ISO image by going to the <a href="https://ubuntu.com/download/desktop">official website</a>. Make sure to download the LTS version. In my case, I downloaded Ubuntu 20.04.4.</p><p>Next, if you are on Windows, you can use <a href="https://rufus.akeo.ie/">Rufus</a> to write the ISO to your USB stick. You can read <a href="https://www.howtogeek.com/howto/linux/create-a-bootable-ubuntu-usb-flash-drive-the-easy-way/">How to Create a Bootable Linux USB Flash Drive, the Easy Way</a> to find out how to do this.</p><p>If you are already on Ubuntu, you can try creating the bootable USB stick with the “Startup Disk Creator” as outlined in the above article. It didn’t seem to work for me though, so I did this directly from the terminal. Read <a href="https://codepre.com/en/como-crear-un-disco-usb-de-arranque-desde-la-terminal-de-ubuntu.html">How to create a bootable USB drive from Ubuntu terminal?</a></p><p><strong>What you should be careful of:</strong></p><ul><li>Double check that you are writing the ISO image to the correct drive. Don’t overwrite your local storage.</li><li>Double check that the ISO file you downloaded is not corrupted. This can be done by following <a href="https://ubuntu.com/tutorials/how-to-verify-ubuntu#2-necessary-software">How to verify your Ubuntu download</a>.</li></ul><p>It actually took me a day to get this step working because of two factors</p><ol><li>I initially tried to use a cheap USB stick that I got at a career event. DON’T USE THESE. You will waste a lot of time scratching your head later on when you try to boot Ubuntu and fail. Use a proper and reliable USB stick.</li><li>When I used the “Startup Disk Creator” in Ubuntu, I got a “/casper/vmlinuz not found” error. It turned out that my bootable USB stick was corrupt, so I had to create this from the command line. The same happened when I tried to use my other laptop which comes with a non-English Windows OS to create the USB stick. Make sure that your OS language setting is in English if this happens.</li></ol><h4>Step 2. Change boot settings</h4><p>Now, with your newly bootable USB plugged in, we have to change your laptop behaviour upon boot. On most machines, you can enter the boot menu when the computer starts if you press a certain key. This depends on the laptop, but they are usually either Esc, F2, F10 or F12. On my Dell XPS 15, pressing both Fn and F2 at the same time takes me to the boot settings page. Make sure to practice this so that you can always comfortably go to the boot menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTAUToBEfCYJipktLkuizg.png" /><figcaption>Screen of boot sequence menu</figcaption></figure><p>Now that you are in the boot menu, you have to do two things. Firstly, you have to change the General &gt; Boot Sequence so that your Ubuntu USB comes to the top. Secondly, you should go to System Configuration &gt; Driver and uncheck every drive you see listed. This will disconnect your internal storage upon boot so that you won’t accidentally overwrite these when you are installing Ubuntu to your external SSD. This will avoid most of the problems that the article I followed (<a href="https://www.58bits.com/blog/2020/02/28/how-create-truly-portable-ubuntu-installation-external-usb-hdd-or-ssd">How to Create a Truly Portable Ubuntu Installation on an External USB HDD or SSD</a>, which is, by the way, an amazing article) addresses, namely that the EFI partition might be overwritten and that you have to install Grub yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wf2fjUcPjDw3SN3yKWkOpg.png" /><figcaption>Screen of driver menu</figcaption></figure><p>You can easily reconnect your internal storage afterwards once you finish your installation by going to the boot menu and ticking the boxes again.</p><h4>Step 3. Boot Ubuntu from bootable USB</h4><p>Now reboot your laptop with the bootable USB plugged in. In the first menu that shows up, don’t select the normal Ubuntu, but try “Ubuntu (safe graphics)”. This will save you a lot of pain of waiting on a stalled installation. After a while, a loader with options of “Try Ubuntu” and “Install Ubuntu” will come up. You can choose either one. If you choose Try Ubuntu, Ubuntu will load from your USB for the time being, and on the desktop there is a shortcut to “Install Ubuntu”. I personally prefer this way because the fonts appear much bigger, and you can do other things on the temporary Ubuntu while the installation is ongoing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*5MPrO9QGu12sVlhRELRy6A.png" /><figcaption>Screenshot of Try Ubuntu / Install Ubuntu menu</figcaption></figure><h4>Step 4. Install Ubuntu onto External SSD</h4><p>Once you move to the installation screen, connect your external SSD and follow the instructions. At one point, they will ask for the installation type. Now, in <a href="https://medium.com/r?url=https%3A%2F%2Fwww.58bits.com%2Fblog%2F2020%2F02%2F28%2Fhow-create-truly-portable-ubuntu-installation-external-usb-hdd-or-ssd">the other tutorial I followed</a>, the author recommends partitioning your disk yourself. However, I wanted to take advantage of the LVM encryption feature that comes in the “Advanced features” option if you choose “Erase disk and install Ubuntu”. This works only if you have disconnected all internal storage in the boot setting as outlined in <strong>Step 2</strong> — otherwise, there is a risk that your local EPI partition will be overwritten as the above article warns. If you see more than these two options, you may still have some internal storage that are not disconnected, or you might not have wiped your external SSD beforehand.</p><p>The only other downside to choosing the default setting rather than going for a custom “Something else” option is that, you can’t decide how your hardware will be partitioned. This is especially annoying for the swap partition, which is only given ~800MB in the default setting. We can later fix this by adding our custom swap file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9sMMOV8U7mRP-JAG0pO-g.png" /><figcaption>Screenshot of installation wizard: installation type</figcaption></figure><p>The rest of the installation process should be straightforward. When you choose your username, make sure that you don’t have any spaces. This can help you avoid a lot of headaches down the line. Once everything is installed, you can reboot your laptop. The screen should ask you to remove your bootable USB before it reboots.</p><h4>Step 5. Updating software and drivers</h4><p>Once the system reboots, hooray, you have a working Ubuntu OS on your external SSD! Don’t celebrate too soon though. Wait until you finish updating your software and drivers.</p><p><strong>General Software Update</strong></p><p>You can either use the Software &amp; Update GUI interface to update packages, or you can perform</p><pre>sudo apt update</pre><pre>sudo apt upgrade</pre><p><strong>Nvidia Driver Update</strong></p><p>By default, Ubuntu uses a third party driver instead of the Nvidia proprietary driver. To change this to the official drivers, you can follow either of the below.</p><ul><li><a href="https://www.cyberciti.biz/faq/ubuntu-linux-install-nvidia-driver-latest-proprietary-driver/">Ubuntu Linux Install Nvidia Driver (Latest Proprietary Driver)</a></li><li><a href="https://linuxconfig.org/how-to-install-the-nvidia-drivers-on-ubuntu-20-04-focal-fossa-linux">How to install the NVIDIA drivers on Ubuntu 20.04 Focal Fossa Linux</a></li></ul><p><strong>Change GRUB settings</strong></p><p>There’s one thing I would do straightaway (even if you don’t have any issues), which is to update the GRUB setting so that Ubuntu will print out logs onto the screen upon boot. Upon your initial boot, open /etc/default/grub with your favourite text editor (for example, by running sudo gedit /etc/default/grub) and where it says</p><pre>GRUB_CMDLINE_LINUX_DEFAULT=&quot;quiet splash&quot;</pre><p>change this to</p><pre>GRUB_CMDLINE_LINUX_DEFAULT=&quot;&quot; </pre><p>Also, set GRUB timeout to something more than 0, so that if you want to open the GRUB menu upon boot, you can do so by pressing the shift key.</p><pre>GRUB_TIMEOUT=10</pre><p>Once you save and close the text editor, reflect the updated GRUB settings.</p><pre>sudo update-grub</pre><p><strong>Things to be aware of:</strong></p><p>This is where I struggled the most. I must have tried at least 20 installations following <a href="https://www.58bits.com/blog/2020/02/28/how-create-truly-portable-ubuntu-installation-external-usb-hdd-or-ssd">the article I mentioned</a>, but every single time, my Ubuntu kept hanging at reboot with a blinking underscore cursor with no error messages. Updating the GRUB setting as above provided me with the logs, but still, they were kind of misleading and was a red herring because Ubuntu kept hanging at different logs when I tried rebooting multiple times.</p><p>Eventually I realised that Ubuntu was simply failing to load the GUI login screen in time, which is typically handled by GDM3. This was confirmed because if I open up the terminal with Ctrl + Alt + F3and I manually type sudo service gdm start I was able to start the GUI login screen. Reading <a href="https://askubuntu.com/questions/1050672/gdm3-does-not-start-in-ubuntu-18-04">this StackOverflow thread</a> was helpful.</p><p>In the end, what worked for me was to not follow the article above but to follow the default Ubuntu installation procedures, with encryption enabled. I haven’t tried comparing the encrypted version and non-encrypted version, but I am suspecting that the amount of time I take to type in my password to unlock the hard drive is enough time for the X server to start running so that the GUI can launch properly (I came to this conclusion because whether Ubuntu stalls seemed pretty random, when I tried rebooting multiple times without any changes to the system). But I could be wrong.</p><p>The other option that worked for me (with custom partitions following the article) was to switch to lightdm by doing the following.</p><pre>sudo apt-get install lightdm<br>sudo dpkg-reconfigure lightdm </pre><p>This was not necessary with the default installation procedure.</p><h4>Step 6. Add custom swap file (optional)</h4><p>Swap spaces are used when the OS runs out of RAM and wants to offload some unused data in the RAM. By default, Ubuntu installation only creates ~800MB of swap space, which is tiny compared to what is usually expected (about the same size of your RAM). Fortunately, we can create a swap file within our main partition to basically do the same. For more details, please read <a href="https://linuxize.com/post/how-to-add-swap-space-on-ubuntu-20-04/">How to Add Swap Space on Ubuntu 20.04</a>.</p><h4>Step 7. Reconnect your internal drives</h4><p>Once you finish your setup and make sure that Ubuntu boots properly, it is safe to go back into the boot menu and re-enable the internal drives. Upon reboot, if Ubuntu doesn’t show, go back into the boot menu and reorder the boot sequence so that your Ubuntu SSD drive will boot first.</p><h3>Final thoughts</h3><p>Although the final procedure I converged to is fairly straightforward, it has been a long journey since I had to eliminate all other possibilities of failure along the way by the method of trial and error. I hope this article will help some people avoid potentially wasting a lot of time chasing red herring error messages (if your installation or reboot stops with a certain log message, that doesn’t necessarily mean that that is a warning you should care about, especially if it doesn’t explicitly say “error”).</p><p>But I can assure you that the effort is totally worth it! You will never buy a new laptop again just because you are running out of internal disk space, which will save both your wallet and the planet!</p><h3>Helpful resources</h3><ul><li><a href="https://www.howtogeek.com/howto/linux/create-a-bootable-ubuntu-usb-flash-drive-the-easy-way/">How to Create a Bootable Linux USB Flash Drive, the Easy Way</a></li><li><a href="https://linuxhint.com/install-ubuntu-external-hard-drive/">How to Install Ubuntu on an External Hard Drive</a></li><li><a href="https://codepre.com/en/como-crear-un-disco-usb-de-arranque-desde-la-terminal-de-ubuntu.html">How to create a bootable USB drive from Ubuntu terminal?</a></li><li><a href="https://www.58bits.com/blog/2020/02/28/how-create-truly-portable-ubuntu-installation-external-usb-hdd-or-ssd">How to Create a Truly Portable Ubuntu Installation on an External USB HDD or SSD</a></li><li><a href="https://linuxize.com/post/how-to-add-swap-space-on-ubuntu-20-04/">How to Add Swap Space on Ubuntu 20.04</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=388294e701b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/installing-linux-ubuntu-20-04-on-an-external-portable-ssd-and-pitfalls-to-be-aware-of-388294e701b5">Installing Linux (Ubuntu 20.04) on an external portable SSD and pitfalls to be aware of</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do machines plan? —An overview]]></title>
            <link>https://medium.com/data-science/how-do-machines-plan-an-overview-a96a1aaa6dfa?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/a96a1aaa6dfa</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Fri, 16 Apr 2021 15:37:07 GMT</pubDate>
            <atom:updated>2021-04-20T16:27:25.240Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h3>How do machines plan? —An introduction</h3><h4>A gentle introduction to graph search algorithms and Markov Decision Processes</h4><p>The ability to plan into the future seems to be one of the key characteristics of intelligence. Physical actions such as walking, cycling, doing sports, or driving requires immense coordination, and the best possible moves depend highly on the external environment (you have to adapt and change your strategy if there is a stone, an obstacle or an opponent in your way). Moreover, most of the things we do day to day — commuting, shopping, cooking, studying, working, etc. — involve both short and long-term planning. Strategic games such as chess and Go are also famous examples where thinking ahead plays a crucial role.</p><p>Back in the 1950s, people have come up with mathematical ways to describe the procedure of planning. Now the variants of these methods can be found everywhere, from robot motion planning to finding the best route on Google Maps. In this article, we will look at some of the key formulations and planning algorithms, laying the foundation for future articles on planning and reinforcement learning (RL).</p><h3>States, actions and rewards (costs)</h3><p>It is easiest to visualise what a typical planning problem would look like in a navigation setting. Imagine that you are in a maze. You are at some location (x, y) and you can move in four directions — up, down, left and right — as long as you don’t run into a wall. If you reach the target you successfully terminate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_JiT_h2ezQv_Gs1KSXyog.png" /><figcaption>Robot in a grid maze (Image by author)</figcaption></figure><p>We describe the current situation we are in as <strong>states</strong>. If you are in location (x, y), x and y can be considered to be encoding the state you are in, because as long as you know x and y, assuming that the maze environment doesn’t change, we will be able to place ourselves at the right location and reconstruct the current situation. Typically, we think of <strong>states as a set of details that sufficiently summarises a specific situation</strong> we may encounter, and can be used to distinguish one unique situation from another.</p><p>If you think of a more realistic robot, you can summarise its configurations using a set of numbers— its pose (location and angle) and all the angles of its many joints, which can be considered states.</p><p>Once we are happy with our definition of states, we can think of moving between different states to reach a state we desire. For the example above, this would be reaching the location of the treasure chest. We can move between states by taking <strong>actions</strong>. In the above case, the actions that the robot can take are limited to moving up, down, left and right. But this doesn’t limit us from thinking of more complicated actions, such as taking longer strides or jumping over hedges, although we won’t consider them for now.</p><p>The final ingredient to the problem of planning is the idea of “cost” or “reward”. In shortest path search or in robotics, it is more typical to think of costs of each move, and try to minimise the total cost along the path. In the context of planning in games or environments where you can potentially boost up your scores, energy levels, net worth, etc., it is more common to think of rewards and trying to maximise the total rewards you can collect.</p><h3>Planning as a search problem</h3><p>Earlier work in planning have focussed on problems with a finite number of states, with each action leading to a deterministic transition between states. In other words, whenever you take an action, you can be confident of which state you will go to next. This is exactly like the grid maze problem we have just seen.</p><p>Because we want to evaluate the shortest path to the target, we assign a cost of 1 to each move and try to minimise the total cost before reaching the target. We can now convert our grid maze problem into a shortest path problem for the state transitions illustrated below on the left. The shortest path that can take us from the initial state to the target state will also minimise the total transition cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QH0FvBukkvfBhyRymIkhzQ.png" /><figcaption>Graphs for evaluating the shortest path (Image by author)</figcaption></figure><p>In a more general case, we can solve shortest path problems for any given connected network (e.g. houses connected by paths on the right). These kind of networks are called “graphs” in maths. There are nodes (in blue) which represents states, and edges (in brown) which represents transitions between states. Graph search algorithms such as Dijkstra and A* can find optimal solutions to shortest path problems on a graph. Dijkstra’s algorithm come with the least amount of assumptions, whereas A* can be more efficient in its search if you have a rough guess (heuristics) of the priorities of expanding the nodes.</p><p>In the interest of the length of this article, I will move onto a more general formulation of planning, which is Markov Decision Processes. However, graph search algorithms are very important for solving complex real-world problems such as robotics and shortest path search. If you want to learn more about Dijkstra’s algorithm and A*, I recommend this article with amazing interactive graphics.</p><p><a href="https://www.redblobgames.com/pathfinding/a-star/introduction.html">Red Blob Games: Introduction to the A* Algorithm</a></p><h3>How to describe a more general planning problem</h3><p>Graph search algorithms are great when you have a finite number of states with deterministic transitions between them. However, what if there’s some uncertainty in the transitions, or if there are an infinite number of states and transitions that can be made?</p><p>Let’s look at a slightly more involved example of planning — chess. What would states and actions look like in this context?</p><p>Since each state should capture unique details about the current situation, a plausible choice may be to encode locations of every piece on the board ({‘black king’: G8, ‘black queen’: D8, …, ‘white king’: G1, ‘white queen’: D1…}). The exact way of encoding this is not too important, as long as they have a one-to-one mapping with the board state, and indeed, many chess game engines have come up with different ways of encoding the board state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MmDGgbyODmokPrkrliF_g.png" /><figcaption>Chess game state, action and transition (Image by author, <a href="https://en.wikipedia.org/wiki/Chess_piece">chess pieces from Wikipedia</a>)</figcaption></figure><p>There are more possible actions in chess (what you can do to move from one state to another). On average, there are about 30 moves you can make per turn, because you can choose which piece to move and each piece has a set of moves they can make. Let’s say we chose the bishop. The actions we can take in this case are highlighted in green. Once we choose an action, we end up in the next board state, shown on the right.</p><p>The interesting thing here is that, because chess is a two-player game, we cannot fully determine the next game state by just choosing our action. The opponent gets to make a move as well, so while we have some idea of what possible next states we can end up in, which state that would be is opened to some uncertainty.</p><p>As with most games, there are game states that are more desirable in chess. The most obvious ones are those states when you’ve taken the opponent’s king and you’ve won. The less obvious ones are those where you haven’t won yet but are very close to winning.</p><p>Finally, let’s imagine a more real-world problem of driving through some obstacle course. As we’ve discussed, the state of the car can be summarised by its pose (location and angle) as well as the wheel velocity, acceleration, steering angle, the amount of fuel remaining, etc. Actions that take the car from one state to another may be how much you accelerate, break, steer, and top up the fuel.</p><p>What makes it difficult in driving or robotics in general is that, unlike the grid maze example or chess, the states and the actions are often continuous. If you are driving the car, you don’t just steer fully to the left or fully to the right; you can accelerate, break, or rotate the steering wheel smoothly, and the resulting position, velocity, acceleration and angle of the car and its wheels all take continuous values. This makes planning in this state space a very hard problem to solve.</p><p>Similarly to chess, driving is a multi-agent planning problem, meaning that you have to coordinate with others on the streets who are also driving, cycling or walking. Since we don’t have telepathy yet, we have to make decisions without the full knowledge of what others might decide. There are also environment states that are not fully-known to us, such as when the traffic lights will change next, whether there is a traffic jam in the next intersection, or where exactly we are at right now if we are in a tunnel and don’t have GPS signal.</p><p>In the real world, there are many more planning problems that are difficult to solve. What if you are on a road trip and your goal is to visit as many scenic places as possible? There isn’t a single obvious target to be reached in this case. What if you want your AI to learn the best strategy for stock investment, and keep reinvesting your earnings? At which point would you even evaluate the AI’s performance if there isn’t a clear end to this task?</p><h4>Range of planning problems</h4><p>We have already seen a lot of similarities and differences in planning problems we might be interested in solving. There are many more assumptions we have made in some of our examples, and adding or removing assumptions can make the problem look entirely different, and with different problems, different solutions arise.</p><p><strong>Commonalities:</strong></p><ul><li>The aim is to find a good strategy that allows us to decide which actions to take under a given situation (at a given state)</li><li>There is some kind of mapping between distinct situations and states</li><li>Actions can influence a transition from one state to another</li><li>There is some kind of reward or cost that can be gathered during each transition</li><li>There is a notion of desirability (value) of being in a certain state</li></ul><p><strong>Different assumptions depending on the problem:</strong></p><ul><li>Sometimes, it is uncertainty in which state you will end up in after you take an action, either because the state transition is noisy / probabilistic, or because there are others who are also making decisions. There are algorithms developed specifically for two-player games, such as minimax and alpha-beta pruning. In a more general case, we can model a probabilistic state transition as a Markov Decision Process (MDP), which we will discuss next. The problem involving other agents is called a multi-agent problem, and there can be additional considerations that can be made based on whether the agents are cooperating or competing, and whether they are allowed to communicate with each other.</li><li>Sometimes, the rewards you can get for each transition can also be probabilistic.</li><li>In many cases, the state transition and reward dynamics of the environment are unknown until you try things out and see what happens, so it is difficult to plan things ahead without some trial-and-error. This is the main assumption of reinforcement learning, and this dilemma is referred to as “exploitation vs exploration”.</li><li>Sometimes, the states and/or actions can be continuous, which means that discrete planning algorithms such as Dijkstra and A* would no longer work. In robotics, one common approach is to discretise or sample the state space, produce a rough shortest trajectory estimate, and then apply control theory to find a suitable continuous control input that minimises the error between the trajectory estimate and the actual trajectory taken by the robot. With the success of deep learning, however, it has become possible to model a continuous function using neural networks, opening up a range of possibilities to directly plan in continuous space.</li><li>Sometimes, the state we are in cannot be measured exactly. In robotics, where there is limited range of sensor inputs, the most common problem is localisation, i.e. knowing exactly where the robot is at the moment. A Kalman filter is one of the techniques used to estimate the state, given some noisy measurements and observations. <a href="https://medium.com/swlh/how-robots-make-maps-an-intro-to-slam-simultaneous-localisation-and-mapping-37370c3e7dfe">SLAM (Simultaneous Localisation and Mapping)</a> is an entire field dedicated to estimating the current position of the robot from camera inputs. More generally, the true state is unknown because we cannot observe the states directly (like whether we have cancer, or the exact position and velocity of every particle in the universe), so we have to estimate them based on a limited amount of observations. A relevant field in reinforcement learning is called POMDP (Partially Observable Markov Decision Process).</li></ul><p>These are the motivation for introducing a more general planning paradigm which takes into account these uncertainties — Markov Decision Processes.</p><h3>Markov Decision Process (MDP)</h3><p>Let us think of a general planning problem. Whether that be a robot, chess or driving, there is always a decision making entity that changes the situation by taking actions. We call the decision making entity an <strong>agent</strong>, and everything external to it the <strong>environment</strong>. Usually, we humans are the agent if we are the ones playing chess, moving around a room or driving. When we solve these problems using an algorithm, the computer algorithms themselves become the agent. The agent can take actions in the environment to reach a new state. The environment is something that provides the agent knowledge about the current state, as well as and the rewards for every state transition that the agent initiates.</p><p><strong>State</strong>s <em>s</em> ∈ <em>S</em> (we denote the set of possible states as <em>S</em>, and each state as <em>s</em>), as described before, is a unique encoding of a specific situation. The current state can either be directly measured or observed (as with chess where the board state is fully known, or a robot arm with fully-known configurations of joints) or has to be inferred from observations provided by the environment (as with driving, where the driver has to infer the current position and velocity of the car, or with a robot which isn’t fully localised).</p><p>The agent can initiate transitions from one state to another by taking <strong>actions </strong><em>a</em> ∈ <em>A</em>(<em>s</em>) (the actions that are available can depend on which state you are in, so the set of actions can be a function of state <em>s</em>). This will trigger a change in the environment, and the environment will update the agent with observations of the new state, as well as a <strong>reward </strong><em>r</em>.<strong> </strong>The reward can be positive, such as when you made a move resulting in check-mate in chess or correctly predicting the rise in stock, but can also be negative, such as loosing the game, running out of fuel or driving into an obstacle. The rewards are usually a function of the current state <em>s</em>, the action taken by the agent <em>a</em>, and the new state <em>s’</em>, and is written as <em>R</em>(<em>s</em>, <em>a</em>, <em>s’</em>).</p><p>Finally, we can also define a transition probability from the current state <em>s</em> to the new state <em>s’</em>, based on some action <em>a </em>as <em>P</em>(<em>s’</em>|<em>s</em>, <em>a</em>). This is a conditional probability because we want to know which state we will end up in, given that we are in state <em>s</em> and have taken the action <em>a</em>.</p><p>Let’s illustrate this with a hypothetical scenario where we want to decide whether it is better to going to school by flying on brooms or by teleportation. (Note: I was initially going for a more daily example, but it was difficult to come up with probabilities which are both plausible and easy to inspect, so let’s go with a hypothetical example.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUcb7Ps5PKDgELh2-XDlpQ.png" /><figcaption>A simple Markov Decision Process for a hypothetical transport system (Image by author)</figcaption></figure><p>As illustrated, your starting state <em>s</em> is “home”, and there are three outcomes — school, hospital and kidnapped. If you teleport, it is faster so the rewards for getting to school is higher, but it is riskier so you are more likely to end up in hospital with a severe injury. On the other hand, travelling by broom is slower and is more exposed so there is a chance that you will be kidnapped by aliens.</p><p>Let’s decide whether we should take an action “travel by broom” or “teleport”. We can calculate the expectation of rewards (the rewards averaged over the probabilities) for each action (Σ <em>P</em>(<em>s’</em>|<em>s</em>, <em>a</em>)<em>R</em>(<em>s</em>, <em>a</em>, <em>s’</em>))</p><p><em>a=</em>“broom”: 0.8 * 1 + 0.1 * (-10) + 0.1 * (-100) = -10.2</p><p><em>a=</em>“teleport”: 0.7 * 5 + 0.25 * (-15) + 0.05 * (-100) = -5.25</p><p>Therefore, in this simple example we found that teleportation gives us the maximum amount of expected rewards for this single move.</p><h3>Maximising the total expected rewards</h3><p>While the above example just had a single step of transitions with immediate rewards, in a typical planning problem such as chess, you need to plan ahead and take actions strategically based on your future reward estimates, not just the immediate rewards. More specifically, we should maximise the sum of the rewards we expect in the future. The sum of future rewards are referred to as <strong>returns </strong><em>G</em>, and our objective is to find a strategy that maximises it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*gI1RVG3UsxCVRV4CClxxFg.png" /><figcaption>Definition of return</figcaption></figure><p>Back to our grid maze example, the return at the starting point will be the sum of all the costs to move around and the final reward for reaching the target. Let’s say that the robot took 6 steps to reach the treasure chest, and receives a reward of -1 at every step, but receives a reward of 10 when it reaches the treasure chest. In this case the return is (-1) * 6 + 10 = 4.</p><p>Note that in the definition of return, there is a discount factor γ. Some planning problems have no definite end, so rewards keep accumulating indefinitely. To prevent the return to become infinity, we discount future rewards by multiplying γ &lt; 1 (something like γ≈0.99 would do).</p><h3>Thoughts</h3><p>I hope this has been helpful to gain some intuition as to how planning problems can be described mathematically, and how the formulation of planning with an MDP is more complex than graph search, but that also allows us to model a more general planning problem.</p><p>Usually, the concepts of states, actions and rewards are introduced as a part of the MDP formulation, used in reinforcement learning. In this article, however, I wanted to introduce the idea of states, actions and rewards (costs) more generally, because those ideas are not unique to RL or MDPs, but also appear in robotics, control theory and probability theory, which all have a long history and a lot of great work. Once we start to see these relationships, we start to see that e.g. cumulative costs in Dijkstra’s algorithm and values in reinforcement learning are identical under some assumptions, only formulated in different ways.</p><p>In future articles, we will examine reinforcement learning in more depth, look at different methods to arrive at a good strategy, and discuss the intuitions behind them.</p><h4>Related articles</h4><p><a href="https://medium.com/swlh/how-robots-make-maps-an-intro-to-slam-simultaneous-localisation-and-mapping-37370c3e7dfe">How Robots Make Maps— An Intro to SLAM (Simultaneous Localisation and Mapping)</a></p><h4>References</h4><ul><li>Richard S. Sutton and Andrew G. Barto. <a href="http://www.incompleteideas.net/book/the-book.html">Reinforcement Learning: An Introduction, Second Edition</a> (2018), MIT Press</li><li>Steven M. LaValle. <a href="http://lavalle.pl/planning/">Planning Algorithms</a> (2006), Cambridge University Press</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a96a1aaa6dfa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-do-machines-plan-an-overview-a96a1aaa6dfa">How do machines plan? —An overview</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 hints AI gives us about life]]></title>
            <link>https://medium.com/tech-to-inspire/3-hints-ai-gives-us-about-life-23ed0410a706?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/23ed0410a706</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[personal-development]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 15:17:11 GMT</pubDate>
            <atom:updated>2021-01-30T15:42:17.267Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to perform stochastic gradient ascent towards your goals</h4><p>While maths, algorithms and data science can seem abstract and indifferent to our day-to-day worries and woes, I find it amusing how they can sometimes provide a perfect analogy to the problems and lessons we encounter in life. Here, I selected three observations that we can make from practices in machine learning and planning, which may give us hints on how we, in turn, can navigate the complexities of life to reach a near-optimal solution.</p><p>(Disclaimer: I have no intentions to claim that I know how to navigate life effectively — on the contrary, my weights are under-tuned and my gradients are steep, so please enjoy this just as a casual read! Also, I am using the term “AI” fairly loosely here.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*_JDnGsXCW7YiQNCmbXTtUg.png" /><figcaption>An objective function with optimisable parameters (Source: <a href="https://www.coursera.org/learn/machine-learning/lecture/8SpIM/gradient-descent">Andrew Ng, Coursera</a>)</figcaption></figure><h4><strong>1. Learn from the past, but don’t get caught up in it.</strong></h4><p>After all, machine learning is all about learning from data — data that has been collected in the past. Unlike something like expert systems, which has built-in fixed conditions for decision making that cannot self-improve, the systems that employs machine learning can continually learn and improve with more data, adapting to possible changes in the environment or the application domain.</p><p>Analogously, we humans also learn from past experiences. Through trial and error, we collect experiences, update our knowledge and beliefs about the world to best explain past observations, and adapt our behaviour policy accordingly to maximise our expected future outcome.</p><p>We learn history because there are recurring patterns in historical events and humans tend to make similar mistakes, and we might be able to harvest valuable insight by studying them. In reinforcement learning (RL), one effective technique for improving performances is “experience replay”, in which the algorithm keeps past experiences in a memory bank and keeps retraining on it so that the learning won’t be forgotten.</p><p>So we know that learning from the past is useful and important. However, learning from the past alone is not enough. That is the biggest distinction between supervised learning methods that passively train on a fixed collection of data, and RL which actively collects new experiences. An effective RL algorithm should have a healthy mix of trying things that worked before (exploitation) and trying out new things (exploration). It is like how you might try out different dishes at a restaurant. On every visit, you would include some dishes that you know you like so that you are guaranteed to have an overall satisfying meal, but you would also order something different in the hope that you might discover a hidden gem that you can add to your list of favourites. This is actually a Multi-Armed Bandit (MAB) problem, which is a subset of RL.</p><p>Not totally depending on your past experience is important for another reason, which is that things can change over time, and we have to adapt our behaviour to the new environment. In the context of RL and MAB, this is called a non-stationary reward problem. Maybe the chef of the restaurant has changed, in which case, we could no longer rely on our past experiences.</p><p>We humans are heavily governed by our past experiences. Sometimes we get caught up in our past, maybe because of a single traumatic incident, which affects every decision we take from then on. However, that cautious approach might prevent us from discovering a way forward, trapping us in a <em>local optimum</em>. Whilst we cannot and should not explore the entire state space, some of which have severe consequences with no paths leading back, it is good to <strong>get out of our comfort zone</strong>, maintaining a healthy balance between exploration and exploitation, and not let ourselves <em>overfit </em>to our past experiences but to learn a more general <em>policy</em>.</p><h4><strong>2. A greedy algorithm isn’t always optimal, but with a good heuristic function, you can navigate efficiently.</strong></h4><p>Have you ever regretted your choices? It is easy to be wise in hindsight, since now we have obtained new information that wasn’t available in the past. Looking back, it all seems so obvious what the correct decision would have been.</p><p>But is that really the case? Unless you are at your death-bed (in which case you probably wouldn’t be reading this anyway), you still have a long time to make up for your past mistakes. In fact, we never know when it is time to say, “in hindsight, this was the correct thing to do”. Time goes on, and what seemed right can turn out to be wrong, unforeseen opportunities may arise, and what seemed like a big mistake can help us avoid bigger failures, provided that we learn from our mistakes.</p><p>There are two classes of planning problems — one where the environment is fully-known and the other where it is only partially known. In our lives, we always have to deal with the latter. We never know whether job opportunities will remain open, whether the stock prices will go up or down, whether the feeling you have towards that person is (or remains) mutual, or if life will go back to normal any time soon.</p><p>In a partially known setting, the best we can do is to make the best possible decision given what is known at present and what we estimate will happen in the future. A good heuristic function will guide us to make decisions that are good in the long-run, and to avoid unwanted consequences, when other “greedy” decisions with immediate rewards might seem more appealing in the short-term. Every failure and mistake we make, every unfortunate circumstances give us an opportunity to reconsider and update our heuristics, giving us a better chance to make a better decision in the future.</p><p>What is so miraculous about humans (and other species which communicate via language) is that we can transfer our knowledge and wisdom with words, allowing others to update their heuristic functions without them having to go through the same unpleasant experiences. This is somewhat analogous to parallel policy updates in reinforcement learning where millions of agents are spawn, each collecting experiences individually and then communicating how the policy should be updated.</p><p>So don’t regret your past choices. Instead, use those gradients to update your policy so that you won’t make the same mistakes, and maybe that will guide you to a state that is much better than where you would have ended up otherwise.</p><h4><strong>3. Diversity and combined effort made neural networks successful.</strong></h4><p>What made neural networks so successful as a machine learning method? A lot of credit goes to the insight that deep networks can approximate more complex functions, and the back-propagation algorithm which made parameter updates efficient even for deeper networks. But the other dimension — the width of the network, i. e. the number of channels —where features are learnt and detected, is also important. The more channels a layer has, the more diverse the features it can recognise becomes. Each channel is different from another. They diversify so that it can cover the entire spectrum of relevant features that are useful for subsequent layers.</p><p>Dropout, which randomly masks out some outputs at intermediate layers, encourages robustness in the feature representation such that, even if one feature is missing, the other features can make up for it.</p><p>We are also very diverse. We have different backgrounds, interests, opinions and lifestyle. While such differences present many challenges that we must overcome, such diversity is also our fundamental strength. Imagine how boring and dysfunctional the world will be if everyone likes to do the same job, has the same food, lives in the same place, and shares the same belief (which may or may not be true). While it would be easy to satisfy everyone, there will no longer be any specialties, and it would not be possible for us as a species to explore the entire spectrum of human capabilities. The lack of diversity will also make us vulnerable to certain types of risks.</p><p>Channels in neural networks are very good at diversifying and specialising, but also at cooperating. In a typical neural network architecture, a layer receives outputs from all channels in the previous channel, and each of them decide independently how much they want to listen to each previous channel. Whilst some channels might be more useful for certain types of input more than others, every channel has its contribution. The advantage of diversity and cooperation is clear from the fact that ensemble methods always perform equally or better than any sub-component.</p><p>It is worth noting here that, while these channels are diverse, they all share one thing — combined together, they all share a unique goal of optimising the objective function. They are not merely trying to be different from each other. Although they start at randomly initialised states, looking at different directions, once they start their gradient descent, they all start work towards the same goal, but each following their own paths, improving upon their specialties. I think this is a beautiful thought.</p><p>We, human species, have not yet agreed upon a single objective function we are optimising. It is unclear whether there is even such a function in the first place. However, if there is such a thing, my hope is that we can all play a part in our own ways, using our own strengths, whilst valuing each other’s contribution and accepting their differences, taking one small optimisation step down the gradient towards a brighter and kinder future.</p><p>Thank you for reading this article. If you liked it, please have a look at a related article below where I translated 25 proverbs into AI context:)</p><p><a href="https://medium.com/tech-to-inspire/25-proverbs-in-ai-language-949ab9531202">25 proverbs in AI language</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23ed0410a706" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-to-inspire/3-hints-ai-gives-us-about-life-23ed0410a706">3 hints AI gives us about life</a> was originally published in <a href="https://medium.com/tech-to-inspire">Tech to Inspire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[25 proverbs in AI language]]></title>
            <link>https://medium.com/tech-to-inspire/25-proverbs-in-ai-language-949ab9531202?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/949ab9531202</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 11:44:33 GMT</pubDate>
            <atom:updated>2021-01-30T15:35:27.574Z</atom:updated>
            <content:encoded><![CDATA[<h4>Training of a 1000 epochs begins with a single gradient descent</h4><p>It is fascinating how so many proverbs have endured the test of time and are still used in literature and daily conversations. The beauty of proverbs is that so many people can relate to them. This can be observed both from the abundance of synonymous proverbs and the number of proverbs that have spread cross-culture and cross-language.</p><p>As a research student who spends time with neural networks, I thought it would be fun to rephrase some of these well-known proverbs using AI terminology, and see how well they preserve the meaning of the original. The hope is that this will make neural network jargon more relatable and approachable. The meaning of the proverb is written beneath each translation, so whether you are knowledgeable in the field, you can try to guess the original proverbs from the description.</p><p>All the below translations are my own work. Feel free to use these quotes in your daily life (at your own personal risk of scaring away your friends), but <strong>please reference/link this article</strong> if you want to use any of these in written form.</p><p>Disclaimer: some of the quotes below are not technically-speaking always true, but that goes the same with proverbs, so please take it easy. I’d be opened to any suggestions for improvements:)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4zps_l5CIWfPfkvH" /><figcaption>Photo by <a href="https://unsplash.com/@joncas89?utm_source=medium&amp;utm_medium=referral">Jonathan J. Castellon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>1. Training of a 1000 epochs begins with a single gradient descent</h4><p>Even the longest and most difficult ventures have a starting point; something which begins with one first step. —[<a href="https://en.wikipedia.org/wiki/A_journey_of_a_thousand_miles_begins_with_a_single_step">see answer</a>]</p><p>An epoch refers to one cycle through the full training dataset. Usually each epoch is further broken down into several mini-batches. A neural network is trained by applying gradient descent to its parameters for every mini-batch.</p><h4>2. All that has a derivative of zero is not a global optimum</h4><p>Not everything that looks precious or true (or optimal) turns out to be so. — [<a href="https://en.wikipedia.org/wiki/All_that_glitters_is_not_gold">see answer</a>]</p><p>The goal of machine learning is to find a set of parameters which optimises an objective function. At a global optimum (the best possible solution), the derivative of the objective function becomes zero, but that is also true for local minima, maxima and saddle points.</p><h4>3. Set a stupid objective function, get a stupid prediction</h4><p>If one asks a strange or nonsensical question, the listener will probably respond with a similarly strange or nonsensical answer. — [<a href="https://en.wiktionary.org/wiki/ask_a_stupid_question,_get_a_stupid_answer">see answer</a>]</p><p>The objective function should define the problem an AI should solve; otherwise the prediction that the AI makes will be meaningless.</p><h4>4. Bad gradients propagate fast</h4><p>Bad news circulates quickly because people often spread it everywhere. — [<a href="https://en.wiktionary.org/wiki/bad_news_travels_fast">see answer</a></p><p>Out-of-distribution training samples, often known as outliers, will most likely result in large losses and gradients. Regularisation techniques and dropout may be good measures to counter overfitting to these samples.</p><h4>5. Interpretability lies in the eyes of the researcher</h4><p>Different people have different views on what is beautiful (or interpretable). — [<a href="https://en.wiktionary.org/wiki/beauty_is_in_the_eye_of_the_beholder">see answer</a>]</p><p>It is often not clear how a neural network is making a prediction just by inspecting its parameters and intermediate outputs. Many methods have been developed to make it more interpretable, but it remains an actively investigated topic in AI research.</p><h4>6. Convergence of loss comes to those who wait</h4><p>A patient person will be satisfied in due time; patience is a virtue. — [<a href="https://en.wiktionary.org/wiki/good_things_come_to_those_who_wait">see answer</a>]</p><p>Big neural networks can take a very long time to converge, but when it does, it often outperforms smaller ones.</p><h4>7. A watched plot never improves</h4><p>A process appears to go more slowly if one waits for it rather than engaging in other activities. — [<a href="https://en.wiktionary.org/wiki/a_watched_pot_never_boils">see answer</a>]</p><p>Here, a plot means a graph that shows the loss over training.</p><h4>8. Data leakage leads to overfitting</h4><p>One does not profit by cheating. — [<a href="https://en.wiktionary.org/wiki/cheats_never_prosper#English">see answer</a>]</p><p>In machine learning, it is common practice to split data into training, validation and test datasets, and only use the training dataset for training. One could cheat by leaking information from the validation and test datasets into the training dataset, but then the model will most likely fail in real-world settings because it has overfitted to the dataset.</p><h4>9. Don’t delete your checkpoints</h4><p>Don’t do something which forces you to continue with a particular course of action, and make it impossible for you to return to an earlier situation. — [<a href="https://en.wiktionary.org/wiki/burn_one%27s_bridges">see answer</a>]</p><p>Checkpoints are network parameters that are saved during training after every couple of epochs.</p><h4>10. There’s no point crying over killed processes</h4><p>To worry about unfortunate events which have already happened and which cannot be changed. — [<a href="https://en.wiktionary.org/wiki/cry_over_spilt_milk#English">see answer</a>]</p><p>Always save your intermediate results to avoid having to start from scratch if your process dies mid-training:(</p><h4>11. Don’t change model architectures in mid-training</h4><p>To change one’s plan or approach when an effort is already underway or at another inopportune time. — [<a href="https://en.wiktionary.org/wiki/change_horses_in_midstream">see answer</a>]</p><p>Usually, once you define your model, you won’t be able to change it mid-training if you don’t want to start from scratch again. (Instead, you can turn the training on and off for sub-components of your model.)</p><h4>12. Don’t judge a network by the number of parameters</h4><p>One shouldn’t prejudge the worth or value of something by its outward appearance alone. — [<a href="https://en.wikipedia.org/wiki/Don%27t_judge_a_book_by_its_cover">see answer</a>]</p><p>Unfortunately, size does matter for neural networks, but that’s not all. A cleverly designed architecture with shared parameters and additional constraints can go a long way, and also makes the network more robust and generalisable.</p><h4>13. Don’t put all your weights on one feature</h4><p>To make everything dependent on only one thing; to place all one’s resources in one place, account, etc. — [<a href="https://idioms.thefreedictionary.com/put+all+eggs+in+one+basket">see answer</a>]</p><p>Typically you would have many channels in a neural network layer, each channel computing some kind of feature. A robust network will not rely on one channel or feature alone, but makes its decision based on a combination of different features. Dropout is one strategy to ensure such robustness.</p><h4>14. Don’t filter out the signal together with noise</h4><p>To discard, especially inadvertently, something valuable while in the process of removing or rejecting something unwanted. — [<a href="https://en.wiktionary.org/wiki/throw_the_baby_out_with_the_bathwater">see answer</a>]</p><h4>15. Don’t try to segment before you can classify</h4><p>You must master a basic skill before you are able to learn more complex things. — [<a href="https://idioms.thefreedictionary.com/We+must+learn+to+walk+before+we+can+run">see answer</a>]</p><p>Image classification is simpler and is a necessary step to image segmentation, which is a problem of classifying every pixel in an image instead of just classifying the entire image.</p><h4>16. Reinitialise pre-trained embeddings</h4><p>To spoil one’s plans or hope of success. — [<a href="https://en.wiktionary.org/wiki/cook_someone%27s_goose#English">see answer</a>]</p><p>Pre-trained embeddings are learnt features that can help accelerate downstream tasks.</p><h4><strong>17. Returns are maximised by agents who self-play</strong></h4><p>You cannot depend solely on divine help, but must work yourself to get what you want. — [<a href="https://idioms.thefreedictionary.com/God+helps+those+who+help+themselves">see answer</a>]</p><p>A return is a discounted sum of future rewards. In reinforcement learning, the objective is to find a strategy to maximise the expected return. In the famous example of AlphaZero, an AI learnt to play Go, chess and Shogi at a super-human level, just by playing against itself.</p><h4>18. It’s all neural network parameters to me</h4><p>A way of saying that something is difficult to understand. — [<a href="https://en.wikipedia.org/wiki/Greek_to_me">see answer</a>]</p><h4>19. No model can be optimised for two objective functions</h4><p>You cannot work for two different people, organisations, or purposes in good faith, because you will end up favoring one over the other. — [<a href="https://idioms.thefreedictionary.com/No+man+can+serve+two+masters">see answer</a>]</p><p>An objective function defines the problem the AI must solve. If you give it two objectives that contradict each other, the AI can’t give an optimal solution to both simultaneously.</p><h4>20. The gradient is always steeper on the other side</h4><p>People always think they would be happier in a different set of circumstances. — [<a href="https://idioms.thefreedictionary.com/The+grass+is+always+greener+on+the+other+side">see answer</a>]</p><p>Steep gradients are good because that means you have more scope to improve your parameters and reach a better solution (but not too steep).</p><h4>21. Adversary and loss make a network wise</h4><p>We gain wisdom faster in difficult times than in prosperous times. — [<a href="https://ythi.net/idioms-proverbs/english/adversity-and-loss-make-a-man-wise/">see answer</a>]</p><p>Defining a loss as an objective to minimise is a typical way to train a neural network. A family of networks called Generative Adversarial Networks also employs adversity to train itself. Typical applications are for realistic image generation.</p><h4>22. GPT-3 wasn’t trained in a day</h4><p>It takes a lot of time to achieve something important. — [<a href="https://idioms.thefreedictionary.com/Rome+wasn%27t+built+in+a+day">see answer</a>]</p><p>GPT-3 is a massive state-of-the-art network that can perform a variety of language-related tasks.</p><h4>23. Multi-head attention is better than single-head</h4><p>It is better to have the power of two people’s minds to solve a problem or come up with an idea than just one person on their own. — [<a href="https://idioms.thefreedictionary.com/Two+heads+are+better+than+one">see answer</a>]</p><p>Multi-head attention is a mechanism used in Transformers, a neural network architecture that has been shown to be highly effective at capturing the complexity of language. GPT-3 uses Transformers as its building block.</p><h4>24. Where there’s a gradient, there’s a loss</h4><p>Every rumor has some foundation; when things appear suspicious, something is wrong. — [<a href="https://idioms.thefreedictionary.com/where+there%27s+smoke%2c+there%27s+fire">see answer</a>]</p><h4>25. Don’t put a fully-connected layer before a convolutional layer</h4><p>Do not do things in the wrong order. — [<a href="https://idioms.thefreedictionary.com/don%27t+put+the+cart+before+the+horse">see answer</a>]</p><p>Convolutional layers typically appear in computer vision tasks. It is very likely that a fully-connected layer comes after a convolutional layer, not before (although nothing is impossible).</p><p>That’s it! I hope you’ve enjoyed it. Here are the original proverbs:</p><ol><li>A journey of a thousand miles begins with a single step</li><li>All that glitters is not gold</li><li>Ask a stupid question, get a stupid answer</li><li>Bad news travels fast</li><li>Beauty is in the eye of the beholder</li><li>Good things come to those who wait</li><li>A watched pot never boils</li><li>Cheats never prosper</li><li>Don’t burn your bridges behind you</li><li>There’s no point crying over spilt milk</li><li>Don’t change horses in midstream</li><li>Don’t judge a book by its cover</li><li>Don’t put all your eggs in one basket</li><li>Don’t throw the baby out with the bathwater</li><li>We must learn to walk before we can run</li><li>Cook someone’s goose</li><li>God helps those who help themselves</li><li>It’s all Greek to me</li><li>No man can serve two masters</li><li>The grass is always greener on the other side</li><li>Adversity and loss make a man wise</li><li>Rome wasn’t built in a day</li><li>Two heads are better than one</li><li>Where there’s smoke, there’s fire</li><li>Don’t put the cart before the horse</li></ol><p>If you liked this article, please also have a look at this article, where I draw analogies between our lives and how AI overcomes difficulties.</p><p><a href="https://medium.com/tech-to-inspire/3-hints-ai-gives-us-about-life-23ed0410a706">3 hints AI gives us about life</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=949ab9531202" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-to-inspire/25-proverbs-in-ai-language-949ab9531202">25 proverbs in AI language</a> was originally published in <a href="https://medium.com/tech-to-inspire">Tech to Inspire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Robots Make Maps— An Intro to SLAM (Simultaneous Localisation and Mapping)]]></title>
            <link>https://medium.com/swlh/how-robots-make-maps-an-intro-to-slam-simultaneous-localisation-and-mapping-37370c3e7dfe?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/37370c3e7dfe</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 21:37:50 GMT</pubDate>
            <atom:updated>2021-04-16T15:43:57.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Robots Make Maps— an Intro to SLAM (Simultaneous Localisation and Mapping)</h3><h4>A big picture of odometry, localisation, mapping, feature matching and loop closure for non-roboticists</h4><p>Remember the last time you’ve visited somewhere new? If you are reading this in 2020, you might have to rack your brain for those happy days. It may have been a holiday trip to an exotic place. You are excited to explore the area, check out all the nice restaurants and attractions. What would you do?</p><p>Yes, you <strong>read a map</strong>! (…or so it used to be)</p><p>Life has become too simplified nowadays with the intelligent little devices in our pockets, but let’s just imagine we are back in the stone ages. What if your phone has died and your only hope is a tourist guide in your backpack?</p><p>The first challenge is to find where you are. If you don’t have a GPS, you can’t just follow the blue blinking dot. You will probably look for street names or distinct landmarks nearby, and eventually, <strong>locate yourself</strong>. In robotics terms, this is called <strong><em>localisation</em></strong>. Once you know where you are and you know where you are going, you’re all sorted.</p><p>Well, what if you don’t have a map to begin with?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6GyQxrLyajs0JB10" /><figcaption>Photo by <a href="https://unsplash.com/@drscythe?utm_source=medium&amp;utm_medium=referral">Dominik Scythe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In theory, we can always explore the area to figure out where everything is relative to each other and memorise it, constructing a mental map. Even if we don’t have a ruler and a protractor, we roughly know how long our strides are and what a 90 degrees’ turn looks like. As we move, we know how far we moved by identifying landmarks we have previously observed. Furthermore, as soon as we see new landmarks and scenes, we can add those to our mental map to expand our territory of known places.</p><p>Many things are happening here. We used both (i) the estimate of our motion dynamics, and (ii) triangulation (broadly speaking) from known landmarks. Moreover, we (iii) updated our map as we obtain new observations. (i) tells us the change in our position i.e. <strong><em>odometry</em></strong>. If we have a good idea of where we were at previously, we can use the estimated odometry to figure out where we are now. Most robots operate on wheels so it is fairly easy to measure how much they’ve moved. Some robots even have sensors called<strong> inertial measurement unit (IMU)</strong> that measure their body motion. Even so, we cannot just rely on odometry alone to know where you are. That is like walking with your eyes closed. At some point, you have to open your eyes and correct for the accumulated error. That is what (ii) does. For (ii), you need a half-built map already to correct for your localisation. But in (iii), you are using your current best guess of where you are in order to update the map. This is why localisation and mapping has to happen <em>simultaneously</em>.</p><p>Even if we take carefully measured strides and construct the map carefully, it is impossible to rule out all kinds of noise. After a couple of turns, the error accumulates and we are no longer certain of our location. How do we make a recovery then?</p><p>This is where loop closure comes into play. Assuming that buildings and trees don’t move, we know when we do a full loop and come back to the same place we have been before (<strong>loop detection</strong>). We can then correct our mental map and adjust for the noise that had accumulated (<strong>loop closure</strong>).</p><p>The above is the core idea behind Simultaneous Localisation and Mapping, which is used very widely in any kind of robotics applications that require the robot to move around a new environment. It doesn’t have to be just robots — it can be used for smartphones and other devices with a camera too. Augmented Reality (AR), for instance, requires the virtual world to be mapped onto the real scenery with precision, so some advanced use cases would require SLAM as a part of the pipeline.</p><p>Now that you have constructed a map, you are armed with knowledge about the environment, ready to be used for future navigation. If you ever need to visit a place you’ve previously visited, you don’t even have to take the same route. You can take shortcuts and plan strategically (similarly to how you optimise your shopping route).</p><p>Unlike humans, different robots have different sensors and use cases, and there are many approaches to solving the same problem. That is why there are so many variations of SLAM systems out there. Here, I will try to present a high level picture of some of the major approaches and how they differ from each other. For a more detailed, comprehensive and accurate description, please refer to some of the survey papers [1, 2, 3].</p><h4><strong>Perfection or efficiency? — SLAM, SfM or VO</strong></h4><p>Even before we get started with different approaches in SLAM, let’s talk about the siblings of SLAM: Structure from Motion (SfM)<strong> </strong>[4] and Visual Odometry (VO)<strong> </strong>[1]. All these fields address the same problem —for a collection of images, estimate where the camera was when each image was taken, so that the images tell a consistent story when they are reverse-projected back into 3D world space. They share many procedural steps, such as feature detection, feature matching, and optimising the estimated pose based on a consistency metric. However, the constraints they assume are slightly different.</p><p><strong>Structure from Motion</strong> is a problem of reconstructing the 3D structure of the environment from a collection of 2D images. The images could be ordered or <strong>unordered</strong>, hence it cannot rely on odometry. Visual SLAM poses a more specific problem in which the images are captured sequentially by a camera that is moving through an environment, following some kind of trajectory. Some SfM algorithms focus more on <strong>accuracy and global consistency</strong> rather than time constraints, and can work at a very <strong>large scale</strong> if need be. For instance, SfM can be applied to reconstruct a subset of the globe in 3D from Google Street View images. Obviously, this takes a huge amount of time and resources, so such algorithms aren’t expected to run in real time. Hence, these are called <strong>offline methods</strong>. In contrast, the main purpose of SLAM is to aid the robot in its exploration and navigation, so real time execution is crucial. Hence, this falls under the category of <strong>online methods</strong>. (However, this distinction has become blurred with Incremental SfM which operates online, and many SLAM methods have borrowed the idea of Incremental SfM.)</p><p><strong>Visual Odometry</strong> simplifies the SLAM problem, focussing more on computational and resource efficiency. Rather than ensuring global consistency of the map it creates like SLAM does, VO’s main concern is about <strong>local consistency</strong>. Its goal is to estimate the odometry (differences in camera poses between two images taken one after another) without having to rely on sensors such as IMU or ground truth odometry measurements. If we don’t care about global consistency, the loop closure step can be taken away, saving us some computation and making the system simpler.</p><h4>Why do we have two eyes? — Stereo, Monocular, or Depth Camera</h4><p>Even if we were able to localise the camera, it would be a struggle to reconstruct the surroundings without knowing the depth of each pixel of the image i.e. how far the surface is from the camera. Humans and most animals have two eyes, because that allows us to figure out where objects are relative to us using triangulation. Similarly, the depth can be inferred using stereo cameras, with some extra work of finding correspondences between the two images by feature matching. There also exist depth cameras, which provides the depth information in addition to RGB, either by measuring the time of flight or the pattern density of the Infra Red light emitted from the camera. There is one disadvantage though — unlike stereo cameras, depth cameras only work for short distances (e.g. indoors).</p><p>Even with just a single camera, the depth can be inferred by comparing frames taken at different camera positions. In this case, the scale of the reconstructed map is unknown unless we use some other means to infer the scale.</p><p>Some other SLAM systems are developed for LASER or LiDAR scanners.</p><h4>How do we find correspondences and consistency between frames? — Feature-based Method vs Direct Method</h4><p>As we explore, we identify salient features such as landmarks and objects, which we use to match pieces of observations together and construct a consistent mental map. We now need to invent a convenient definition of “salient features” that our system can detect and match.</p><p>While landmarks such as buildings and sign posts work well for humans, it is much easier for machines to identify and match low level features such as corners, edges and blobs. More sophisticated feature definitions, together with detection algorithms and descriptors (a distinct feature representation) have been invented, such as Scale-invariant Feature Transform (<strong>SIFT</strong>) [5], Speeded Up Robust Features (<strong>SURF</strong>) [6] and Oriented FAST and Rotated BRIEF (<strong>ORB</strong>) [7, 8]. These features are designed to be robust to translation, rotation, variations in scale, view-point, lighting, etc.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FufvPS5wJAx0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DufvPS5wJAx0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FufvPS5wJAx0%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/e013dd65b0435dacae81c882a8d4827c/href">https://medium.com/media/e013dd65b0435dacae81c882a8d4827c/href</a></iframe><p>A limitation to the feature-based approach is that, once the features are extracted, all other information contained in the image is disregarded. This could be problematic when feature matching alone cannot offer robust reconstruction, e.g. in environments with too many or very few salient features, or with repetitive textures.</p><p>An alternative approach to feature-based matching is minimising the <strong>photometric </strong>(light intensity) <strong>error</strong>, which is called the <strong>direct method</strong>. Well-known examples are <strong>LSD-SLAM</strong> [9] and <strong>Direct Sparse Odometry</strong> [10]. These methods by-pass the computationally expensive process of feature extraction and matching, and can benefit from the rich information in the environment. However, it is sensitive to changes in lighting or large motions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoJt3Ln8H03s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoJt3Ln8H03s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoJt3Ln8H03s%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/4547b245afa6b48c11a19d1505fa94b0/href">https://medium.com/media/4547b245afa6b48c11a19d1505fa94b0/href</a></iframe><h4>How do we adjust camera poses? — RANSAC, Iterative Closest Point</h4><p>Now that we have identified some correspondences between successive frames, it is time to find the camera motion that best explain those matches. While something as simple as least squares would work well if all our matches are correct, we have to bare in mind that our correspondences are noisy and inaccurate. <strong>RANSAC </strong>[11] is a method widely used to estimate a transform from one set of data points to another. It randomly samples the minimum number of paired coordinates (<strong>Xᵢ</strong>, <strong>Yᵢ</strong>) required to estimate a transformation from set <strong>X</strong> to set <strong>Y</strong>. For every estimated transformation, the transformation is applied to all remaining data points in set <strong>X</strong> to see if the transformed points are close enough to their corresponding matches in set <strong>Y </strong>(these are called inliers). This process is repeated and the best transform that yielded a good number of inliers is kept as a final estimate.</p><p>Once we apply RANSAC, we have a fairly good estimate of the camera motion between two frames <strong>X</strong> and <strong>Y</strong>. Note though, that this was estimated only from the feature matches that we have, which doesn’t utilise the entire information obtainable from the images. We can further refine our estimate by reverse-projecting images into 3D for each frame as point clouds, and trying to align these point clouds together.</p><p><strong>Iterative Closest Point (ICP)</strong> is a common technique in computer vision for aligning 3D points obtained by different frames. Using the estimate given by RANSAC as an initial transform estimate, ICP aligns the closest points in two point clouds, using a fast nearest neighbour search, and re-estimates the transformation to minimise the distances between the matches. This process is performed iteratively until convergence.</p><h4>How do we correct the map? — Filter Methods vs Bundle Adjustment</h4><p>As the robot moves around, we may want to adjust our previous estimates of the camera poses, especially when loop closing happens, i.e. when the robot revisits somewhere we’ve seen previously. To make the matter complicated, adjusting the camera pose will also mean amending the map we have built using that camera pose. Again, this is why localisation and mapping is a chicken and egg problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejXBdmeUs1Y00v8hOCm32Q.png" /><figcaption>(a) Bundle Adjustment over all camera poses and features (b) Filter method (c) Key frame Bundle Adjustment. Image taken from [12]. <strong>T:</strong> camera trajectory, <strong>x: </strong>features</figcaption></figure><p>There are two main approaches to correcting the camera pose and map estimates — filter methods and bundle adjustment (BA) methods. The major difference is that, whereas <strong>bundle adjustment</strong> at its most basic form re-evaluates all the camera poses and feature poses in the map from scratch at every time step as a maximum likelihood estimate, <strong>filter methods</strong> represent its estimate of the camera and feature poses as a probability density function, allowing those estimates to be incrementally updated by taking new observations into account. <strong>Extended Karman Filters (EKF)</strong>, which gives a Bayesian solution to the state estimate update given new observations, is typically used. A multivariate Gaussian is a common choice to model probabilities for the state estimate and the observation noise. <strong>Particle Filters</strong>, which do not assume the shape of the probability density function, is another option within the family of filter methods.</p><p>While filter methods seem to have an advantage over BA methods in terms of reusing previous estimates, there is a hidden cost. Because filter methods only retain the most recent camera pose estimate together with feature nodes in the map, when it comes to updating the map based on accumulated error, we have to compute at how every feature node affects every other feature node. This is captured by the covariance matrix of the multivariate Gaussian, which grows as more and more features get added to the map.</p><p>A more computationally efficient approach to BA would be to evaluate the optimal solution on a subset of past camera poses and features. Typically, key frames which have distinct features are chosen at regular intervals, and only these will be used to compute the optimal poses in order to reduce computational complexity. More techniques have been developed to reduce the computational complexity of real-time BA, such as Pose Graph Optimisation. For a more in-depth comparison, see [12].</p><h4>When do we close the loop? — Place Recognition</h4><p>As we observed at the beginning of this article, loop closure is key to ensure a global consistency of the map that we construct. This aspect also characterises SLAM from other methods such as Visual Odometry.</p><p>There are three ways to find out whether you came back to the same place. You can either compare the current image frame to previous frames (image-to-image), compare the current frame against the map (image-to-map), or compare the current location in the map to other regions in the map (map-to-map).</p><p>For image-to-image comparison, Bag of Words (BoW) is an effective way to quickly narrow down candidates for corresponding frames. Bag of Words is a rather lazy way of describing images — basically it only cares about what kind of local features appears in the image, but throws away all the high level spatial context. However, this is effective for quickly looking up images that may have been taken from the same place.</p><h4>Challenges in SLAM</h4><p>We have barely scraped the surface of research in SLAM. We have yet to discuss some of the typical challenges in SLAM and how some systems overcome them. The ultimate goal is to make SLAM handle environments with too many or very few salient features, large scale environments, dynamic environments (i.e. with lots of moving objects or people), non-smooth movements of the camera, occlusions, transparency and reflection, while meeting computation time, memory and sensory device constraints.</p><h4>Related articles:</h4><p><a href="https://alacreme.medium.com/how-do-machines-plan-an-overview-a96a1aaa6dfa">How do machines plan? —An overview</a></p><p>[1] K. Yousif et al. <a href="https://link.springer.com/content/pdf/10.1007/s40903-015-0032-7.pdf">An Overview to Visual Odometry and Visual SLAM: Applications to Mobile Robotics</a> (2015), Intelligent Industrial Systems</p><p>[2] J. Fuentes-Pacheco et al. <a href="https://link.springer.com/content/pdf/10.1007/s10462-012-9365-8.pdf">Visual Simultaneous Localization and Mapping: A Survey</a> (2015), Artificial Intelligence Review</p><p>[3] M. R. U. Saputra et al. <a href="https://dl.acm.org/doi/pdf/10.1145/3177853">Visual SLAM and Structure from Motion in Dynamic Environments: A Survey</a> (2018), ACM Computing Surveys</p><p>[4] O. Ozyesil et al. <a href="https://arxiv.org/pdf/1701.08493.pdf">A Survey of Structure from Motion</a> (2017), Acta Numerica</p><p>[5] D. G. Lowe <a href="https://link.springer.com/content/pdf/10.1023/B:VISI.0000029664.99615.94.pdf">Distinctive Image Featuresfrom Scale-Invariant Keypoints</a> (2014), International Journal of Computer Vision</p><p>[6] H. Bay et al. <a href="https://people.ee.ethz.ch/~surf/eccv06.pdf">SURF: Speeded Up Robust Features</a> (2006), ECCV</p><p>[7] E. Rublee et al. <a href="http://www.willowgarage.com/sites/default/files/orb_final.pdf">ORB: an efficient alternative to SIFT or SURF</a> (2011), ICCV</p><p>[8] R. Mur-Artal et al. <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=7219438">ORB-SLAM: A Versatile and Accurate Monocular SLAM System</a> (2015), IEEE ROBIO</p><p>[9] J. Engel et al. <a href="https://link.springer.com/content/pdf/10.1007%2F978-3-319-10605-2_54.pdf">LSD-SLAM: Large-ScaleDirect Monocular SLAM</a> (2014), ECCV</p><p>[10] J. Engel et al. <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=7898369">Direct Sparse Odometry</a> (2018), IEEE Transactions on Pattern Analysis and Machine Intelligence</p><p>[11] M. Fischler et al. <a href="https://dl.acm.org/doi/pdf/10.1145/358669.358692">Random Sample Consensus: A Paradigm for Model Fitting with Applications to Image Analysis and Automated Cartography</a> (1981), Communications with the ACM</p><p>[12] H. Strasdat et al. <a href="https://www.doc.ic.ac.uk/~ajd/Publications/strasdat_etal_ivc2012.pdf">Visual SLAM: Why Filter?</a> (2012), Image and Vision Computing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37370c3e7dfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-robots-make-maps-an-intro-to-slam-simultaneous-localisation-and-mapping-37370c3e7dfe">How Robots Make Maps— An Intro to SLAM (Simultaneous Localisation and Mapping)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9 Steps to Reprogram Yourself and Stay Productive]]></title>
            <link>https://medium.com/tech-to-inspire/9-steps-that-helped-me-assess-myself-and-stay-productive-2c6044673092?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c6044673092</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[goals]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 09:10:01 GMT</pubDate>
            <atom:updated>2020-08-14T17:22:31.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vplM5-G0SG_YsLshftHT2w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@julensan09?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Julentto Photography</a> on <a href="https://unsplash.com/s/photos/sunrise?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We all have different ways of keeping ourselves focussed and productive. I have seen many hardworking fellow students with a variety of strategies, and there are some habits I’ve adopted myself. I don’t pretend to have a comprehensive list of all the tricks and habits that can work. However, I do think that there is an underlying theme to these approaches. Here, I want to share what I believe to be some of the essentials to keep in mind.</p><h4><strong>Step 1: Know Your Strengths and Weaknesses</strong></h4><p>Different approaches work for different people, so it is important to sit down and assess yourself to figure out what works for you best. Some of the things worth asking yourself are:</p><ul><li>What do I find passion in?</li><li>What is most important to my happiness and sense of fulfillment?</li><li>When are the times when I was really focussed on something?</li><li>When do I get distracted or unproductive?</li><li>How long can I keep myself focussed?</li></ul><p>For instance, I find that I can focus well when I feel excited about something, such as when I am working on an idea or vision that I care about, or solving a non-trivial problem. I work better when I have someone in mind whom I want to impress, or if I can feel my progress and growth. On the other hand, I tend to lose momentum once I lose my enthusiasm towards the vision I started off with. I often get distracted when I am trying to finish multiple tasks at once, and during lockdown, I noticed that I am spending too much time on my social media news feed.</p><p>Once you have identified what makes you excited and productive, and what is preventing you, you can start adapting your schedule and daily routine to your advantage. For instance, when I start a new project or set a goal for myself, I tell my close friends about it to make myself committed and motivated. Writing on Medium is also a great way of keeping myself motivated to learn new things and reflecting upon the things I have learnt.</p><h4><strong>Step 2: Identify Your Purpose and Priorities</strong></h4><p>When you want to use your time wisely, it is important to identify what you mean by a “meaningful use of your time”. I will be honest here and admit that I am far from perfect. There are many hours in my day in which I don’t produce any apparent progress. Having said that, my goal is not about optimising the use of every single minute of my day. What matters is that you feel satisfied with how you spent your time while being aware of your purpose and your priorities.</p><p>A big mistake I used to make is to reduce the hours of my sleep. If you are someone as busy as Elon Musk, you might have justification for that. You might have spent every single minute of your day purposefully and meaningfully to the extent that you might not have any other alternative. However, most people cannot claim to have spent all their waking hours for things that are truly valuable to them. At least for me, pulling an all-nighter has usually been a result of my bad planning and procrastination, rather than because I had 10 other grand missions to save the world. By pulling an all-nighter, you not only sacrifice your health and the quality of your work, but that damage carries on to the next few days when you could have been more productive, creating a vicious cycle. So I would say, reduce your hours of sleep only if you can do so healthily and sustainably. Otherwise, you can always make an extra hour by cutting out something that is low on your priority list.</p><p>So what should you cut out?</p><p>The answer will depend on what you want to achieve. An important thing is to be aware of your purpose. Let’s say you are scrolling through Instagram, Facebook or Twitter. If you don’t have a purpose, you are just consuming information passively. If you let the stimulation take control over you, you might end up spending hours on the platform having gained very little. On the other hand, if you are actively seeking information or trying to learn from their UX or their revenue model, you navigate such platforms with a totally different intent and efficiency. You will probably learn far more than a passive user.</p><p>We also have to be careful when you start off having a purpose but then you forget about it and allow yourself to be a passenger rather than a driver. Reading a book is a good example. You don’t read a book just to see the number of pages you’ve flicked through increase. You have a set purpose, which is to gain knowledge from the book. If you are losing focus and reading the same lines over and over again, or if the book is not yielding useful information, close the book and open another book, or take a short break and come back with renewed focus.</p><p>There is one thing that you can’t really plan in advance — socialising. These things happen organically and spontaneously, so even if you have a beautifully planned out schedule, you may have to abandon it if you value the time you spend socialising. Again, it depends on what kind of value and meaning you assign to such interaction. Personally, I look for enjoyment, relaxation and refreshment, so I prefer to be flexible once I decide to join a social gathering. I try to balance that out by choosing how frequently I join such gatherings.</p><h4>Step 3: Visualise Your Goals and Accomplishments</h4><p>Goals that are not written down can be easily dismissed or forgotten. I have a bulletin board in front of my desk where I write what I want to do in big fonts with a thick marker. If you have multiple tasks, this is a good way to off-load your brain so that it can focus on one specific task until it has been accomplished.</p><p>Seeing yourself making progress is really motivating and can amplify your productivity. When I was studying for my entrance exam, I had a list of exercise books I have to finish with a progress bar next to it. When I complete a chapter, I colour the progress bar in so that I can see my progress even before I finish an entire book.</p><p>While it isn’t good to be overly self-confident, looking back upon your past achievements and things you are proud of is also a good way to reignite your motivation, especially when you are feeling burnt-out or have lost your self-esteem. We are all human (hello, GPT-3!) and we all make mistakes and have failures. Upon these tough times, it is good to have something that can remind you of your value and how you have overcome many other challenges before.</p><h4>Step 4: Find a Companion. Have Motivated People Around You.</h4><p>It would be ideal if you could motivate yourself persistently to achieve whatever goals you set. I do enjoy programming, online courses and listening to podcasts, so for those I don’t need external assistance. However, for the things which aren’t necessarily enjoyable but still important for life, such as preparation for exams, it is good to have a companion.</p><p>During my undergraduate studies, I was fortunate to have a study partner who really helped me keep focussed and motivated. She was much better than me at planning out study schedules and making this a daily routine. She would often ask me questions, which forced me to revise the material so that I can give her a proper answer.</p><p>With COVID-19, physical study sessions have become rather difficult. Although it is slightly inconvenient, remote companionship also does the trick. I have friends who keep their Zoom or Skype on while they study in silence with their friends, or even with their family.</p><p>Companionship can also work outside of study. During the lockdown, I joined a remotely organised six-week event of building a web service from scratch. There were more than a hundred participants who joined, and we formed a team of three to build our product. Although we only had two hours of Zoom classes each week, it was very motivating to have teammates, and to know that there are a hundred other students who are working on a product of their own. There were some teams where no one had prior experiences of building a web service, but after six weeks, they came out with a working product. This shows how such initiatives can make you push your boundaries.</p><h4>Step 5: Warm Up with Something Simple and Easy</h4><p>It is very difficult to force yourself to do something when you really aren’t in the mood. Getting up from bed and going for a run, for instance, is one such example. Especially during winter, the thought of going outside in the cold for a run is not appealing when you are warm in bed. That is why it is helpful to break things down into smaller steps which gradually prepares you for the ultimate goal.</p><p>The trick is to start with something very easy that you can do passively. I found that a good way to start my day is to listen to an episode of a motivational podcast. After 10 minutes, I feel slightly more awake. On a sunny summery day, I go out for a run immediately, but in the winter, I spend an extra five minutes on a warm-up exercise in my room while listening to music. When I finish that, I feel awake enough to brace the cold.</p><p>The same strategy can be applied when you feel that you want to do something that is bad for your productivity — like binge-watching some series on YouTube. You know that you should go back to work, but the temptation is strong and you feel addicted. It would be very difficult to just start working, because you aren’t in the proper mindset. Here, you also want to start with something easy and passive. Listen to an episode of a motivational podcast / audiobook, calm yourself down with a cup of tea, clear your desk and get back to work.</p><h4>Step 6: Set Up a Productive Routine</h4><p>A painless and easy way to bringing yourself to a proper mindset is to make that process a habit. The key is to make that habit something enjoyable. Audiobooks have been one of my favourite pass time since when I was a kid, and recently I learnt about some really good podcasts. Since listening to podcasts and running go together very well, this motivated me to properly adopt running as my habit, which has become my new hobby. Many of the podcasts I listened to were either educational or motivational, which helped me start the day off with increased energy.</p><h4>Step 7: Create Associations and Separations</h4><p>Warm ups, routines and habits are all about training the brain to move into <em>productive mode</em> when you perform certain actions in sequence. This works because the brain learns what to expect, and tunes into the right state of mind you want to be in. More broadly, this is about creating associations.</p><p>It could be useful to create additional cues for your brain to indicate that you are switching from leisure mode to productive mode. Some people like to relax in their rooms and study in the library. Separating out where you sleep and where you work is helpful to make you sleep better without anxiety, and be more focussed when you are working.</p><p>What I found helpful is to have two laptops, one for work and another just for leisure (usually I won’t be able to afford two laptops, but the department provided me with a laptop). In this way my brain knows to switch gears when I switch laptops. It also helps me monitor the time I spend on my leisure laptop, so that I feel guilty if I spend too much time on it.</p><h4>Step 8: Make it Effortless to be Productive and Difficult to be Distracted</h4><p>Designing your work space is important for increasing your productivity. Putting your daily and weekly goals on the wall, clearing your desk, maybe even changing your background image of your laptop and smartphone to a motivational quote that matters to you are some of the effective ways to remind yourself to be productive.</p><p>Another way to subconsciously signal to your brain to be productive is to make it effortless to be productive and costly to be counterproductive. Setting up app blockers are one such effective way. If you want to make an exception and have a sneak-peak at your Facebook, make sure you don’t let yourself get away with it without at least a bit of sacrifice. Even something as simple as doing 10 pushups every time you are tempted to open your social media might be enough to discourage you from doing that too often.</p><p>Distraction is the biggest enemy of all. A notification on your phone can easily break your concentration for 30 minutes straight. If you want to keep focussed and get things done, it won’t hurt to set your phone on airplane mode for an hour.</p><h4>Step 9: Say it Out Loud, Monitor Your Progress and Turn Your Words into Action</h4><p>The final step is the most important — do the thing!</p><p>Committing to your plans and goals is a challenge. It is so easy to give up mid-way and allow yourself to get away with it. That is why writing down your goals is useful, and even better, to tell someone else about your goals. This will make you more responsible to follow your goals.</p><p>Decide on a measure or a weekly / monthly target to keep track of your progress and monitor your performance. These targets can start small. When I started running, I decided to run only on sunny days and run a minimum of 1 mile. When I feel like it, I would run 4 miles or even 8 miles. This flexible goal has allowed me to be persistent without quitting. I also told a lot of my friends about this new habit I adopted because I was very excited about it.</p><h3>To Recap</h3><p>Here is the summary of all the steps:</p><ol><li>Know Your Strengths and Weaknesses</li><li>Identify Your Purpose and Priorities</li><li>Visualise Your Goals and Accomplishments</li><li>Find a Companion. Have Motivated People Around You.</li><li>Warm Up with Something Simple and Easy</li><li>Set Up a Productive Routine</li><li>Create Associations and Separations</li><li>Make it Effortless to be Productive and Difficult to be Distracted</li><li>Say it Out Loud, Monitor Your Progress and Turn Your Words into Action</li></ol><p>Make your goals something you feel excited about, so that you are compelled to tell your friends and family. This will then make you commit to those goals. I don’t know about your brain, but my brain is lazy by default and easily distracted, so it is very important to make it clear why something needs to be done and what I get out of it. Designing a routine, a habit and an environment also helps our brain to operate with increased productivity and incentive.</p><p>Thank you for reading this through! As I said at the start, this is no where near a comprehensive list of what you can do, and I am eager to learn other tricks and strategies that can help my personal development. If you have any tips and strategies that you have found useful, I would be delighted to hear!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c6044673092" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-to-inspire/9-steps-that-helped-me-assess-myself-and-stay-productive-2c6044673092">9 Steps to Reprogram Yourself and Stay Productive</a> was originally published in <a href="https://medium.com/tech-to-inspire">Tech to Inspire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Counting in Binary Numbers can Cause Auditory Illusions]]></title>
            <link>https://medium.com/tech-to-inspire/how-counting-in-binary-numbers-can-cause-auditory-illusions-4f01646e09bd?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f01646e09bd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[sound]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Sat, 08 Aug 2020 14:13:01 GMT</pubDate>
            <atom:updated>2020-08-09T15:27:04.902Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s generate Shepard Scales from a PIC microcontroller in Assembly Language</h4><p>In <a href="https://medium.com/tech-to-inspire/how-assembly-language-became-my-first-programming-language-ea8db4f4c620">my previous article</a>, I talked about the simplicity of Assembly Language and about the world’s smallest hobbyist computer — a PIC microcontroller. In this article, I want to pick up where we left off and introduce you to a fascinating illusion called Shepard Tones — an illusion of ever-ascending/descending scales — and how you can create that complex illusion with a simple PIC that can only emit ON-OFF signals.</p><h3>The fundamentals of Shepard Tones</h3><p>There is a family of auditory illusions called Shepard Tone. Hearing is believing. Here is a great example on YouTube:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMShclPy4Kvc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMShclPy4Kvc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMShclPy4Kvc%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/5db9948df0260100d6f0ed758622f510/href">https://medium.com/media/5db9948df0260100d6f0ed758622f510/href</a></iframe><p>In the first half of the video, the pitch seems to go down and down; in the second half, it goes up and up, with no apparent end. In fact, the sound is on repeat so it can go on forever! How can this be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlvKf0_j9vxWjPaCSdc4Uw.png" /><figcaption>Image from the <a href="https://asa.scitation.org/doi/10.1121/1.1919362">original paper by Roger Shepard</a>¹</figcaption></figure><p>The trick, as described in <a href="https://asa.scitation.org/doi/10.1121/1.1919362">Roger Shepard’s paper</a>, is to play multiple notes at once at octave intervals. Because of the periodicity in how we perceive pitch, if we hear a note that superposes 10 notes of the key C, D, or E at octave intervals, we will have difficulty in separating them out. Furthermore, these notes are passed through a bell-shaped envelope filter that boosts the middle frequency and suppresses the high and low frequencies. After a full cycle, the top-most note fades away to be replaced by the bottom-most note, resulting in a never-ending loop of ascending / descending notes.</p><p>Okay, so the principle is fairly straightforward. How then, shall we create this superposition of sound waves at octave intervals? This is where our PIC microcontroller plays its trick.</p><p>We said that a PIC has byte-long Input/Output ports with 8 pins each. PIC16F628A has two ports, Port A and Port B. Let’s now make each pin on Port B output a wave at octave intervals. We emit waves by switching the output pins ON and OFF. The faster you switch, the higher the wave frequency. Let’s say that pin 0 emits a wave with the highest frequency, and pin 7 emits a wave with the lowest frequency. The result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U09bbFssFYhkdSQc5cYiWw.png" /><figcaption>Diagram showing how each pin on port B should be switched to produce wave signals at octave intervals. RB0-RB7 are bits on Register B, which are exported to Port B that maps onto the output pins.</figcaption></figure><p>RB0-RB7 corresponds to the outputs of pins 0–7. Looking at each individual pin from left to right, you can see that they are switched ON and OFF at different frequencies with a scaling factor of two. Now, let’s look at each port output value as a whole. Do you see something interesting?</p><p>Yes, it’s binary counting! (The title gave it away, didn’t it?) The left most output amounts to 00000000, then 00000001, 00000010, 00000011, … and so on. How simple and yet beautiful! By just counting up binary numbers at 2⁴ * 440Hz, a PIC is able to produce the basic wave components for a Shepard Tone of key A. By counting faster or slower, the PIC can alter the pitch. While recordings of a Shepard Tone may require MBs of memory, the Assembly code captures the fundamentals of Shepard Tones in a simple loop!</p><p>I will now give a brief overview of the code. The full assembly code is available at <a href="https://github.com/shuishida/shepard_tone_pic">this GitHub repository</a>. In case you aren’t interested in the implementation, scroll to the final section where you can hear for yourself some Shepard Tone samples generated by the circuit!</p><h3>Code for the Shepard Tone Generator</h3><p>We start by implementing the core functionality of producing a Shepard Tone. The relevant code is in <a href="https://github.com/shuishida/shepard_tone_pic/blob/master/tone_generator.asm">tone_generator.asm</a>. Varying the base frequency for different keys, i.e. how fast it counts, is a little involved. For now, we can abstract that complexity away by calling a subroutine DLYSET which will provide us with an appropriate amount of delay. CNT0 is the counter that counts down from 0xFF, 0xFE, … down to 0x00 (this weird notation is called HEX, and it represents numbers with a base 16 where every digit is from 0–9 to A-F), using a DECFSZ command. You could easily substitute this with an INCFSZ command and count up if you’d prefer. CNT1 counts down the number of times this loop has to be repeated in order to make the note last for a quarter of a second. A PIC command consumes 1 μS or 2 μS, depending on whether it involves a jump. The amount of μS required for each command is shown in the comment. TONE_TM is there just to make it consume an extra 2 μS to make every loop consume the same amount of time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d94bbc6de9cebe7f6019f60234dedd/href">https://medium.com/media/32d94bbc6de9cebe7f6019f60234dedd/href</a></iframe><p>So that was just 14 lines of code for the heart of the Shepard Tone! How beautiful!</p><p>Well, not so easy. We now have to figure out the exact amount of delay in DLYSET and the exact amount of loops CNT1 to generate a note with the key of our desire. This is handled in sections DLYSET and NOTESET.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/907d0a9c0e430d137f736487311672a7/href">https://medium.com/media/907d0a9c0e430d137f736487311672a7/href</a></iframe><p>Here are two variables, TONE and NOTE. The reason for this will become clearer when you see the <a href="https://github.com/shuishida/shepard_tone_pic/blob/master/tone_generator.asm">entire code</a>. Basically, because Shepard Scales repeat the same sequence of notes but with a different offset, it makes sense to just define the sequence of notes defined relative to the offset TONE, and evaluate the absolute NOTE on the fly. The absolute NOTE should wrap around if an octave is reached, so it always has a value between 0x00 and 0x0B (=11).</p><p>For each NOTE, we want to retrieve the relevant wait subroutine and the loop count CNT1. This is happening whenSETDATA is called. Here, I have used a trick called lookup tables. Essentially, this is an array of commands in order in memory so that they could be jumped to conditionally based on the value stored in the working memory. It is typical to have a GOTO or a RETLW (retrieve a hard-coded value, store it in working memory, and return) statement to make the PIC have varying behaviour based on the value of the working memory.</p><p>The rest of the code mainly consists of two parts. First is about creating the right amount of delay necessary for a sound wave to be produced. For instance, if you want a note with a key A, that has a frequency of 2⁴ * 440Hz, you will have to turn the least significant bit ON and OFF 2 * 2⁴ * 440 times in a second, which gives you 71 μS for each loop. There is an overhead of 18 μS in the TONE_LP loop, so the delay in TONEDLY_A should amount to 53 μS.</p><p>The second part of the code is to do with switching sound tracks. There are five songs I’ve hard-coded in the built-in memory, and with external input, you can switch between them. The external input is read in by Port A.</p><h3>Shepard Tone Generator Circuit + Extra Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*ocSScvFrtYjF2ZdsBX6TkA.png" /><figcaption>Circuit diagram for the Shepard Tone Generator</figcaption></figure><p>A fun but also an labour intensive part is building the circuit. In addition to the core PIC that generates the Shepard Tone, I added two additional PICs, one for track selection, and the other for displaying the tracks on an LED display. The corresponding assembly code are <a href="https://github.com/shuishida/shepard_tone_pic/blob/master/track_selector.asm">track_selector.asm</a> and <a href="https://github.com/shuishida/shepard_tone_pic/blob/master/track_display.asm">track_display.asm</a> respectively. Then these PICs are wired together as shown in this diagram.</p><p>The three PICs in the diagram from top to bottom correspond to the track selector, tone generator, and track display PIC respectively. The track selector PIC is connected to four buttons: PLAY, STOP, PREV, NEXT. You can select the sound track using PREV and NEXT, and once you decide on a track, you can press PLAY. Then the selected track will be outputted from Port B of the PIC and is transmitted to the other two PICs, which receive that signal at their Port A. The tone generator emits 8 wave signals from its 8 pins, which are then combined to make a single output signal.</p><p>There is an additional post-processing step. Do you remember the bell-shaped envelope at the beginning of this article? You would want to apply a filter to the generated wave signal so that the middle-range is boosted while the higher and lower frequencies are cut off. This can be achieved either by a passive mid-range filter circuit made of resistors and capacitors, or with an active filter that uses an op-amp. I went for the former approach.</p><p>And finally, after a couple of months’ work, I had a Shepard Tone generator, ready to be exhibited at our school festival!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4DaRgiZkOromjzDAAt8FA.jpeg" /><figcaption>Completed Shepard Tone Generator</figcaption></figure><h3>Generated samples</h3><p>In case you don’t want to go through the daunting work of shopping for components, soldering, programming, and compiling, below are some example recordings, all taken from the Shepard Tone Generator that I have created. Apart from cropping and concatenating, no post-processing has been performed on the recorded signals.</p><p>Here is the first example. This is already two cycles, but you can put this on repeat to fully appreciate how never-ending this scale can be!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F872380753%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Falacreme%2Fshepard-tone-example-1&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b8cd37f34757d9c5a785dc57f7ea0cb/href">https://medium.com/media/7b8cd37f34757d9c5a785dc57f7ea0cb/href</a></iframe><p>If you listen carefully, you might pick up the base note which drops at a certain point. Now, let’s compare this against a non-Shepard Tone scale with the same keys.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F872382736%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Falacreme%2Fnon-shepard-tone-example-1&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/c76fe2a28e365fa94bdb35ddfc08946a/href">https://medium.com/media/c76fe2a28e365fa94bdb35ddfc08946a/href</a></iframe><p>Now the difference is evident! The first scale might be able to catch the listener unawares whereas the second one is plainly disillusioning!</p><p>Here is another example that I like, partly because I got the idea from those boring scales you have to practice when you are learning to play the piano:P</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F872383684%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Falacreme%2Fshepard-tone-example-2&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/4448a8ff55a7fdf82f98e3e793790d7b/href">https://medium.com/media/4448a8ff55a7fdf82f98e3e793790d7b/href</a></iframe><p>Finally, I tried to be more experimental by making some very long pieces of music just out of Shepard Tones. Most of it was rather a challenge, since any piece has to fit within a range of an octave to cause a convincing illusion (you can work around with this by making the cut-off frequencies of the mid-range filter depend on which part of the song it is playing, but that can get pretty advanced). I will share with you an attempt at doing this with Greensleeves, which I think went fairly well despite its range of pitch.</p><p><a href="https://soundcloud.com/alacreme/greensleeves-in-shepard-tone">Greensleeves In Shepard Tone</a></p><p>This whole recording is 10 min long, and it consumes 98MB as a WAV file. Remember that a PIC has only 4KB of memory? Despite that, it was able to withhold this entire song, along with four other songs in its built-in memory. I think it is astounding and beautiful that a simple machine code of a few hundred bytes can express this rich information in the most compressed and fundamental form!</p><p>Thank you for reading till the end!</p><p>[1] Roger Shepard (1964) <a href="https://asa.scitation.org/doi/10.1121/1.1919362">“Circularity in Judgements of Relative Pitch”</a>, Journal of the Acoustical Society of America 36 (12): 2346–2353.</p><p><strong>Related articles:</strong></p><p><a href="https://medium.com/tech-to-inspire/how-assembly-language-became-my-first-programming-language-ea8db4f4c620">How Assembly Language became my first programming language</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f01646e09bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-to-inspire/how-counting-in-binary-numbers-can-cause-auditory-illusions-4f01646e09bd">How Counting in Binary Numbers can Cause Auditory Illusions</a> was originally published in <a href="https://medium.com/tech-to-inspire">Tech to Inspire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Assembly Language became my first programming language]]></title>
            <link>https://medium.com/tech-to-inspire/how-assembly-language-became-my-first-programming-language-ea8db4f4c620?source=rss-53b23b891950------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea8db4f4c620</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[assembly-language]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shu Ishida]]></dc:creator>
            <pubDate>Sat, 01 Aug 2020 17:59:04 GMT</pubDate>
            <atom:updated>2020-08-08T21:45:44.551Z</atom:updated>
            <content:encoded><![CDATA[<h4>The beauty of PIC microcontrollers</h4><p>“Hello World!” — that is where we all start programming. At least, if you have a console. My entry point into this fascinating world was slightly different. In this <em>hello world article</em>, I want to share my first programming experience, which was literally in 0s and 1s.</p><p>I joined a science club in secondary school. There, I was immersed in synthesising ferrofluid — a liquid that is attracted to magnets. I managed to break a few beakers in the process. There was a student in the upper year who knew a lot about micro-controllers, and for our annual school festival, he decorated the entrance to the science club exhibition with LED lights which were programmed to flicker on and off in various patterns. What was more exciting is that, he just programmed a tiny chip called microcontrollers to make the whole thing work. That was what got me excited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*O4xAF36ZE_Ik-9r55LFqBg.png" /><figcaption>A PIC16F628A microcontroller on a breadboard.</figcaption></figure><p>A microcontroller is a tiny rectangular chip with lots of tiny legs (pins). Despite this slightly disturbing description, they are one of the cutest intelligent things you can get for $2. It is a minuscule computer in the simplest form — no monitors, no keyboard inputs, and with a bare minimum amount of memory. It can store a set of instructions in its program memory, which is executed as soon as you connect the chip to a power supply. In addition, it has a small amount of data storage and temporary memory for calculation.</p><p>So how small is small? It has been around eight years since I played with these beauties so I had to look at the <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/40044G.pdf">data sheet</a>. My favourite microcontroller is PIC16F628A, since it has quite a lot of functions for a very cheap price. The answer is quite mind-blowing! It has a program memory of 2048 instructions (~4KB), 128 Bytes of data memory (EEPROM), and 224 Bytes of temporary memory (RAM). The vocabulary of the programming language for this PIC consists of only 35 words!</p><p>To put this into context, a modern laptop in 2020 might have 8GB of RAM and 512GB of flash memory, so roughly speaking, we are talking about 40,000,000 times difference in RAM and 100,000 times difference in flash memory.</p><p>So why would anyone want to play with PIC? For me, the pure attraction was that (1) it is so simple and minimalist, and you can understand its functionality back to front, (2) unlike ready-made computers, you can directly integrate microcontrollers into electric circuits and control devices such as LEDs, speakers, transistors and motors. This is possible because of those many pins sticking out from PICs — each pin can either measure a voltage input or emit a voltage output. These signals can then be amplified by transistors if higher voltage signals are required, e.g. by motors. Note also that PICs are very flexible and can be integrated into more complex circuits. You can add more components to it, such as external memory, an LCD display, or a Wi-Fi module to build a custom IoT device.</p><p>If you are thinking of starting your first ever IoT project, I would probably recommend something like Arduino or a Raspberry Pi. Arduino is a microcontroller kit with many useful external components, such as USB and Ethernet ports, with a specialised software for developing more complex IoT devices. Raspberry Pi is a proper computer with an operating system, on which you can run ordinary software, despite its cheap price of just $40! On the other hand, if you are interested in the bare-bones of computers, learn how programs are translated into 0s and 1s, and see the working results in real life, microcontrollers (e.g. PIC) is the way to go!</p><p>As a 14 year old, the cheapness of a single microcontroller was what excited me the most. I probably bought a hundred of these tiny beauties, which would have been impossible had it been more expensive.</p><p>The set of instructions are really straightforward. You read voltage inputs from a block of 8 pins by reading a byte-long binary value from a port. You output voltage from a block by setting a byte-long value to a port. You can perform calculations and store intermediate results in memory. You can only make changes to a single memory address at a time. If you want to perform operations that involve more than a single address, you have to use a working register (a byte-long temporary memory storage). Available operations are addition, subtraction, AND, IOR (Inclusive OR), XOR (Exclusive OR), copy and clear. Each command requires 1 or 2 clock cycles to be executed. There is an instruction called No-Op, which consumes 1 clock cycle without doing anything. And that is 80% of the language explained in a single paragraph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSBdIa6S_e9CjfbUa6t6nQ.png" /><figcaption>Screenshot of MPLAB IDE (a developing tool for PIC in Assembly Language) from 2011… looks so old!</figcaption></figure><p>The funkiest commands in this minimalist language are GOTO, CALL and RETURN. Yes, GOTO! Pretty much all programmers will be shocked to see any GOTO statements appearing in code nowadays, which is not supported in most modern programming languages anyway. In modern languages, we have the concept of functions and loops instead. WHILE and FOR loops help programs to be broken into self-contained meaningful parts without having the unpredictability of a GOTO statement, which can potentially jump to any part of the code and cause unexpected and difficult-to-debug errors. However, replacing GOTOs with WHILE and FOR also required an additional workaround command called BREAK.</p><p>So what about IF statements? All programs require some conditionals, especially if there is an external input to be considered, which is often the case with electronic devices with switches and sensors. In Assembly, there isn’t an explicit IF statement. Instead, there are things called flags, which are set either ON or OFF every time you make a calculation. The important ones are the Zero flag and the Carry flag, which tells you additional information about the operation you have just executed. The Zero flag is set when the result is 0, and a Carry flag is set when the calculation result exceeds the numerical range that can be represented in a byte. There are two handy instructions — INCFSZ and DECFSZ, which stands for Increment [Decrement] F, Skip if Zero. When the increment / decrement operation results in 0, the next instruction is replaced with a No-Op. It is common practice to put a GOTO statement in this line if you want a branch or a loop in your program.</p><pre>LOOP<br>        ; In the loop<br>        ...<br>        DECFSZ    REG1, F<br>        GOTO      loop<br>BLOCK<br>        ; Out of the loop<br>        ...</pre><p>All the commands, including the labels on the left and memory addresses with human readable names are translated into either memory addresses in 0s and 1s. The amazing thing is that each command has a unique zero-one string associated with it to make the whole program unambiguous, even when there are only 0s and 1s. These 0s and 1s are saved as a .HEX file. Thankfully, we can hand over that nasty task of translation to compilers, such as <a href="https://www.microchip.com/mplab/mplab-x-ide">MPLAB X IDE</a> (official software produced by Microchip, which manufactures PIC). These are powerful tools that also has debugging features such as stepping through the code and inspect the values of each memory address, register and port.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMFH3ALJOcDUNhzQ3VyEXA.png" /><figcaption>My PIC programming board. A PIC16F628A is on stage.</figcaption></figure><p>Once everything is translated into 0s and 1s, it is time to write into our PIC. You mount the PIC onto a programming board, connect it to a laptop, start up a software specific to your programming board, read your .HEX file into the software and start writing into the PIC flash memory. The programming board is probably the most expensive part. You can build such programming boards from scratch, but I was lazy so I bought a ready-made board. This specific one in the picture cost about $50.</p><p>And now for the most exciting part. The program is written into the PIC. You detach the PIC from the programming board. You place it in your circuitry (never solder your PIC directly onto your circuit board because the heat can break the chip. Use a socket instead). And you switch the power supply on. I must have short-circuited about five unfortunate PICs over the course of my experiments, and many more have lost legs from being plugged in and out of the socket repeatedly, so make sure you have a resister in place, and choose your sockets wisely. If all goes well, you will have an array of LEDs blinking at you with a warm “Hello World!”.</p><p>In my next article, I write about a real project I’ve worked on using PIC, with the accompanying assembly code and circuit diagram. It is about an auditory illusion called Shepard Tones. Hope you find it interesting!</p><p><a href="https://medium.com/tech-to-inspire/how-counting-in-binary-numbers-can-cause-auditory-illusions-4f01646e09bd">How Counting in Binary Numbers can Cause Auditory Illusions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea8db4f4c620" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-to-inspire/how-assembly-language-became-my-first-programming-language-ea8db4f4c620">How Assembly Language became my first programming language</a> was originally published in <a href="https://medium.com/tech-to-inspire">Tech to Inspire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>