<?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 Fernando Jaruche Nunes on Medium]]></title>
        <description><![CDATA[Stories by Fernando Jaruche Nunes on Medium]]></description>
        <link>https://medium.com/@fernandojaruchenunes?source=rss-7ec560909e77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PyWdOQLBs1voBbyy.</url>
            <title>Stories by Fernando Jaruche Nunes on Medium</title>
            <link>https://medium.com/@fernandojaruchenunes?source=rss-7ec560909e77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:42:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fernandojaruchenunes/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[Udacity Robotics ND Project 8–Deep RL Arm Manipulation]]></title>
            <link>https://medium.com/@fernandojaruchenunes/udacity-robotics-nd-project-8-deep-rl-arm-manipulation-ce480cbb1194?source=rss-7ec560909e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce480cbb1194</guid>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Fernando Jaruche Nunes]]></dc:creator>
            <pubDate>Thu, 06 Dec 2018 18:21:31 GMT</pubDate>
            <atom:updated>2018-12-11T18:13:19.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZA-nDWDvxr92W1P7Irt1Lw.png" /><figcaption>Robotic Arm simulated in ROS Gazebo</figcaption></figure><h3>Introduction</h3><p>In this article I’ll go over my submission for the Udacity Robotics ND Project 8— Deep RL Arm Manipulation. The goal of this project is to create a DQN agent and define reward functions to teach a robotic arm to carry out two primary objectives in a simulated environment:</p><ol><li>Have any part of the robot arm touch the object of interest, with at least a 90% accuracy.</li><li>Have only the gripper base of the robot arm touch the object, with at least a 80% accuracy.</li></ol><p>I&#39;ll go over the implementation details of the agent below.</p><h3>DQN Agent Implementation</h3><p>The ArmPlugin plugin is responsible for creating the DQN agent and training it to learn to touch the prop. Below I&#39;ll go over the main changes to the originalArmPlugin methods for this project.</p><h4>ArmPlugin::Load()</h4><p>In this function I create the camera and collision nodes and subscribed them to the respective topics. Also ArmPlugin::OnUpdate() will be called for every world update.</p><pre>// Create our node for camera communication<br>cameraNode-&gt;Init();<br>cameraSub = cameraNode-&gt;Subscribe(&quot;/gazebo/&quot; WORLD_NAME &quot;/camera/link/camera/image&quot;, &amp;ArmPlugin::onCameraMsg, this);                </pre><pre>// Create our node for collision detection<br>collisionNode-&gt;Init();<br>collisionSub = collisionNode-&gt;Subscribe(&quot;/gazebo/&quot; WORLD_NAME &quot;/&quot; PROP_NAME &quot;/tube_link/my_contact&quot;, &amp;ArmPlugin::onCollisionMsg, this);</pre><pre>// Listen to the update event. This event is broadcast every simulation iteration.<br>this-&gt;updateConnection = event::Events::ConnectWorldUpdateBegin(boost::bind(&amp;ArmPlugin::OnUpdate, this, _1));</pre><h4>ArmPlugin::createAgent()</h4><p>I&#39;ve then created the DQN agent by providing the hyperparameters to the constructor. The number of possible actions is defined as 2x the number of joints (DOF) as they can rotate both clockwise and counter-clockwise.</p><pre>// Create DQN Agent<br>agent = dqnAgent::Create(INPUT_WIDTH, INPUT_HEIGHT, INPUT_CHANNELS, DOF*2, OPTIMIZER, LEARNING_RATE, REPLAY_MEMORY, BATCH_SIZE, GAMMA, EPS_START, EPS_END, EPS_DECAY, USE_LSTM, LSTM_SIZE, ALLOW_RANDOM, DEBUG_DQN);</pre><h4>ArmPlugin::onCollisionMsg()</h4><p>Once a collision is detected I&#39;ve calculated the episodic reward. The reward is positive in cases where the gripper collides with the prop tube and negative otherwise:</p><pre>// Check if there is collision between the gripper and object, then issue learning reward<br>if((strcmp(contacts-&gt;contact(i).collision1().c_str(), COLLISION_ITEM) == 0) &amp;&amp;<br>(strcmp(contacts-&gt;contact(i).collision2().c_str(), COLLISION_POINT) == 0))<br>{<br>    rewardHistory = REWARD_WIN;<br>    newReward  = true;<br>    endEpisode = true;</pre><pre>    // multiple collisions in the for loop above could mess with win count<br>    return;<br>}<br>else {<br>    // Give penalty for non correct collisions<br>    rewardHistory = REWARD_LOSS;<br>    newReward  = true;<br>    endEpisode = true;<br>}</pre><h4>ArmPlugin::updateAgent()</h4><p>This method updates the arm joints based on the action chosen by the DQN Agent. Depending of the joint control method the position of the joints can be incremented by a small position or a velocity delta. I&#39;ll discuss the difference between the two in the next section.</p><pre>#if VELOCITY_CONTROL<br>// Increase or decrease the joint velocity based on whether the action is even or odd<br>// Set joint velocity based on whether action is even or odd.<br>float velocity = vel[action/2] + actionVelDelta * ((action % 2 == 0) ? 1.0f : -1.0f);<br>(...)<br>#else<br>// Increase or decrease the joint position based on whether the action is even or odd<br>const int jointIdx = action / 2;<br>// Set joint position based on whether action is even or odd.<br>float joint = ref[jointIdx] + actionJointDelta * ((action % 2 == 0) ? 1.0f : -1.0f);<br>#endif</pre><h4>ArmPlugin::OnUpdate()</h4><p>This method calculates the interim reward used to train the DQN Agent. I&#39;ve used a smoothed moving average of the delta of the distance to the object and a time penalty.</p><pre>const float distDelta = lastGoalDistance — distGoal;<br>const float movingAvg = 0.9f;<br>const float timePenalty = 0.50f;</pre><pre>// compute the smoothed moving average of the delta of the distance to the goal<br>avgGoalDelta = (avgGoalDelta * movingAvg) + (distDelta * (1.0f — movingAvg));<br>rewardHistory = avgGoalDelta * REWARD_MULTIPLIER — timePenalty;<br>newReward = true;</pre><h3>Decision on Joint Control Methods</h3><p>There are two joint control mechanisms available to control the arm joints: velocity or position based. I&#39;ll quickly discuss the differences between the two approaches as how each influenced in the DQN accuracy:</p><h4>Velocity Based</h4><p>The velocity based control takes into account the Arm physics where changes in velocity determine the robot position. This method produces movements that are way more realistic in contrast to controlling the joints position directly.</p><h4>Position Based</h4><p>The position based control is simpler in contrast as the Arm position is determined directly. While simpler to control this method produces unrealistic motion where position changes instantly producing accelerations that cannot be matched by a real robotic arm.</p><p>For the purpose of this project <strong>I picked the position based control method</strong> as it is simpler and led to more accurate results in simulation.</p><h3>Reward Functions</h3><p>I’ve created the following reward functions to address the objectives #1 and #2 respectively:</p><h4>Reward Function #1 — Have any part of the robot arm touch the object of interest</h4><p>For the first objective I&#39;ve created a reward function that rewards any collision between the arm and the tube, and penalizes when robot collides with itself or the ground.</p><p>I&#39;ve also introduced an interim reward proportional to the distance to the objective looking to provide the agent a &quot;trail of breadcrumbs&quot; that creates a closer association between action and reward.</p><p>Finally, I&#39;ve added a time penalty that guarantees the agent will reach the objective as quickly as possible. This factor punishes behaviors, such as wasting time by getting close to the tube and collecting as much interim rewards before touching it.</p><p>Here a summary of the reward function:</p><ol><li>Any part of the Arm collides with the tube: +500</li><li>Any other form of collision (i.e. Arm colliding with itself): -500</li><li>Gripper hits the ground: -500</li><li>Interim reward based on the smoothed moving average of the delta of the distance to the object and a time penalty</li></ol><h4>Reward Function #2 — Have only the gripper base of the robot arm touch the object</h4><p>The Reward Function #2 is very similar to the one above and it has a slight modification to the collision reward. This function will only reward collisions between the gripper and the tube:</p><ol><li><strong>Gripper (only) collides with the tube: +500</strong></li><li><strong>Any other form of collision (i.e. Arm colliding with itself or link2 collides with the tube): -500</strong></li><li>Gripper hits the ground: -500</li><li>Interim reward based on the smoothed moving average of the delta of the distance to the object and a time penalty</li></ol><h3>Hyperparameters</h3><p>Below I&#39;ll describe my DQN hyperparameters and the reasoning behind the selection.</p><h4>Image Input size</h4><p>Keeping the state space smallest as possible helped with convergence:</p><pre>#define INPUT_WIDTH 64<br>#define INPUT_HEIGHT 64</pre><h4>Training</h4><p>I chose RMSProp as the optimizer as it is usually a good choice for recurrent neural networks.</p><pre>#define OPTIMIZER “RMSprop”</pre><p>I kept the learning rate unchanged but had I ran into convergence issues I would have tried to lower this value.</p><pre>#define LEARNING_RATE 0.1f</pre><p>Looking to keep batch gradient updates stable I chose to keep a pool of decorrelated replay memory transitions and increased the batch size:</p><pre>#define REPLAY_MEMORY 10000<br>#define BATCH_SIZE 32</pre><h4>Network Architecture</h4><p>I chose to use the LSTM architecture as a mean to keep track of the previous states in the network internal memory.</p><pre>#define USE_LSTM true<br>#define LSTM_SIZE 256</pre><h3>Results</h3><p>I&#39;m pleased with the results. I got over 90% accuracy for both reward functions (see video below) in less than 200 episodes. The time penalty introduced last was crucial to have the Arm to complete the task quickly. Before introducing this factor the robot would get close to the tube and move back forth collecting as much interim reward as possible without ever touching the tube.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fn2o_D_2Yb3w%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dn2o_D_2Yb3w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fn2o_D_2Yb3w%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/522654c5f9fe47598ee28b7410370a0a/href">https://medium.com/media/522654c5f9fe47598ee28b7410370a0a/href</a></iframe><p>The complete code can be found at my repo:</p><p><a href="https://github.com/fjnunes/RoboND-DeepRL-Project.git">fjnunes/RoboND-DeepRL-Project</a></p><h3>Future Work</h3><p>This was an extremely useful project. From all the RL examples I&#39;ve seen so far this was the first that uses Gazebo as simulation environment. Thats really exciting as I can use the concepts from previous lessons to create new worlds in URDF and apply RL on top of them. I.e. I want to try to create a race track and have cars learning to complete a lap in the quickest time.</p><p>Also, if time permits, I would like to try to control the robotic arm in simulation with the velocity based method as it is more realistic and would allow me to test the resulting DQN in a real robot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce480cbb1194" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Udacity Robotics ND Project 5–Robotic Inference]]></title>
            <link>https://medium.com/@fernandojaruchenunes/udacity-robotics-nd-project-5-robotic-inference-e05d37792e50?source=rss-7ec560909e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/e05d37792e50</guid>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Fernando Jaruche Nunes]]></dc:creator>
            <pubDate>Mon, 03 Dec 2018 18:18:35 GMT</pubDate>
            <atom:updated>2018-12-06T18:56:22.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAIo2Sm9QSO8kkbKcruLag.png" /><figcaption>Pill Data Acquisition Platform created for this project</figcaption></figure><h3>Abstract</h3><p>This article discusses the project for the Udacity Robotics ND Project 5–Robotic Inference. The goal of this project is to create an embedded robotics inference system, leveraging Nvidia DIGITS workflow, to create models that can be deployed at the edge for real time robotics applications.</p><h3>Introduction</h3><p>The project was divided in two parts: First we were asked to practice with the Nvidia DIGITS workflow with a supplied dataset to create a network that achieves at least 75% accuracy and an inference time of less than 10 ms.</p><p>The second step was to pick an idea for a robotics inference system and create an inference workflow in Nvidia DIGITS to support that idea. I’ve decided to create a pill classifier based off one of the suggestions in the classroom. Pills are coded with different shapes, size, colors and textures making Convolution Neural Nets (CNNs) a great candidate for building a system that recognizes these distinct visual features. Also, to help with the data collection, I’ve created a simple mechanism similar to the conveyor belt presented in classroom to acquire the sample data.</p><h3>Motivation</h3><p>Who never mixed pill accidentally and later had no idea what they were? Or in too much pain to read thru tiny labels? It would be interesting to have a system that would sort / verify the pills before we take them as a safety mechanism.</p><p>Looking online for something along these lines I found a few Pill Identifier websites (like <a href="https://www.goodrx.com/pill-identifier">this one from GoodRx</a>) that searches for pills using rudimentary user selection like pill imprint, color and shape.</p><p>These websites are clumsy but they have a huge database of pills and did a decent job finding examples of the pills I was searching for.</p><p>I&#39;ve then continued my research of alternatives to keep pills organized and I found this incredibly popular Automatic Pill Dispenser:</p><p><a href="https://www.amazon.com/dp/B00FL620B0/?th=1">LiveFine Automatic Pill Dispenser, 28-Day Electronic Medication Organizer with Alarm Reminders, Flashing Light and Safety Lock - Dispenses Prescriptions Up To 6 Times Per Day - Clear Lid</a></p><p>Once pill are manually sorted inside of this device it can be programed to deliver pills, by moving the carousel to the proper position, multiple times per day. An alarm will sound until the device is tilted by the user releasing the pills.</p><p>I envision a product that combines the capabilities present on both solutions discussed above. This product would be responsible for ingesting and sorting pills and then placing them on to the appropriate carrousel slots to be dispensed based on the rules described by the doctors prescription.</p><p>The first step to accomplish that vision is to design an inference system capable of classifying pills. I&#39;ll go over this implementation in more detail in the sections below.</p><h3>Background / Formulation</h3><p>Embedded systems present challenges as they cannot rely on the cloud and often present with computation, memory, network bandwidth and latency constraints. Privacy is another consideration, sensitive data should be protected an preferably should not leave the device that captured it. All those factors limit the complexity of the inference model resulting in a tradeoff between model accuracy and speed.</p><p>For the reason above I choose the GoogLeNet network as the base of my inference system as it offers a good balance between Accuracy and Inference speed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5LKzIkhcGcL_P3jlkW-tQ.png" /><figcaption>GoogLeNet offers a good balance between Accuracy and Inference speed</figcaption></figure><p>GoogLeNet uses inception modules that combine multiple convolution kernel sizes and batch normalization layers that are more forgiving to hyperparameters choices as gradients flow independently of layer depth speeding up learning. This last feature is greatly appreciated by this student way past his deadline!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnUUqwaxLnWs%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnUUqwaxLnWs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnUUqwaxLnWs%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/58d4bbaf8d4658d5c898e132e242e4cc/href">https://medium.com/media/58d4bbaf8d4658d5c898e132e242e4cc/href</a></iframe><h4>Practicing with the DIGITS Workflow</h4><p>I&#39;ve then moved to training a model with the provided sample data using Nvidia DIGITS workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*FzZZ276MHpc4yoVa.jpg" /><figcaption>Sample data provided with the lesson: P1_data</figcaption></figure><p>I&#39;ve loaded the P1_data into a dataset with the same name splitting 15% of the data for validation and 10% for test.</p><p>I&#39;ve then created the P1_model using the default hyperparameters and selecting GoogLeNet architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wj0zlyAhRzLSIePSWoQKKA.png" /><figcaption>P1_model using the default hyperparameters and GoogLeNet architecture</figcaption></figure><p>With the model created I&#39;ve started the training job:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOL1jIUjty0cBKiHzI9FQQ.png" /><figcaption>P1_model_GoogleNet Job with P1_data dataset</figcaption></figure><p>After completing the training I ran the &quot;evaluate&quot; command and got an accuracy of 75.4% with an average inference time of 5ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NoxRRM5HB42pbJDUbW9hJQ.png" /><figcaption>The resulting model had an accuracy of 75.4% with an average inference time of 5ms</figcaption></figure><p>With the first part completed, and a good understanding of the Nvidia DIGITS workflow, I&#39;ve moved on to tackle my pill idea.</p><h3>Data Acquisition</h3><p>Collecting labeled data is an expensive and tedious process and a successful classifier requires thousands of pill pictures with respective labels. Looking to save myself from this trouble I build a simple data acquisition platform, similar to the conveyor belt presented in the classroom, but for pills:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9YxxyByNGuc%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9YxxyByNGuc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9YxxyByNGuc%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/8e77d9fe12289bfee41fdb775c614e3a/href">https://medium.com/media/8e77d9fe12289bfee41fdb775c614e3a/href</a></iframe><p>For collecting the data I used my iPhone X as a video recorder, a Ceramic Mug to position the iPhone to the desired hight and an <a href="http://a.co/d/1ZFZZRC">Automatic Pill Dispenser</a> with 28 compartments.</p><p>I’ve made a quick modification to the pill dispenser such that it would rotate indefinitely, loaded the tray with pills and recorded them passing by for about 10 minutes. I’ve repeated the same process for other types of pills and, just for fun, I’ve recorded some other pill-like objects such as skittles candy, beans and lentils.</p><p>Finally, looking to introduce some variation to the data set I&#39;ve captured the data in two different lighting conditions: indirect natural light and direct light using the iPhone X camera flash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*CvAHpXItKVGeUDBoZ16MQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*p9A9f-FldM4wT00W5hbcbA.png" /><figcaption>Image captured with indirect natural light (left) and using the iPhone X camera flash (right)</figcaption></figure><p>I&#39;ve exported the videos from the iPhone using the mac Photos app and then resized down to 256px wide using ffmpeg:</p><pre>for i in Inference*; do ffmpeg -i $i -vf scale=256:-2 small_$i; done</pre><p>With the videos resized to the appropriate size I&#39;ve then used ffmpeg, one more time, to sample 2 frames per second from the video and convert them to PNG images:</p><pre>ffmpeg -i small_Inference_-_1.m4v -vf fps=2 tylenol/tylenol-indirect-%04d.png</pre><pre>ffmpeg -i small_Inference_-_2.m4v -vf fps=2 tylenol/tylenol-flash-%04d.png</pre><p>Here is what the sample images look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*04smX4DfdmbXGAqf3NnSLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*nF0UhOSmpEx7LM91ZULQ_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*CnK4PuwcGYj7dHx3WguF6A.png" /><figcaption>Images created from video captured with the iPhone sampled at 2fps</figcaption></figure><p>I&#39;ve then compressed all images and uploaded to an AWS S3 bucket and pulled the 2.77GB archive to my Udacity Workspace.</p><p>The last step was to convert the images from the 256x456 format down to 256x256 expected by the GoogleLeNet model. Lucky DIGITS offers a few handy image transformations out of the box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*hgBy72m0fo-JeZ8KPrWGaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*0LgCEJncMop0epiRbuxTyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*astqh2KjyCAC0XG3FFgkaQ.png" /></figure><p>Given that most pills fit nicely inside of a 256x256 square I&#39;ve picked the crop transformation that would remove unnecessary blank space and keep the original image ratio. It worked great and all pills were correctly framed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5y18ob0TMPgYyydexPq2A.png" /><figcaption>View of Pills Dataset (train) in DIGITS</figcaption></figure><p>In total, 24,211 images were loaded and then divided as follows:</p><ul><li>18,158 images (75%) for training</li><li>3,631 images (15%) for validation during the training process</li><li>2,422 images (10%) for final test when training completes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpibjqjWH7pI_-wmeQDgtg.png" /><figcaption>PillDataset details</figcaption></figure><p>The dataset was also fairly well balanced across all 10 categories:</p><ul><li>beans: 1,916 images</li><li>tylenoltab: 1,819 images</li><li>tylenolpm: 1,815 images</li><li>vitamin: 1,815 images</li><li>tylenol: 1,813 images</li><li>advil: 1,812 images</li><li>skittles: 1,811 images</li><li>tamsulosin: 1,811 images</li><li>tictac: 1,810 images</li><li>lentil: 1,736 images</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuFrtnHNZh3OkolnJ6aGsg.png" /><figcaption>PillDataset category distribution</figcaption></figure><p>I then created the PillModel from the PillsDataset created above. Once again I’ve opted for the GoogLeNet network architecture with default hyperparameters and and started the training job:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7YYfGoY88eMC7gnnhGW8w.png" /><figcaption>PillModel Training job</figcaption></figure><h3>Results</h3><p>I was thrilled with the training results: the loss converged really quickly in few iterations with accuracy hitting 100% after 30 epochs!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FG6Xa_QZbySghMrVTU6IYg.png" /><figcaption>Final accuracy of 100% after 30 epochs</figcaption></figure><p>The learning rate was lowered by a factor of 10 at every 10 epochs helping SGD to settle to the local minima:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceZTi3iO3bIombMOdMlbvA.png" /><figcaption>Learning rate was lowered by a factor of 10 at every 10 epochs.</figcaption></figure><p>Once the training job completed it was time to evaluate the model against the test dataset made of images the model has not seen during training. Here are a few examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5yc3WuLZ95tWJTTCBK50A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-Zn-peBhrZnnufWCk3tbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0od8nYwphUiBKVl5jBA-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xAoazfP-tJwAz3QUyDmlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_epPdmw-8J-gawivkOB4kA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8wmFevz1zd5Y2X8GfiHaA.png" /></figure><h3>Discussion</h3><p>Overall I&#39;m pleased with the results, the Pill Data Acquisition Platform developed for this project was simple yet extremely efficient collecting thousands of samples in a matter of minutes. The trained model provided consistent results and managed to identify 10 types of pills with strong confidence with inference time under 5ms in average.</p><p>On the other hand, I chose pills that had unique colors, shapes and sizes making it easier for the CNN to learn salient features for each class. I wonder if the results would be the same for pills with similar visual characteristics.</p><p>Also, I realize that I forgot a very important category that my network should have been trained on: “empty”! As identifying that the slot has no pills is as important as classifying them! I’ll make sure to include this category next time.</p><p>Finally, considering that dispensing the incorrect medication would result in disastrous consequences would be wise to design a system that focuses in doing it right in contrast of quickly. With that in mind, it would be worth considering more accurate network types like ResNet and Inception or even classifier ensembles that would take more time to compute the result but at a much higher accuracy.</p><h3>Future Work</h3><p>This project was a lot of fun where I had the chance to get familiar with the Nvidia DIGITS workflow. I found that DIGITS is a great tool to quickly parse training data, training models and evaluating inference systems. It is a great addition to my ML/AI toolbox!</p><p>If time permits, I would like to scale the training data and retrain the model with thousands of new pill types and add it to a potential commercial pill sorting product that will use the inference system to safely dispose medication to patients.</p><p>But now it is time to move to the next project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e05d37792e50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Udacity Robotics ND Project 6— Where Am I?]]></title>
            <link>https://medium.com/@fernandojaruchenunes/udacity-robotics-nd-project-6-where-am-i-8cd657063585?source=rss-7ec560909e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cd657063585</guid>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Fernando Jaruche Nunes]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 00:36:43 GMT</pubDate>
            <atom:updated>2018-07-02T00:57:28.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7B32UDW6yhnOSkwhDt0jLw.png" /><figcaption>My custom robot loosely based on Senna’s F1 car</figcaption></figure><h3>Abstract</h3><p>In this article I&#39;ll go over my submission for the Udacity Robotics ND Project 6 — Where Am I? The goal of this project is to configure a number of ROS packages that can be used in conjunction to accurately localize and navigate a mobile robot inside a provided map in the Gazebo and RViz simulation environments.</p><p>The complete code for this submission can be found here:</p><p><a href="https://github.com/fjnunes/RoboND-Localization-Project">fjnunes/RoboND-Localization-Project</a></p><h3>Introduction</h3><p>This project consists of creating a complete ROS package that includes a Gazebo world, a robot model in URDF and, using the ROS navigation stack, to localize the robot on the map as well as move it to a desired destination and pose avoiding any obstacles on the way!</p><h3>Background</h3><p>Robots often operates in unpredictable environments where the agent is uncertain about its state. Using calculus and probability theory it is possible to manage the this uncertainty and represent the robots beliefs of its state in mathematical form that can later be used for decision making.</p><p>For a robot to find its position on a map (localization problem) it needs to filter noisy sensor data using probabilistic methods. There are 3 types of localization problems:</p><h4>Position tracking</h4><p>This is the first and simplest form of the localization problem: in this scenario the robots initial position is known and the algorithm keeps track of the robot&#39;s position as it moves.</p><h4>Global localization</h4><p>For cases where the initial position is unknown and needs to be determined at as the robot moves. This problem combines the uncertainties from measurements and actions in a cycles to achieve a precise estimate of the location.</p><h4>Kidnaped robot</h4><p>The most difficult localization problem is to recover from abrupt changes in position like moving a robot from a position on the map to another. This is particularly difficult for bayesian algorithms to recover from since they preserve an internal belief that interfere with the new robot state.</p><p>In the classroom we were introduced to two localization methods: Kalman Filters and Particle Filters. Both probabilistic methods can be successfully applied to position tracking and global localization and will later help to localize my robot in Gazebo and RViz.</p><h3><em>Kalman filters</em></h3><p>The Kalman filter estimates the value of a variable by updating its estimate as measurement data is collected filtering out the noise. Kalman Filters models the state uncertainty using Gaussians and it is capable of making accurate estimates with just a few data points.</p><p>KF starts with an initial state estimate then performs the following cycle: measurement update produced by sensor measurements followed by a state prediction from control actions.</p><p><a href="https://en.wikipedia.org/wiki/Kalman_filter">Kalman filter - Wikipedia</a></p><h4>Multidimensional KF</h4><p>Most of real world robots operates on multiple dimensions, i.e. a drone&#39;s position is defined by x, y and z coordinates and orientation in roll, pitch and yaw angles. This motivates generalizing the KF to multiple dimensions with equations in matrix format.</p><p>The MKF algorithm consists of calculating the Kalman Gain K that determines how much weight should be placed on the state prediction, and how much on the measurement update. It is an averaging factor that changes depending on the uncertainty of the measurement and state updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHqTy18Cwx_hAsoPpWM19w.png" /><figcaption>The Kalman gain K averages the measurement update P and motion update x</figcaption></figure><h4>Extended Kalman Filter</h4><p>Kalman Filter assumes that motion and measurement models are linear and that the state space can be represented by a unimodal Gaussian distribution. Most mobile robots will execute non linear motion like following a curve. Non linear actions will result in non-Gaussian posterior distributions that cannot be properly modeled by a closed form equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTv1et0JB7oJ4ULsdfPufw.png" /><figcaption>Gaussian prior (left) subject to a non-linear action (atan(x) — center) results in a non-Gaussian posterior (right)</figcaption></figure><p>EKF approximates motion and measurements to linear functions locally (i.e. by using the first two terms of a Taylor series) to compute a best Gaussian approximation of the posterior covariance. This trick allows EKF to be applied efficiently to a non-linear problems.</p><p><em>y</em>=<em>z</em>−<em>Hx</em>′</p><p>is replaced with the nonlinear h(x&#39;):</p><p>y = z — h(x’)</p><p>This is where the multivariate Taylor series comes into play. The function function h(x) can be approximated by a Taylor series centered about the mean μ, as defined below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTkcK-8YeJJjA6dF6-Aisw.png" /></figure><p>The h(x) approximation above is now linear around <em>μ </em>and will produce a Gaussian posterior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEhVSvLlKdJSWQ2e2M8fPA.png" /><figcaption>Linear approximation (in purple) of the atan(x) function around x = 0</figcaption></figure><h3><em>Particle filters</em></h3><p>Monte Carlo localization algorithm similar to Kalman Filters estimates the posterior distribution of a robot’s position and orientation based on sensory information but instead of using Gaussians it uses particles to model state.</p><p>The algorithm is similar to KF where motion and sensor updates are calculated in a loop but MCL adds one additional step: a particle resampling process where particles with large importance weights (computed during sensor updates) survive while particles with low weights are ignored.</p><p>In the MCL example below all particles are uniformly distributed initially. In the following update steps the particles that better match the predicted state survive resulting in a concentration of particles around the robot estimated location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*obNhTk_-W5yPgkAYPXoxrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*g2Wvc9gqNeglZV4gWrB6qQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mVHFT8g0mQZaXFwjhJx1ag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*O6SQjlEmGada7UO12zRfbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*S2NXYHgm7rKb6e5wzErxNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2Jyn6D_sLRWqjzYNA0-6jw.png" /><figcaption>MCL steps visualization — Particles (green/yellow) start uniformly distributed (step 0) and then concentrates around the ground truth (blue) (steps 1–5). Robot&#39;s sensors read distances to landmarks (red).</figcaption></figure><p>MCL solves the local and global localization problems but similar to KF is not suitable for addressing the kidnaped robot problem.</p><p><a href="https://en.wikipedia.org/wiki/Particle_filter">Particle filter - Wikipedia</a></p><h3>Model Configuration</h3><p>Now lets jump right to the project! After setting-up the world and launch files by following the instructions in the classroom, I proceeded to model the 2 robots below. The first robot based off the classroom (left) and a custom robot that attempts to look like a F1 car (left).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*7it9mmoZzd3K1LnHPt_feQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7B32UDW6yhnOSkwhDt0jLw.png" /><figcaption>Classroom robot (left) and my custom robot (right) loosely based on Senna&#39;s F1 car</figcaption></figure><p>The F1 robot has a differential actuation, just like the classroom robot, instead of 4 wheels of a regular car. I kept only 2 wheels to comply with the <a href="http://wiki.ros.org/navigation">ROS navigation package</a> hardware requirement #1:</p><blockquote>It is meant for both <a href="https://en.wikipedia.org/wiki/Differential_wheeled_robot">differential drive</a> and <a href="https://en.wikipedia.org/wiki/Holonomic_(robotics)">holonomic wheeled</a> robots only. It assumes that the mobile base is controlled by sending desired velocity commands to achieve in the form of: x velocity, y velocity, theta velocity.</blockquote><h3>Tuning Parameters</h3><p>I&#39;ll now describe my journey turning the parameters for each of the packages from the ROS navigation stack. I&#39;ve used the tutorial below as a starting point as it provides an excellent overview of the parameters and packages discussed below.</p><p><a href="http://wiki.ros.org/navigation/Tutorials/RobotSetup">navigation/Tutorials/RobotSetup - ROS Wiki</a></p><h4>amcl.launch</h4><p>The only parameters I needed to tweek in the AMCL launch file was the translational and rotational movement required before performing a filter update. The <a href="http://wiki.ros.org/amcl#Parameters">default values</a> were too large for my slow moving robot. After reducing them by an order of magnitude, I got state updates far more frequently resulting in a reduction of the location uncertainty to a minimum.</p><p>update_min_d = 0.01<br>update_min_a = 0.005</p><p>In my experiments I found that I could get very good results with just 5–20 particles! The more particles the more accurate location will be but at the cost of additional compute resources. To keep the state updates as frequent as possible I decided to keep the particle count down to a minimum.</p><p>min_particles = 5<br>max_particles = 20</p><p>Also I noticed some noisy readings coming from the laser sensor. It would at times detect obstacles at short distances when there was nothing there. To prevent those readings to interfere with the localization I&#39;ve defined a minimum laser range:</p><p>laser_min_range=0.4</p><p>Finally I set the initial pose estimate to zero to coincide with the location of the robot at start-up.</p><p>initial_pose=(0, 0, 0)</p><h4>TrajectoryPlannerROS — base_local_planner_params.yaml</h4><p>The trajectory planner is responsible for computing velocity commands to send to the mobile base of the robot given a high-level plan. I found useful to first understand what was going on under the planner&#39;s covers. Enabling the <a href="http://wiki.ros.org/base_local_planner#Parameters">publish_cost_grid_pc parameter</a> allowed me to visualize the cost_cloud topic in RViz:</p><p>publish_cost_grid_pc: true</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_aEwKpsqE96t09bXqLC31g.png" /><figcaption>A large costmap is heavily influenced by the navigation goal.</figcaption></figure><p>I&#39;ve then noticed that the robot was deviating too much from the global path as if attempting to head straight to the goal. I&#39;ve then changed the parameters below reducing the goal influence (gdist_scale) and increasing the global path (pdist_scale) compliance:</p><p>pdist_scale: 1.0<br>gdist_scale: 0.4</p><h4>local_costmap_params.yaml</h4><p>The local costmap size was by far the most important parameters to get right to successfully navigate around the corner at the end of the corridor. This is because the goal creates a huge influence over the local costmap. This resulted in the robot getting pulled away from the calculated global path. Reducing the size of the local costmap to approximate to the corridor width solved this problem.</p><p>width: 5.0<br>height: 5.0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*veBbCcYnRPkU3Hnf9sBAcg.png" /><figcaption>A smaller costmap will produce a gradient along the global path that is not directly affected by the end goal</figcaption></figure><h4>costmap_common_params.yaml</h4><p>I&#39;ve then adjusted the distance range that the costmap should be updated based off the laser readings to either add or remove obstacles.</p><p>obstacle_range: 4.0<br>raytrace_range: 4.0</p><p>To avoid having the robot bumping on the walls I&#39;ve defined a radius that conformably fits the robot size. This parameters defines a padding that is added to obstacles. The navigation planer then takes the padding into account when calculating the global path.</p><p>inflation_radius: 0.6</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*soFjNHg1FjHmW9A07_HFnA.png" /><figcaption>Cost added by the inflation radius to the global costmap acts as a padding around the walls</figcaption></figure><p>The parameters below depend exclusively on the performance of the VM I ran my tests in. It defines the rate the costmaps should be calculated and published and for how long they are valid. I&#39;ve decreased these values until I got no timeout warning messages.</p><p>transform_tolerance: 0.2<br>update_frequency: 5.0<br>publish_frequency: 2.0</p><p>Finally I&#39;ve lowered the goal tolerances to get a very precise position and orientation when reaching the goal:</p><p>xy_goal_tolerance: 0.05<br>yaw_goal_tolerance: 0.01</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pTTdsaUgChgxZxBHKJwxQ.png" /><figcaption>Low tolerances result in a precise final goal position and orientation</figcaption></figure><h3>Results</h3><p>Both the classroom and my custom robots performed similarly since they have similar mass, size and actuators. In the videos below the robots navigate to the position provided by the nodenavigation_goal and it is possible to observe the AMCL particles converging quickly as soon as the robot starts moving. Thanks to the confident location estimate of the robot position, it successfully follows the global path completing the navigation with a precise final position and orientation to the goal.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBYjwBBco-Fc%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBYjwBBco-Fc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBYjwBBco-Fc%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/df7bb9046e89d3b9c3bf18d652c8f681/href">https://medium.com/media/df7bb9046e89d3b9c3bf18d652c8f681/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsxhouyhjvWQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsxhouyhjvWQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsxhouyhjvWQ%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/9c977d5fb152e48884717a868905975c/href">https://medium.com/media/9c977d5fb152e48884717a868905975c/href</a></iframe><h3>Discussion</h3><p>It took a long time, and a lot of help from the Slack channel, for me to realize that the local costmap size was such a critical parameter. Only after I&#39;ve reduced it to a reasonable size that it became clear how the remaining parameters work. It was infuriating and embarrassing to se my robot doing the complete opposite of what I was expecting.</p><p>I&#39;ve recorded two examples in the bloopers video below: in the first one the robot runs away from the global path. The local planner would completely ignore the global path and attempt to head straight to the goal to then bounce off the wall.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTbWwbmQWIs4%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTbWwbmQWIs4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTbWwbmQWIs4%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/4418b2a755f59cdefda8b8c8e2abc16d/href">https://medium.com/media/4418b2a755f59cdefda8b8c8e2abc16d/href</a></iframe><p>The second scenario was even more intriguing: after reducing gdist_scale in an attempt to reduce the goal influence over the local plan the robot would rotate in place when a goal was defined immediately across the wall, but would start moving immediately when the goal was moved somewhere else! Again the huge goal influence over the large local costmap was the reason for this surprising behavior.</p><p>Also, it is important to point out that the robot would fail to localize when moved to a different location. As discussed previously this is due the fact AMCL is a bayesian algorithms that holds an internal belief of the world that is difficult to change in case of abrupt changes in the environment.</p><p>One way to go about moving the robot from place to place would be to reset the AMCL internal state, back to a uniform distribution of particles, when placing the robot on a new location. This would reduce the kidnaped robot to a global localization problem (or &quot;wake-up robot problem&quot; in that context).</p><h3>Future Work</h3><p>This project was an excellent introduction to the ROS navigation stack. I got to explore a variety of packages that process odometry and sensor streams and outputs velocity commands to send to a mobile base. This is a really useful tool that can be applied to all kinds of mobile robots.</p><p><a href="http://wiki.ros.org/navigation">navigation - ROS Wiki</a></p><p>I&#39;m now eager to extend this project to a real life robot, leveraging the iRobot Create 2 and Slamtec A2 lidar that I recently bought for that reason. There will more to come!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cd657063585" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Udacity Robotics ND Project 4–Follow Me]]></title>
            <link>https://medium.com/@fernandojaruchenunes/udacity-robotics-nd-project-4-follow-me-1668c3a1361d?source=rss-7ec560909e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/1668c3a1361d</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Fernando Jaruche Nunes]]></dc:creator>
            <pubDate>Wed, 14 Mar 2018 15:50:02 GMT</pubDate>
            <atom:updated>2018-03-16T04:36:08.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DS7fj4qh1Hhc3x7dp08Dw.png" /><figcaption>The Drone is using a FCN to follow a target person (in red) from the RGBD camera feed (bottom-right)</figcaption></figure><p>In this article I&#39;ll go over my submission for the 4th and last project for the Robotics ND Term 1. This project consists of designing and training a Fully Convolutional Network (FCN) that provides scene understanding to a Drone that has the mission of following a specific person in a simulated environment.</p><p>The complete code for this submission can be found here:</p><p><a href="https://github.com/fjnunes/RoboND-DeepLearning-Project">fjnunes/RoboND-DeepLearning-Project</a></p><h3>Network Architecture</h3><p>For this project we are interested in not only to classify if a target person is present or not in the input image but also where that person is located so the drone controller can take the necessary actions like: moving closer if target is far away or turning if target it off the center of the image. This problem is known as &quot;semantic segmentation&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*YNX1jgXp0iNlPTCe5aCQOQ.png" /><figcaption>Trained FCN performing semantic segmentation. Input image (left), ground truth (center) and FCN output (left)</figcaption></figure><p>That is the motivation behind building a Fully Convolution Network. In contrast to a classic Convolution Network that classifies the probability a determined class is present in the image, a FCN preserve the spacial information throughout the entire network outputting a map of probabilities corresponding to each pixel of the input image.</p><p>Following the suggestion from the class and notebook I created a FCN consisting of 3 parts: 1) An encoder network that transforms an image input into feature maps followed by 2) 1x1 convolution that combines the feature maps (similar to a fully connected layer) and finally 3) a decoder network that upsamples the result from the previous layer back to the same dimensions as the input image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1k0gPXEog-hVECpGBamVA.png" /><figcaption>Example FCN comprised of Encoder block (left) followed by 1x1 Convolution (center) and Decoder block (right)</figcaption></figure><p>I’ll go over each one of the above modules in detail below.</p><h4>Encoder Block</h4><p>The fist step in building our network is to add feature detectors capable of transforming the input image into semantic representation. This is what the encoder block below does. It squeezes the spacial dimensions at the same time that it increases the depth (or number of filters maps), by using a series of convolution layers, forcing the network to find generic representations of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHFESDDEDIlEex6JKn1E3g.png" /><figcaption>Example of an encoder network</figcaption></figure><p>This is what the code for the encoder block looks like:</p><pre><strong>def</strong> separable_conv2d_batchnorm(input_layer, filters, strides=1):<br>    output_layer = SeparableConv2DKeras(filters=filters,kernel_size=3, strides=strides,<br>                             padding=&#39;same&#39;, activation=&#39;relu&#39;)(input_layer)<br>    <br>    output_layer = layers.BatchNormalization()(output_layer) <br>    <strong>return</strong> output_layer</pre><pre><strong>def</strong> encoder_block(input_layer, filters, strides):<br>    <em># Creates a separable convolution layer using the separable_conv2d_batchnorm() function.</em><br>    output_layer = separable_conv2d_batchnorm(input_layer, filters, strides=strides)<br>    <br>    <strong>return</strong> output_layer</pre><h4>1x1 Convolution</h4><p>In between the encoder block and the decoder block is a 1x1 convolution layer that computes a semantic representation by combining the feature maps from the encoder. It that acts like a fully connected layer where the number of kernels is equivalent to the number of outputs of a fully connected layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDcPT1OpZCXPUsjCAArUbA.png" /><figcaption>1x1 Convolution combines feature maps (depth) preserving spacial information</figcaption></figure><p>The reason for using a 1x1 convolution instead of a fully connected layer is that it preserves spacial information. Fully connected layers, on the other hand, all dimensions are flattened into a single vector losing the original spacial structure of the input.</p><p>One last reason for using convolution: it works for different input sizes while fully connected layers are constrained with a fixed output size.</p><p>This is what the code for the 1x1 convolution layer looks like:</p><pre><strong>def</strong> conv2d_batchnorm(input_layer, filters, kernel_size=3, strides=1):<br>    output_layer = layers.Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding=&#39;same&#39;, activation=&#39;relu&#39;)(input_layer)</pre><pre>output_layer = layers.BatchNormalization()(output_layer) <br>    <strong>return</strong> output_layer</pre><pre>conv1 = conv2d_batchnorm(encoder3, filters=128, kernel_size=1, strides=1)</pre><h4>Decoder Block</h4><p>Finally the decoder block upsamples the output from the 1x1 convolution back to the original input format, through the use of a series of transpose convolution layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHiRVvjNxNzugz7D80K8Ww.png" /><figcaption>Example of a decoder network with a series of upsampling / transpose convolution layers</figcaption></figure><p>I&#39;ve also made use of &quot;skip connections&quot; allowing the network to use information from multiple resolution scales resulting on more precise segmentation decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZ10L_PkPlHoZ3__Oo0pUg.png" /><figcaption>Skip connections example</figcaption></figure><p>This is what the code for the decoder block looks like:</p><pre><strong>def </strong>decoder_block(small_ip_layer, large_ip_layer, filters):<br>    <em># Upsample the small input layer using the bilinear_upsample() function.<br>    </em>upsampled_layer = bilinear_upsample(small_ip_layer)<br><br>    <em># Concatenate the upsampled and large input layers<br>    </em>output_layer = layers.concatenate([upsampled_layer, large_ip_layer])<br><br>    <em># Add some number of separable convolution layers<br>    </em>output_layer = separable_conv2d_batchnorm(output_layer, filters)<br><br>    <strong>return </strong>output_layer</pre><h3>Finding a proper model size</h3><p>After completing the main FCN building blocks I&#39;ve moved into designing the complete network architecture. My strategy to design a reasonable network was to start with a fairly simple (shallow) model and incrementally making it more complex by adding more layers.</p><p>I&#39;ve tried several configurations observing the learning curves patterns and results for each and then settled for the network configuration that was just right for the dataset at hand.</p><h4>FCN Model #1</h4><p>My fist attempt was to simply use a single encoder block followed by a single decoder block:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*abfZUlDRghkzot4PC_3MDw.png" /><figcaption>FCN Model #1 — 1 Encoder and 1 Decoder</figcaption></figure><pre><strong>def </strong>fcn_model1(inputs, num_classes):<br>    <br>    <em># Encoder Blocks<br>    </em>encoder1 = encoder_block(inputs, filters=8, strides=2)<br>    <br>    <em># 1x1 Convolution layer using conv2d_batchnorm().<br>    </em>conv1 = conv2d_batchnorm(encoder1, filters=16, kernel_size=1, strides=1)<br>    <br>    <em># Decoder Blocks<br>    </em>decoder1 = decoder_block(small_ip_layer=conv1, large_ip_layer=inputs, filters=num_classes)<br>    <em><br>    </em><strong>return </strong>layers.Conv2D(num_classes, kernel_size=1, activation=<strong>&#39;softmax&#39;</strong>, padding=<strong>&#39;same&#39;</strong>)(decoder1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*TkzRdJwYbvpFZEYL-U1LeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*6-1Y3fzUJvXdfzl-Hssmnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*XWVKGFkJK7AUIQLsaiSCug.png" /><figcaption>FCN Model #1 — Final score = 0.171411814517</figcaption></figure><p>No surprise here, the network performs poorly getting a score of 17%.</p><h4>FCN Model #2</h4><p>I’ve then added one more pair of encoder/decoder blocks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*qVSXhbkKKS8XDTh1qSDDTg.png" /><figcaption>FCN Model #2–2 Encoders and 2 Decoders</figcaption></figure><pre><strong>def </strong>fcn_model2(inputs, num_classes):<br>    <br>    <em># Encoder Blocks. <br>    </em>encoder1 = encoder_block(inputs, filters=32, strides=2)<br>    encoder2 = encoder_block(encoder1, filters=64, strides=2)<br>    <br>    <em># 1x1 Convolution layer using conv2d_batchnorm().<br>    </em>conv1 = conv2d_batchnorm(encoder2, filters=128, kernel_size=1, strides=1)<br>    <br>    <em># Decoder Blocks<br>    </em>decoder1 = decoder_block(small_ip_layer=conv1, large_ip_layer=encoder1, filters=32)<br>    decoder2 = decoder_block(small_ip_layer=decoder2, large_ip_layer=inputs, filters=num_classes)<br>    <em><br>    </em><strong>return </strong>layers.Conv2D(num_classes, kernel_size=1, activation=<strong>&#39;softmax&#39;</strong>, padding=<strong>&#39;same&#39;</strong>)(decoder2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*PvP3SBl1DNpGcp_2sOOGJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*oLiaKtP5rY2vXkJ0CjvBhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*ZhyfokIR1kMXQvwLWMOI9Q.png" /><figcaption>FCN Model #2 — Final score = 0.26155253301</figcaption></figure><p>We are moving on the right direction! This time the network performs better getting a score of 26%.</p><h4>FCN Model #3</h4><p>Once again, for my third attempt I’ve added yet another pair of encoder/decoder blocks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*oUYRQtEqyPMblASxs_Zcpg.png" /><figcaption>FCN Model #3–3 Encoders and 3 Decoders</figcaption></figure><pre><strong>def </strong>fcn_model3(inputs, num_classes):<br>    <br>    <em># Encoder Blocks. <br>    </em>encoder1 = encoder_block(inputs, filters=32, strides=2)<br>    encoder2 = encoder_block(encoder1, filters=64, strides=2)<br>    encoder3 = encoder_block(encoder2, filters=128, strides=2)<br>    <br>    <em># 1x1 Convolution layer using conv2d_batchnorm().<br>    </em>conv1 = conv2d_batchnorm(encoder3, filters=128, kernel_size=1, strides=1)<br>    <br>    <em># Decoder Blocks<br>    </em>decoder1 = decoder_block(small_ip_layer=conv1, large_ip_layer=encoder2, filters=64)<br>    decoder2 = decoder_block(small_ip_layer=decoder1, large_ip_layer=encoder1, filters=32)<br>    decoder3 = decoder_block(small_ip_layer=decoder2, large_ip_layer=inputs, filters=num_classes)<br>    <em><br>    </em><strong>return </strong>layers.Conv2D(num_classes, kernel_size=1, activation=<strong>&#39;softmax&#39;</strong>, padding=<strong>&#39;same&#39;</strong>)(decoder3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*YNX1jgXp0iNlPTCe5aCQOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*hDqPopVHZG35CNE98XG0xQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*p_ALhyayq6Ilco5JG5P1Pg.png" /><figcaption>FCN Model #3 — Final score = 0.403661134044</figcaption></figure><p>Yay! I got a passing score of a little over 40%! The network this time performs really well identifying the target correctly at different scales.</p><h4>FCN Model #4</h4><p>Finally, I&#39;ve tried adding a 4th block pair and got a worse score of 36%. For that reason I&#39;ve settled with <strong>FCN Model #3</strong>.</p><h3>Choosing the Hyperparameters</h3><p>This was by far the most laborious part of this project. My strategy was to first start with arbitrary values and then later tweak them one-by-one hoping to get to a passing score. I&#39;ll describe my journey below.</p><h4>Batch Size</h4><p>The whole idea of SGD is to <strong>estimate</strong> the error function (and its derivative) by randomly sampling a subset of the training data. This process thus avoids the prohibitive cost of calculating the actual error that requires processing the entire dataset.</p><p>As a guiding principle I assume that the lower the batch size is, the noisier the training signal is going to be. On the flip side a higher batch size, it will take longer to compute the gradient for each step.</p><p>With this motivation in mind, I&#39;ve tried first the smallest possible batch size: <strong>1</strong>. Here is what I got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*ifG476baDgSyMmhCUabT0w.png" /><figcaption>learning_rate = 0.01 — batch_size = 1 — num_epochs = 10 — validation_steps = 100<br>79s — loss: 0.0328 — val_loss: 0.0469 — final_score: 0.206051079873</figcaption></figure><p>The training signal seems to be stable enough and a <strong>batch size of 1</strong> seems to be a suitable value for this dataset.</p><p>Before moving forward, I&#39;ve decided to check for larger values. since larger mini-batch sizes can potentially have performance advantage due to GPU speed-up of matrix-matrix products over matrix-vector products. I&#39;ve then found that the <strong>batch size of 16</strong> halved the time to process one epoch from <strong>80s</strong> to <strong>40s </strong>with a better final score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*WJR9_A7bI0iCQP-_mD7w0w.png" /><figcaption>learning_rate = 0.01 — batch_size = 16 — num_epochs = 10 — validation_steps = 100<br>41s — loss: 0.0351 — val_loss: 0.0536 — final_score: 0.332494734489</figcaption></figure><p>Finally, I&#39;ve increased the batch size further to <strong>64</strong> and thats then I noticed a performance hit with each epoch taking up to <strong>60s</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*oQl7ua80aQ1OHv8YZm7NuQ.png" /><figcaption>learning_rate = 0.01 — batch_size = 64 — num_epochs = 10 — validation_steps = 100<br>58s — loss: 0.0376 — val_loss: 0.0465 — final_score: 0.265805194993</figcaption></figure><p>In conclusion a <strong>batch size of 16</strong> seems to be ideal as it results in a stable training signal and offer the best GPU performance.</p><h4>Learning Rate</h4><p>To find the best value of learning rate I’ve tried different values and then compared the loss curves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*nzyW3qysiagoeX5tND1Lgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*50Sp7oGPKc1lqPxHIG3oKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*cT6gIRY0z_tf4KlLJDPxcQ.png" /><figcaption>Training curves for different values of Learning rate: 0.1 (left) — 0.01(center) — 0.003 (right)</figcaption></figure><h4><strong>Learning rate 0.1:</strong></h4><ul><li>loss: 0.0205</li><li>val_loss: 0.0268</li><li>final_score: 0.367229903911</li></ul><h4>Learning rate 0.01:</h4><ul><li>loss: 0.0175</li><li>val_loss: 0.0249</li><li>final_score: 0.403661134044</li></ul><h4>Learning rate 0.003</h4><ul><li>loss: 0.0178</li><li>val_loss: 0.0308</li><li>final_score: 0.382985155838</li></ul><p>Based on the results above I&#39;ve selected the learning rate of <strong>0.01</strong> because it reached a lower loss and best final score.</p><h4>Number of Epochs</h4><p>The reason I’ve plotted the validation loss along with the training loss was to get a sense of when the model would start to &quot;overfit&quot;. A model is said to overfit when it has great precision on the training set but fails to generalize and ends up performing poorly in the validation set (AKA real life).</p><p>I let the model train for 200 epochs (it took over 3 hours on a p2.xlarge!) and from the result below we can clearly identify the effects of the overfitting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*aB1FFl7USUz783HUbpqpvQ.png" /><figcaption>learning_rate = 0.01 — batch_size = 16 — num_epochs = 200 — validation_steps = 100</figcaption></figure><p>From the curve above we can see that approximately after the<strong> epoch #50</strong> the validation loss stays constant around 0.03 despite constant improvements in the training loss. Since the training beyond that point would only introduce overfitting I&#39;ve decided to stop there.</p><h3>Testing in Simulation</h3><p>With the FCN trained it was time to put it in practice! Below is a video of the FCN deployed as input to the drone that follows the target person:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FV1DSDnN3oPE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DV1DSDnN3oPE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FV1DSDnN3oPE%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/2cea6a306c7cbedcaef6a354f765be63/href">https://medium.com/media/2cea6a306c7cbedcaef6a354f765be63/href</a></iframe><h3>FCNs can only learn from what is in the data</h3><p>It is also worth noting that, despite the fact the FCN above does a great job following a person it would not work for following a dog, cat, car, etc. This is due the fact the model was trained with labeled examples covering only the following 3 categories: 1) the Hero (target person), 2) other people, 3) everything else.</p><p>To create a model that works with more categories it is necessary to collect and label images with enough examples for each class with different poses, distances and lighting conditions. With such dataset on hand it is then possible to train a new model using the same technique described here. This new model would then output more filters, one for each class, those could be used by the drone to follow any one of the classes.</p><h3>Future Enhancements</h3><p>Since the search for hyperparameters was an extremely tedious process I would like to try some sort of automated solution like the Amazon SageMaker Hyperparameter Optimization feature and let it fine tune the parameters automatically.</p><p>I would also try adding dropout to the model to prevent overfitting as well as pooling layers. Pooling would be interesting as it would provide a better way to reduce the spacial dimensions without loosing as much information as convolution strides.</p><h3>Conclusion</h3><p>This was a really exciting project and I&#39;ve started to appreciate how hard it is to architect and train a deep model. Also I&#39;ve learned the importance of good data. It became clear that the model is only as good as the data it is trained on. Collecting good data that covers all scenarios that the model needs to perform well in real life is as challenging as architecting and training the model.</p><p>Overall I wish I got a better score but unfortunately my time is limited and I&#39;m eager to move to Term 2!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1668c3a1361d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Udacity Robotics ND Project 3 — 3D Perception]]></title>
            <link>https://medium.com/@fernandojaruchenunes/udacity-robotics-nd-project-3-3d-perception-2ffc92eeee94?source=rss-7ec560909e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ffc92eeee94</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Fernando Jaruche Nunes]]></dc:creator>
            <pubDate>Wed, 08 Nov 2017 01:46:10 GMT</pubDate>
            <atom:updated>2017-11-08T01:52:13.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NNhHFgoQiaqpk33rz3djg.png" /></figure><p>In this article I&#39;ll go over my submission for the Udacity Robotics Nanodegree 3rd project: 3D Perception. This lesson covered fundamental concepts necessary to create a real world perception pipeline. We learned about camera calibration, point cloud filtering, clustering and trained a simple model to identify objects.</p><p>We were introduced to the PR2: a research robot developed by Willow Garage that costs $400K (yep, almost a half of million dollars!). Lucky the PR2 in simulation did not cost me anything. The goal of the project is to program the PR2 to recognize objects (from the Amazon Robotics Challenge) laying on top of a table, pick them up one by one and, based on a shopping list, place them on the appropriate bins sitting both left and right sides of the robot.</p><p>On the following sections I&#39;ll go over the perception pipeline I&#39;ve created to accomplish this task:</p><h3>Accessing the 3D Camera Data</h3><p>The fist step is to read the data coming from the RGBD sensor. For that I&#39;ve created a ROS node &#39;clustering&#39; and subscribed to the /pr2/world/points topic:</p><pre><em># ROS node initialization<br></em>rospy.init_node(<strong>&#39;clustering&#39;</strong>, anonymous=<strong>True</strong>)<br><em># Create Subscribers<br></em>pcl_sub = rospy.Subscriber(<strong>&quot;/pr2/world/points&quot;</strong>, pc2.PointCloud2, pcl_callback, queue_size=1)</pre><p>The function <strong>pcl_callback</strong> will then be called every time the sensor publishes a new <strong>pc2.PointCloud2</strong> message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJ3t0RUcvpoTRMdlYaygag.png" /><figcaption>Raw image from the camera. Notice the presence of noise artifacts</figcaption></figure><h3>Point Cloud Filtering</h3><p>As it turns out 3D Cameras can at times provide too much information. It is often desirable to work with lower resolutions as well as to limit the focus to a specific region of interest (ROI).</p><p>To reduce the resolution of the camera input down to a tractable amount I&#39;ve applied a downsampling filter that reduced the resolution down to 1 cubic cm:</p><pre># Voxel Grid Downsampling<br>vox = plc_msg.make_voxel_grid_filter()<br>LEAF_SIZE = 0.01<br># Set the voxel (or leaf) size<br>vox.set_leaf_size(LEAF_SIZE, LEAF_SIZE, LEAF_SIZE)<br>downsampled = vox.filter()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdnN4rN59ObNalFmsUqzKQ.png" /><figcaption>Downsampled point cloud</figcaption></figure><p>To make it easier to visualize such sparse point cloud I&#39;ve changed the point style to &quot;Flat Square&quot;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DadyXPYkjH_Nvq4hyn8xvw.png" /><figcaption>Same as above, but using Flat Squares style in RViz</figcaption></figure><p>Then to narrow the focus to the table I&#39;ve applied a pass through filter on the &#39;z&#39; and &#39;y&#39; axis to only capture points above and within the table:</p><pre><em># PassThrough Filter<br></em>passthrough = outliers_removed.make_passthrough_filter()<br><em># Assign axis and range to the passthrough filter object.<br></em>filter_axis = <strong>&#39;z&#39;<br></strong>passthrough.set_filter_field_name(filter_axis)<br>axis_min = 0.6<br>axis_max = 1.1<br>passthrough.set_filter_limits(axis_min, axis_max)<br>passed = passthrough.filter()<br><em># Limiting on the Y axis too to avoid having the bins recognized as snacks<br></em>passthrough = passed.make_passthrough_filter()<br><em># Assign axis and range to the passthrough filter object.<br></em>filter_axis = <strong>&#39;y&#39;<br></strong>passthrough.set_filter_field_name(filter_axis)<br>axis_min = -0.45<br>axis_max = +0.45<br>passthrough.set_filter_limits(axis_min, axis_max)<br>passed = passthrough.filter()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVGqR9pxjMbyb0PyFZjNqg.png" /><figcaption>Using a passthrough filter to crop on the z and y axles</figcaption></figure><h3>RANSAC Plane Segmentation</h3><p>Now that I have selected the data that I need it is time to start identifying the elements in the scene. In the lesson we learn how to use RANSAC to fit a plane in the point cloud. With this technique I was then able to separate the objects from the table:</p><pre># RANSAC Plane Segmentation<br>seg = passed.make_segmenter()<br>seg.set_model_type(pcl.SACMODEL_PLANE)<br>seg.set_method_type(pcl.SAC_RANSAC)</pre><pre>max_distance = LEAF_SIZE<br>seg.set_distance_threshold(max_distance)<br>inliers, coefficients = seg.segment()<br><br># Extract inliers and outliers<br># Extract inliers - tabletop<br>cloud_table = cloud_filtered.extract(inliers, negative=False)<br># Extract outliers - objects<br>cloud_objects = cloud_filtered.extract(inliers, negative=True)</pre><p>Here <strong>Inliers</strong> are the points that fit a plane equation therefore should belong to the table. On the other hand <strong>outliers</strong> are the remaining points that represent the objects over the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0i7EjbnkPlU_DZFT_CXqZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RxdcV4k1k63XIzE06MQaCA.png" /><figcaption>RANSAC Plane Inliers (table) on the left and outliers (objects) on the right</figcaption></figure><h3>Clustering Segmentation</h3><p>Finally I’ve used Euclidean Clustering to distinguish the objects from one another. This approach differs from k-means in the sense that it doesn&#39;t require the prior knowledge of the number of objects we are trying to detect. Unfortunately it uses an hierarchical representation of the point cloud that can be computationally expensive to obtain.</p><pre><em># Euclidean Clustering<br></em>white_cloud = XYZRGB_to_XYZ(cloud_objects)<br>tree = white_cloud.make_kdtree()</pre><pre><em># Create a cluster extraction object<br></em>ec = white_cloud.make_EuclideanClusterExtraction()<br><em># Set tolerances for distance threshold<br># as well as minimum and maximum cluster size (in points)<br></em>ec.set_ClusterTolerance(LEAF_SIZE*2)<br>ec.set_MinClusterSize(10)<br>ec.set_MaxClusterSize(2500)<br><em># Search the k-d tree for clusters<br></em>ec.set_SearchMethod(tree)<br><em># Extract indices for each of the discovered clusters<br></em>cluster_indices = ec.Extract()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcioNha9AXy-EJsfc94NlA.png" /><figcaption>Objects separated from one another by using Euclidean cluster segmentation</figcaption></figure><p>That&#39;s it! Now that I have all objects separated from one another it is time to classify them. For that I&#39;ll use a simple but powerful Machine Learning tool: Support Vector Machine (SVM)</p><h3>Extracting Point Cloud Features</h3><p>SVMs are not as sophisticated as Deep Neural Nets and they require some hand crafted features to work properly. The features that I’ve created are color and normals histograms concatenated together:</p><pre><em># Extract histogram features<br></em>chists = compute_color_histograms(sample_cloud, using_hsv=<strong>True</strong>)<br>normals = get_normals(sample_cloud)<br>nhists = compute_normal_histograms(normals)<br>feature = np.concatenate((chists, nhists))<br>labeled_features.append([feature, model_name])</pre><p>The rational is that histograms do a fairly good job at capturing the overall color and shape characteristics of point clouds but with a limited number of dimensions.</p><h3>Training the SVM Model</h3><p>With the labeled dataset in hand, I moved to training the SVM model. The only change I made to the <strong>train_svm.py</strong> script was to change the kernel type to RBF (Radial Basis Function) to allow for more complex decision boundaries resulting in richer features.</p><pre><em># Create classifier<br></em>clf = svm.SVC(kernel=<strong>&#39;rbf&#39;</strong>)</pre><p><a href="https://en.wikipedia.org/wiki/Radial_basis_function_kernel">Radial basis function kernel</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*nBFlWC2wngchEg8HtM3Vkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*j3UQGIZ9wv-IbmyfoIN_GQ.png" /><figcaption>Comparison between linear and RFB kernels</figcaption></figure><p>I quickly notice how powerful SVMs are for small datasets. It only took me 20 examples per class to get to a very high accuracy! Usually DNNs, as a comparison, requires thousands of examples per class for decent results.</p><h3>Object Recognition and Results</h3><p>My model did a great job identifying objets. It recognized most of the objects successfully on all table configurations. It only failed to recognize 1 object out of 8 on World 3: A glue stick that was partially occluded by a book:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*mG8UGBAXj9NAEUotT32X2A.png" /><figcaption>Recognition result for World 3. Glue is occluded by the book and get misclassified as &quot;snacks&quot;</figcaption></figure><p>The prediction pipeline consists of loading the model from a file then scaling the input feature vector appropriately (scaler also comes with the model file) and finally calling the predict method:</p><pre><em># Make the prediction, retrieve the label for the result<br># and add it to detected_objects_labels list<br></em>prediction = clf.predict(scaler.transform(feature.reshape(1, -1)))<br>label = encoder.inverse_transform(prediction)[0]<br>detected_objects_labels.append(label)<br><br><em># Publish a label into RViz<br></em>label_pos = list(white_cloud[pts_list[0]])<br>label_pos[2] += .4<br>object_markers_pub.publish(make_label(label, label_pos, index))</pre><p>Following are the results for all table top configurations (Worlds 1, 2 and 3):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*7qJ7SsY-F9mEH3CjYN7LmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*HNt4sq5pDQblzkpfoT7yKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*P8u1F7q2d99BKC2fxBQk9g.png" /><figcaption>Results for worlds 1, 2 and 3 respectively</figcaption></figure><h3>Pick Place ROS Message Request</h3><p>The final piece to complete this project is to calculate all necessary arguments to call the <strong>pick_place_routine</strong> service to perform a successful pick and place operation. Also these parameters should be written to a yaml file, presumably to make it easier to grade the project submission.</p><h4>Reading Parameters</h4><p>The object list and dropbox locations where retrieved as a list from the parameter server. I&#39;ve then converted them into dictionaries making it easier to lookup the configuration values for a specific object.</p><pre><em># Get/Read parameters<br></em>object_param_list = rospy.get_param(<strong>&#39;/object_list&#39;</strong>)<br>dropbox_param_list = rospy.get_param(<strong>&#39;/dropbox&#39;</strong>)<br><br><em># Parse parameters into individual variables<br># Transform parameter list in dictionaries<br></em>object_param_dict = {}<br><strong>for </strong>idx <strong>in </strong>range(0, len(object_list_param)):<br>    object_param_dict[object_list_param[idx][<strong>&#39;name&#39;</strong>]] = object_list_param[idx]<br><br>dropbox_param_dict = {}<br><strong>for </strong>idx <strong>in </strong>range(0, len(dropbox_param_list)):<br>    dropbox_param_dict[dropbox_param_list[idx][<strong>&#39;group&#39;</strong>]] = dropbox_param_list[idx]</pre><h4>Calculating Centroid and Pose Messages</h4><p>I&#39;ve then iterated over each detected object and calculated its centroid by averaging all points. I&#39;ve decided what arm to use and what bin the object should be dropped based on the object list and dropbox dictionaries.</p><p>I&#39;ve also introduced some randomness on the drop-off location to prevent objects from piling on top of each other resulting on a better use of the bin space.</p><pre><em># Loop through the detected objects<br></em><strong>for </strong>object <strong>in </strong>object_list:<br>    <em># Get the PointCloud for a given object and obtain it&#39;s centroid<br>    </em>points_arr = ros_to_pcl(object.cloud).to_array()<br>    centroid = np.mean(points_arr, axis=0)[:3]<br><br>    <em># Get config param for that kind of object<br>    </em>object_param = object_param_dict[object.label]<br>    <em># Get corresponding dropbox param<br>    </em>dropbox_param = dropbox_param_dict[object_param[<strong>&#39;group&#39;</strong>]]<br><br>    object_name.data = str(object.label)<br><br>    <em># </em><strong><em>Create &#39;pick_pose&#39; for the object<br>    </em></strong>pick_pose.position.x = np.asscalar(centroid[0])<br>    pick_pose.position.y = np.asscalar(centroid[1])<br>    pick_pose.position.z = np.asscalar(centroid[2])<br>    pick_pose.orientation.x = 0.0<br>    pick_pose.orientation.y = 0.0<br>    pick_pose.orientation.z = 0.0<br>    pick_pose.orientation.w = 0.0<br><br>    <em># </em><strong><em>Create &#39;place_pose&#39; for the object<br>    </em></strong><em># Location on the dropbox + incremental offset so things don&#39;t pile up<br>    </em>position = dropbox_param[<strong>&#39;position&#39;</strong>] + np.random.rand(3)/10<br>    place_pose.position.x = float(position[0])<br>    place_pose.position.y = float(position[1])<br>    place_pose.position.z = float(position[2])<br>    place_pose.orientation.x = 0.0<br>    place_pose.orientation.y = 0.0<br>    place_pose.orientation.z = 0.0<br>    place_pose.orientation.w = 0.0<br><br>    <em># Assign the arm and droppbox side to be used for pick_place<br>    </em>arm_name.data = str(dropbox_param[<strong>&#39;name&#39;</strong>])<br><br>    <em># Create a list of dictionaries (made with make_yaml_dict()) for later output to yaml format<br>    # Populate various ROS messages<br>    </em>yaml_dict = make_yaml_dict(test_scene_num, arm_name, object_name, pick_pose, place_pose)<br>    dict_list.append(yaml_dict)</pre><h4>Creating the .yaml Output Files</h4><p>Once all parameters are set they are then converted to yaml format by calling <strong>make_yaml_dict</strong> and appending the results to <strong>dict_list</strong>. This list is then encapsulated into an object and serialized to output_&lt;world#&gt;.yaml file:</p><pre><em># Output your request parameters into output yaml file<br></em>send_to_yaml(<strong>&quot;output_&quot;</strong>+str(WORLD_ID)+<strong>&quot;.yaml&quot;</strong>, dict_list)</pre><h3>Improvements and Future Work</h3><p>Despite having satisfactory results I was not able to address the camera noise issue. In the future I&#39;ll add a StatisticalOutlierRemoval filter at the beginning of the perception pipeline.</p><p>I&#39;ll also work on improving the SVM model accuracy to achieve a correct prediction of the glue that was misclassified as &quot;snacks&quot;.</p><p>Finally I want to tackle the additional challenges of creating a collision map, sending the request to pick and place the objects and play with different table top configurations.</p><h3>Project Implementation</h3><p>The complete code is available <a href="https://github.com/fjnunes/RoboND-Perception-Project">in my fork</a> of the <a href="https://github.com/udacity/RoboND-Perception-Project">RoboND-Perception-Project</a>:</p><p><a href="https://github.com/fjnunes/RoboND-Perception-Project">fjnunes/RoboND-Perception-Project</a></p><h3>Conclusion</h3><p>This was a fun project and gave me a really good overview of point clouds, how to create a perception pipeline to identify objects and how to integrate perception and motion planing modules using ROS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ffc92eeee94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Udacity Robotics ND Project 2 — Robotic Arm: Pick & Place]]></title>
            <link>https://medium.com/@fernandojaruchenunes/udacity-robotics-nd-project-2-robotic-arm-pick-place-71af9c9ba519?source=rss-7ec560909e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/71af9c9ba519</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[udacity]]></category>
            <dc:creator><![CDATA[Fernando Jaruche Nunes]]></dc:creator>
            <pubDate>Wed, 11 Oct 2017 02:32:13 GMT</pubDate>
            <atom:updated>2017-10-11T03:23:22.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2S2lhDdEXWOoIQ-Z-Gfz6A.png" /><figcaption>KUKA KR210 Moving the blue cylinder to the bin</figcaption></figure><p>Oh boy, this was a though project! In this article I&#39;ll be going over the second project for the Udacity Robotics Nanodegree Robotic Arm: Pick &amp; Place. This project is modeled after the <a href="https://www.amazonrobotics.com/#/roboticschallenge">Amazon Robotics Challenge</a> and consists of a robotic arm that should be programmed to pick objects from a shelf and place them on a bin in a different location.</p><p>The Amazon Challenge involves many disciplines like: perception in a clutter environment, safe and versatile grippers, motion planing and kinematics. For this Udacity project we will be focusing on the last one: kinematics.</p><h3>Kinematic Analysis</h3><p>Kinematics studies how things move in a 3D environment. For this project we are exploring reference frames, generalized coordinates, degrees of freedom and homogeneous transforms.</p><p>Next we learnt that robots are most commonly controlled via revolute and prismatic joints (both with 1 degree of freedom) and converting from joint values (Joint Space) to a world reference (Cartesian Space) is know as Forward Kinematics Problem.</p><p>Conversely, Inverse Kinematics Problem transforms cartesian coordinates into respective joint values. I quickly learnt that this is a much harder problem as it often results into multiple valid solutions, or none! No solution simply means the cartesian point is out of the robot working space (or reach). On the other hand, multiple solutions indicates that the point can be reached with different configurations of the robotic arm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MKIToEIlYdtlDzzhDwV2w.png" /><figcaption>Forward and Inverse Kinematics transforms Joint Space to Cartesian Space and vice versa</figcaption></figure><h3>Denavit-Hartenberg Parameters</h3><p>We learnt about the Denavit-Hartenberg Parameters <em>α(alpha)</em>, <em>a</em>, <em>d</em>, and <em>θ</em> created to simplify the homogeneous transform equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJHI6OZhagYZ42XCZBp7GQ.png" /></figure><p>Where:</p><ul><li><em>α(alpha)</em>​ = arm twist angle</li><li><em>a </em>= arm link length</li><li><em>d</em>​ = arm link offset</li><li><em>θ</em>​ = arm joint angle</li></ul><h3>Finding the values for the KUKA Arm KR210</h3><p>Ok, this is the hardest part of this project: To compare the joint reference diagram (below) with the link references from RViz and construct the DH parameter table. Below I&#39;ll go over joint by joint calculating first its respective <strong>a</strong> and <strong>d</strong> values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dih6FLBPPyrv0xZqXvLzWA.png" /><figcaption>Joint reference frames and DH parameters a and d</figcaption></figure><h4>Joint 1</h4><ul><li><em>a0 </em>= 0, since this is the base link.</li><li><em>d1</em>​ = link2_[z] = 0.75</li></ul><h4>Joint 2</h4><ul><li><em>a1 </em>= link_2[x] = 0.35</li><li><em>d2</em>​ =0, since X1 and X2 are perpendicular.</li></ul><h4>Joint 3</h4><ul><li><em>a2 </em>= link_3[z] = 1.25</li><li><em>d3</em>​ =0, since X2 and X3 are coincident.</li></ul><h4>Joint 4</h4><ul><li><em>a3 </em>= link_3[z] - link_5[z] = 2–1.9464 = 0.0536</li><li><em>d4</em>​ = link_5[x]- link3[x] = 1.8499–0.3485= 1.5014</li></ul><h4>Joint 5</h4><ul><li><em>a4 </em>= 0, since O4 and O5 are coincident.</li><li><em>d5</em>​ =0, since X4 and X5 are coincident.</li></ul><h4>Joint 6</h4><ul><li><em>a5 </em>= 0, since O5 and O6 are coincident.</li><li><em>d6</em>​ =0, since X5 and X6 are coincident.</li></ul><h4>Joint 7 (Gripper Joint)</h4><ul><li><em>a6 </em>= 0, since Z6 is coincident with Z7.</li><li><em>d7</em>​ = link_gripper[x]-link_5[x]= 2.1529–1.8499 = 0.303</li></ul><h4>Link Reference Frames</h4><p>Below are the link reference values used on the calculations above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ToutQM47cnZ_ljFhYfrOg.png" /></figure><h4>Twist Angles</h4><p>Finally the twisted angles are give below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWgfwcICOSBBEVspmXos4w.png" /></figure><h4>DH parameter table for KUKA KR210</h4><p>Finally compiling the values calculated above results the DH parameter table below. I&#39;ll then use it to create homogeneous transformation matrices between joints.</p><pre><em># Create Modified DH parameters<br></em>DH = {   alpha0: 0,      a0: 0,      d1: 0.75,    q1: q1,<br>         alpha1: -pi/2,  a1: 0.35,   d2: 0,       q2: q2-pi/2,<br>         alpha2: 0,      a2: 1.25,   d3: 0,       q3: q3,<br>         alpha3: -pi/2,  a3: 0.0536, d4: 1.5014,  q4: q4,<br>         alpha4: pi/2,   a4: 0,      d5: 0,       q5: q5,<br>         alpha5: -pi/2,  a5: 0,      d6: 0,       q6: q6,<br>         alpha6: 0,      a6: 0,      d7: 0.303,   q7: 0}</pre><h3>Homogeneous Transformations</h3><p>Given the DH parameters we can represent the homogeneous transform from frame <strong><em>i-1</em></strong> to frame <strong><em>i</em></strong> is constructed as a sequence of four basic transformations, two rotations and two translations as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*GIaA5x5qzjycWazdjSeHnQ.png" /></figure><p>Multiplying all four transformations results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTljOgxZp98r0WphMWv4Yw.png" /></figure><p>Note that only 4 Denavit-Hartenberg Parameters are necessary to construct the Homogeneous Transformation above.</p><p>Here is what the code to create this matrix looks like:</p><pre><em>### Creates Homogeneous Transform Matrix from DH parameters<br></em><strong>def </strong>homogeneous_transform(q, d, a, alpha):<br>    T = Matrix(<br>[[cos(q),            -sin(q),           0,             a          ],<br>[ sin(q)*cos(alpha), cos(q)*cos(alpha), -sin(alpha), -sin(alpha)*d],<br>[ sin(q)*sin(alpha), cos(q)*sin(alpha),  cos(alpha),  cos(alpha)*d],<br>[                 0,                 0,           0,             1]]<br>    )<br>   <strong>return </strong>T</pre><h4>Individual joints transformation matrices</h4><p>For the individual joints transformation matrices we only need to build the homogeneous transformation with the symbols and then substitute them with the corresponding DH parameters:</p><pre><em># Create individual transformation matrices</em><strong><br></strong>T0_1 = homogeneous_transform(q1, d1, a0, alpha0).subs(DH)<br>T1_2 = homogeneous_transform(q2, d2, a1, alpha1).subs(DH)<br>T2_3 = homogeneous_transform(q3, d3, a2, alpha2).subs(DH)<br>T3_4 = homogeneous_transform(q4, d4, a3, alpha3).subs(DH)<br>T4_5 = homogeneous_transform(q5, d5, a4, alpha4).subs(DH)<br>T5_6 = homogeneous_transform(q6, d6, a5, alpha5).subs(DH)<br>T6_G = homogeneous_transform(q7, d7, a6, alpha6).subs(DH)</pre><h4>Generalized homogeneous transform</h4><p>In order to calculate the transformation from the base link to the end-effector (gripper) we need to perform <strong>intrinsic</strong> transformations by pre-multiplying all individual joints transformation matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*TJub6sYIqu2CH6CIOdVMDA.png" /></figure><pre><em># Generalized homogeneous transform<br></em>T0_G = T0_1 * T1_2 * T2_3 * T3_4 * T4_5 * T5_6 * T6_G</pre><h3>Decoupling the Inverse Kinematics problem</h3><p>Ok, now that I have the forward kinematics modeled it is time to tackle the real problem: calculate all joint angles for a trajectory, defined as an array of poses, calculated by MoveIt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFqwtNBsLLp8u1XXo8ArfQ.png" /><figcaption>Trajectory calculated by MoveIt</figcaption></figure><p>The inverse kinematics problem was resolved analytically by dividing the problem in two parts: 1) Find the first 3 joint angles (counting from the base) from the pose position and 2) Find the remaining 3 wrist joint angles from the pose orientation.</p><h3>Inverse Position Kinematics</h3><p>First I have to find the position of the center of the wrist given the end-effector coordinate. But before that I need to account for a rotation discrepancy between DH parameters and Gazebo (URDF):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmaI2zgI4c3aSAKAfB3lFw.png" /><figcaption>URDF coordinate system in green and DH frame reference in yellow</figcaption></figure><p>For that I&#39;ve created a correctional rotation composed by a rotation on the Z axis of 180° (π) followed by a rotation on the Y axis of -90 (-π/2):</p><pre><em># Compensate for rotation discrepancy between DH parameters and Gazebo<br></em>R_corr = R_z.subs(y, pi) * R_y.subs(p, -pi/2)</pre><p>Finally I&#39;ve performed a translation on the opposite direction of the gripper link (that lays on the Z axis) to find the wrist center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPaHvL4G2rP6k4JEhyNNIQ.png" /></figure><p>The equation below calculates the wrist center by applying a translation on the opposite direction of the gripper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*P9VPaZOW0nWbw9Y9sCqA3g.png" /></figure><p>From the DH parameter table we can find that the griper link offset (d7) is 0.303m:</p><pre><em># Calculate joint angles using Geometric IK method<br></em># Calculating the Rotation Matrix for the Gripper<br>r, p, y = symbols(<strong>&#39;r p y&#39;</strong>)<br>R_x = rot_x(r)<br>R_y = rot_y(p)<br>R_z = rot_z(y)</pre><pre>Rrpy = R_z * R_y * R_x * R_corr<br>Rrpy = Rrpy.subs({<strong>&#39;r&#39;</strong>: roll, <strong>&#39;p&#39;</strong>: pitch, <strong>&#39;y&#39;</strong>: yaw})<br><br><em># Calculate the wrist center position<br></em>nx = Rrpy[0,2]<br>ny = Rrpy[1,2]<br>nz = Rrpy[2,2]</pre><pre># d7: 0.303<br>wx =  px - 0.303 * nx<br>wy =  py - 0.303 * ny<br>wz =  pz - 0.303 * nz</pre><p>Once the wrist center (WC) is known we can calculate the first joint angle with a simple arctangent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRE3mHVp4GbzPY9DeDidKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*ZUFzuISx8uNpaxX7nQ3gJw.gif" /></figure><p>And here is the code:</p><pre><em># Theta 1 from above is a simple atan2 in x and y<br></em>theta1 = atan2(wy, wx)</pre><pre><em># Calculate Radius from above (will be used later)<br></em>r = sqrt(wx**2+wy**2) - 0.35 # a1: 0.35</pre><p>For calculating the joints 2 and 3 I&#39;ve used the picture bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUPMumopKFCwu8uSP-0_ag.png" /></figure><p>With the help of the Law of Cosines I&#39;ve calculated the values for angles <strong>a</strong> and <strong>b</strong>.</p><p><a href="https://en.wikipedia.org/wiki/Law_of_cosines">Law of cosines - Wikipedia</a></p><p>I could then calculate joints 2 and 3 with the following code:</p><pre><em># Calculating Theta 2 and 3 using cosine law. A, B and C are sides of the triangle<br></em>A = 1.5014 # d4<br>B = sqrt(r**2+(wz-0.75)**2) <em># d1: 0.75</em><br>C = 1.25 # a2<br><br><em># a corresponds to angle alpha<br></em>a = acos((B**2 + C**2 - A**2) / (2*B*C))<br>theta2 = pi/2 - a - atan2(wz-0.75, r) <em># d1: 0.75</em><br><br><em># b corresponds to angle beta<br></em>b = acos((A**2 + C**2 - B**2) / (2*A*C))<br>theta3 = pi/2 - (b + 0.036)</pre><h3>Inverse Orientation Kinematics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*tqMhRqw58M1A8VTGXKgMsw.png" /></figure><p>The equation above indicates that the rotation matrix from 0 to 3 needs to be inverted. Inverting a matrix is a complex operation and can be numerically unstable. As pointed out on the #udacity_pick_place Slack channel we can simply use transpose matrix instead. Thats because the rotation matrices are orthogonal and its transpose is equals as its inverse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zPvaS9AgYEZldOI5g-L1pA.png" /><figcaption>Orthogonal matrices properties leads to transpose equals to inverse</figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Orthogonal_matrix">Orthogonal matrix - Wikipedia</a></p><p>So instead of inverting using LU decomposition as pointed out on the project notes I&#39;ve simply used the transpose:</p><pre><em># Calculating Euler angles from orientation<br></em>R0_3 = T0_1[0:3,0:3] * T1_2[0:3,0:3] * T2_3[0:3,0:3]<br>R0_3 = R0_3.evalf(subs={<strong>&#39;q1&#39;</strong>:theta1, <strong>&#39;q2&#39;</strong>:theta2, <strong>&#39;q3&#39;</strong>:theta3})<br><em># R3_6 = R0_3.inv(&quot;LU&quot;)*Rrpy # using transpose instead:<br></em>R3_6 = R0_3.T * Rrpy<br><br>theta4 = atan2(R3_6[2,2], -R3_6[0,2])<br>theta5 = atan2(sqrt(R3_6[0,2]**2 + R3_6[2,2]**2), R3_6[1,2])<br>theta6 = atan2(-R3_6[1,1], R3_6[1,0])</pre><h3>Project Implementation</h3><p>The complete code is available in <a href="https://github.com/fjnunes/RoboND-Kinematics-Project">my fork</a> of the <a href="https://github.com/udacity/RoboND-Kinematics-Project">RoboND-Kinematics-Project</a>:</p><p><a href="https://github.com/fjnunes/RoboND-Kinematics-Project/blob/master/kuka_arm/scripts/IK_server.py">fjnunes/RoboND-Kinematics-Project</a></p><h4>Pick and Place in Action!</h4><p>Here is a video of a few executions of the pick &amp; place cycle:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fl_GFuEMQzoM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dl_GFuEMQzoM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fl_GFuEMQzoM%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/14344919e5ed0c867bd15c0cf6b2eb04/href">https://medium.com/media/14344919e5ed0c867bd15c0cf6b2eb04/href</a></iframe><h3>Conclusion</h3><p>This was a difficult project and made me realize how fortunate we are for having IK solvers built in MoveIt.</p><p>I left this project with many questions about trajectory planing (not covered in the classroom). The trajectories provided by MoveIt were all valid but they didn&#39;t seem to be optimal. I hope future lessons on planing will shed some light on this.</p><p>I&#39;m now eager to move on to the next project: Perception!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71af9c9ba519" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Udacity Robotics ND Project 1 — Search and Sample Return]]></title>
            <link>https://medium.com/@fernandojaruchenunes/udacity-robond-project-1-search-and-sample-return-2d8165a53a78?source=rss-7ec560909e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d8165a53a78</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nanodegree]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[udacity]]></category>
            <dc:creator><![CDATA[Fernando Jaruche Nunes]]></dc:creator>
            <pubDate>Fri, 08 Sep 2017 14:57:02 GMT</pubDate>
            <atom:updated>2017-10-07T03:10:50.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWGtDJ_fVPB-r_eGo36-Tw.png" /><figcaption>Screenshot of my submission: 97% mapped with 73.5% fidelity. 4 out of 6 rocks collected.</figcaption></figure><p>In this article I’ll discuss my submission for the project Search and Sample Return as part of the Udacity Robotics Nanodegree. This is my first submission and what I learnt right off the bat is that Udacity reviewers are not only interested in code that solves the challenge/project but also a comprehensive discussion around implementation decisions. So here we go!</p><p>This project is modeled after the <a href="https://www.nasa.gov/directorates/spacetech/centennial_challenges/sample_return_robot/index.html">NASA Sample Return Challenge</a> and consists of implementing code that will be used to operate a Rover in a simulated environment to map its surroundings, make decisions on how to navigate the terrain avoiding obstacles and, as a bonus, to colect some sample rocks and return to the starting point.</p><p>The complete code discussed here is available in <a href="https://github.com/fjnunes/RoboND-Rover-Project">my fork</a> of the original <a href="https://github.com/udacity/RoboND-Rover-Project">RoboND-Rover-Project</a>:</p><p><a href="https://github.com/fjnunes/RoboND-Rover-Project">fjnunes/RoboND-Rover-Project</a></p><h3>Python Notebook Analysis</h3><p>A Python Notebook was provided to demonstrate the concepts covered in the course material including camera calibration, perspective transform, color thresholding and coordinate transforms: camera to robot, robot to world and euclidian to polar.</p><p>We were asked to add/modify functions to allow for color selection of obstacles and rock samples. I&#39;ll discuss in more detail below:</p><h4>Detecting Obstacles / Navigable Terrain</h4><p>The terrain has a good contrast with bright navigable areas and dark obstacles. So a simple threshold defined by trial and error was enough to separate the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*JhxG90KAwB_l30VTem3Kgw.jpeg" /><figcaption>Image captured by the camera onboard of the Rover</figcaption></figure><p>To detect the navigable terrain is as simple as filtering the pixels that are above a arbitrary threshold of 160 (camera values ranges from 0 to 255).</p><pre>threshed = color_thresh(warped, rgb_thresh=(160, 160, 160))<br>plt.imshow(threshed, cmap=&#39;gray&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*m18SFrhfnJewyQhI-fnUqQ.png" /><figcaption>Camera image warped and thresholded</figcaption></figure><p>The Notebook hints that the obstacles are simply the inverse of navigable terrain. But, since I decided to warp the image to top-down view before thresholding I needed first to ignore the pixels out of the field of view (the two dark triangular areas on the bottom left and right). For that I&#39;ve created a mask consisting of a warped white image:</p><pre>mask = np.ones_like(threshed)<br>mask[:,:] = 255<br>mask = perspect_transform(mask, source, destination)<br>plt.imshow(mask, cmap=&#39;gray&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*IQ_gos1y7S67wSeZiIVlUQ.png" /><figcaption>Mask used to filter out the pixels out of the field of view</figcaption></figure><p>Finally, I&#39;ve applied the mask to the inverse of the navigable terrain to get the obstacles:</p><pre><em>#identify obstacles</em><br>obstacles = np.absolute((np.float32(threshed)-1) * mask)<br>plt.imshow(obstacles, cmap=&#39;gray&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*e_rFgYM3wKjBWMjHyDWssw.png" /><figcaption>Obstacles mask. Note that lower corners are also black since out of field of view.</figcaption></figure><h4>Detecting Rock Samples</h4><p>As discussed before, the Rover needs to identify (and, as a bonus, collect) rock samples. Rocks are mostly yellow and look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*cGnRONY9r58-TDTCSTvZ0w.jpeg" /><figcaption>Rock sample sitting on top of navigable terrain</figcaption></figure><p>Once again the Notebook instructions are very helpful suggesting to impose a lower and upper thresholding bounds to select the yellow color. It also points to the following tutorial that explains that HSV colorspace is much easier to work with than RGB as you only need to impose the bounds to the Hue channel:</p><p><a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html">Changing Colorspaces - OpenCV-Python Tutorials 1 documentation</a></p><p>I found that the rock color falls around the Hue value of 24. So I&#39;ve converted the image from RGB (actually BGR) to HSV and then taking lower and upper bounds by 10 points bellow and above that value I got a mask that clearly isolates the rock sample on the image.</p><pre><em>#identify the rock</em><br>lower_yellow = np.array([24-10,100,100])<br>upper_yellow = np.array([24+10,255,255])<br><br><em># Convert BGR to HSV</em><br>hsv = cv2.cvtColor(rock_img, cv2.COLOR_RGB2HSV)<br><em># Threshold the HSV image to get only upper_yellow colors</em><br>mask = cv2.inRange(hsv, lower_yellow, upper_yellow)<br><br>plt.imshow(mask, cmap=&#39;gray&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*Vm5EaYxoTp6LiTTA60OCPw.png" /><figcaption>Rock sample mask extracted from applying lower and upper HSV bounds</figcaption></figure><p>The last sections on the Notebook explored converting the masks discussed above mapping them to world coordinates and comparing them to a ground truth image.</p><p>I’ll cover this in more detail in the following section where I’ll describe my implementation of the Rover Perception Module followed by a similar discussion around the Decision Module.</p><h3>Rover Perception Module</h3><p>Implementing the Perception Module was fairly easy as most of the work was already completed and tested on the Notebook. I&#39;ve moved the code from the Notebook to the perception_step() at the bottom of the perception.py script.</p><p>The goal here is to map at least 40% of the environment at 60% fidelity and locate at least one of the rock samples. It consists of populating a world map that is then compared with a ground truth.</p><p>I&#39;ve converted the navigable, obstacles and samples masks first from camera coordinates to Rover coordinates (using roover_coords() method) and then finally to world coordinates (using the pix_to_world() method).</p><h4>Strategies Used to Increase Map Fidelity</h4><p>In order to get the best possible map fidelity, I’ve combined two approaches discussed in the <a href="https://www.youtube.com/watch?v=-L0Fz4UnlC8">RoboND Rover Project Livestream</a>: 1) To limit the measurements from the camera to 8 meters and 2) Only update the map if the Rover Roll and Pitch values are around zero (plus or minus 1 degree).</p><p>Given that camera measurement accuracy decreases with the distance I&#39;ve imposed a distance limit by using the following method originally from @wsteiner (Slack handle) to filter out points further out than 8 meters:</p><pre><strong>def </strong>impose_range(xpix, ypix, range=80):<br>    dist = np.sqrt(xpix**2 + ypix**2)<br>    <strong>return </strong>xpix[dist &lt; range], ypix[dist &lt; range]</pre><p>Since the perspective transform methods assume that the Rover is parallel to the ground I&#39;ve decided to only use the measurements where Roll and Pitch values were around zero. Anything above that would introduce significant distortion especially when the Rover bumps on some obstacle or breaks suddenly to catch a rock sample.</p><p>Also I cleaned up the obstacle pixels that overlapped with navigable terrain measurements. Here is what the code looks like:</p><pre><strong>if </strong>(Rover.pitch &lt; 1 <strong>or </strong>Rover.pitch &gt; 359) <strong>and </strong>(Rover.roll &lt; 1 <strong>or </strong>Rover.roll &gt; 359):<br>    Rover.worldmap[obstacle_y_world, obstacle_x_world, 0] = 255<br>    Rover.worldmap[rock_y_world, rock_x_world,1] = 255<br>    Rover.worldmap[navigable_y_world, navigable_x_world, 2] = 255<br>        <em># remove overlap mesurements<br>    </em>nav_pix = Rover.worldmap[:, :, 2] &gt; 0<br>    Rover.worldmap[nav_pix, 0] = 0<br>        <em># clip to avoid overflow<br>    </em>Rover.worldmap = np.clip(Rover.worldmap, 0, 255)</pre><p>Finally, I calculated the navigable terrain and rocks into a polar coordinate system (using the to_polar_coords() method) that will be used later on the Decision Module to control the Rover steering:</p><pre>dist, angles = to_polar_coords(xpix_navigable, ypix_navigable)<br>Rover.nav_dists = dist<br>Rover.nav_angles = angles<br>    <em># Same for rock samples<br></em>dist, angles = to_polar_coords(xpix_rocks, ypix_rocks)<br>Rover.samples_dists = dist<br>Rover.samples_angles = angles</pre><h3>Rover Decision Module</h3><p>The Rover Decision Module was the most exciting part of the project. It consisted of using the perception data from the Perception Module to move the Rover around the terrain.</p><p>The goal is to cover the most terrain in the least amount of time. In order to achieve that I (and many others) decided to implement a wall following approach. On the live stream a few mentioned that hugging the left wall was easier so that was my choice.</p><p>The code changes described below where made to the decision_step() function within the decision.py script.</p><h4>Calculating the Steering Offset</h4><p>The boilerplate code provided by Udacity demonstrated how to steer the Rover using the mean angle of the navigable points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*7TwJxgvzn751o93n9I0DvQ.png" /><figcaption>Navigable points in Rover polar coordinates (in blue) and vector (in red) showing the mean angle.</figcaption></figure><p>A simple way to implement the wall following behavior (as discussed in the Live Stream) is to add a positive offset (to the left in my case) to the mean angle (shown above). But I quickly discovered that a constant offset was not enough because it would a times turn the Rover too much and hit the wall e.g. on narrow hallways or it wound&#39;t turn enough and at times it would miss corners completely.</p><p>Therefore, I decided that adjusting the offset based on the standard deviation of the angles was the way to go. This allowed for small offsets on straight lines and large ones in corners and open areas:</p><pre><em># Steering proportional to the deviation results in<br># small offsets on straight lines and<br># large values in corners and open areas<br></em>offset = 0.8 * np.std(Rover.nav_angles)</pre><p>This simple formula resulted in very robust behavior. I choose to scale the standard deviation by 0.8 via trial and error. The Rover kept steering leaving most of the navigable pixels to the right and keeping an almost constant distance to the wall at all times. This can be seen on the video bellow:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqXI4AUifN3s%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqXI4AUifN3s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqXI4AUifN3s%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/dda63ff5ba5d310b18cd2dcf610a49bd/href">https://medium.com/media/dda63ff5ba5d310b18cd2dcf610a49bd/href</a></iframe><h4>Stuck State</h4><p>The terrain is full of tricky spots and the Rover can get stuck often. To deal with this I&#39;ve created a new state: &quot;stuck&quot;. Once in the stuck state the rover will try to turn to the right for a second (found empirically) and return to the previous state. I&#39;ve modified the code to have a simple state stack that allowed for the Rover to resume to the previous state easily:</p><pre><em># If we&#39;re already in &quot;stuck&quot;. Stay here for 1 sec<br></em><strong>elif </strong>Rover.mode[-1] == <strong>&#39;stuck&#39;</strong>:<br>    <em># if 1 sec passed go back to previous mode<br>    </em><strong>if </strong>Rover.total_time - Rover.stuck_time &gt; 1:<br>        <em># Set throttle back to stored value<br>        </em>Rover.throttle = Rover.throttle_set<br>        <em># Release the brake<br>        </em>Rover.brake = 0<br>        <em># Set steer to mean angle<br>        # Hug left wall by setting the steer angle slightly to the left<br>        </em>Rover.steer = np.clip(np.mean((Rover.nav_angles+offset) * 180 / np.pi), -15, 15)<br>        Rover.mode.pop() <em># returns to previous mode<br>    # Now we&#39;re stopped and we have vision data to see if there&#39;s a path forward<br>    </em><strong>else</strong>:<br>        Rover.throttle = 0<br>        <em># Release the brake to allow turning<br>        </em>Rover.brake = 0<br>        <em># Turn range is +/- 15 degrees, when stopped the next line will induce 4-wheel turning<br>        # Since hugging left wall steering should be to the right:<br>        </em>Rover.steer = -15</pre><p>The Rover gets into the stuck state if it finds itself on forward mode, not moving and not on the stuck state for at least 4 seconds. The last condition was necessary to keep the Rover from oscillating between forward and stuck modes. The code looks like this:</p><pre><em># If mode is forward, navigable terrain looks good<br># Except for start, if stopped means stuck.<br># Alternates between stuck and forward modes<br></em><strong>if </strong>Rover.vel &lt;= 0.1 <strong>and </strong>Rover.total_time - Rover.stuck_time &gt; 4:<br>    <em># Set mode to &quot;stuck&quot; and hit the brakes!<br>    </em>Rover.throttle = 0<br>    <em># Set brake to stored brake value<br>    </em>Rover.brake = Rover.brake_set<br>    Rover.steer = 0<br>    Rover.mode.append(<strong>&#39;stuck&#39;</strong>)<br>    Rover.stuck_time = Rover.total_time</pre><h4>Sample Rock State</h4><p>Once I got the Rover to navigate most of the terrain and map it to a fairly good fidelity without getting stuck, I then moved to picking up the sample rocks. For that I&#39;ve created yet another state: &quot;rock&quot;.</p><p>Once in the rock state the Rover will brake if it is going too fast and turn and move slowly towards the rock sample by steering to <em>samples_angles</em> mean. Once it gets close enough to the rock it will come to a complete stop and that will kick off the pickup process (already implemented by Udacity). Once the rock is no longer in sight it will go back to the previous state.</p><p>I&#39;ve also limited this state for rocks closer than 3 meters. This was necessary to avoid the Rover to fall off its trajectory to pick a rock on the opposite wall.</p><p>Lastly I&#39;ve added a timeout limit of 20 seconds for this state so it will give up and move back to the previous state if too much time is spent attempting to retrieve a rock that is hard to get for some reason:</p><pre><strong>elif </strong>Rover.mode[-1] == <strong>&#39;rock&#39;</strong>:<br>    <em># Steer torwards the sample<br>    </em>mean = np.mean(Rover.samples_angles * 180 / np.pi)<br>    <strong>if not </strong>np.isnan(mean):<br>        Rover.steer = np.clip(mean, -15, 15)<br>    <strong>else</strong>:<br>        Rover.mode.pop() <em># no rock in sight anymore. Go back to previous state<br><br>    # if 20 sec passed gives up and goes back to previous mode<br>    </em><strong>if </strong>Rover.total_time - Rover.rock_time &gt; 20:<br>        Rover.mode.pop()  <em># returns to previous mode<br><br>    # if close to the sample stop<br>    </em><strong>if </strong>Rover.near_sample:<br>        <em># Set mode to &quot;stop&quot; and hit the brakes!<br>        </em>Rover.throttle = 0<br>        <em># Set brake to stored brake value<br>        </em>Rover.brake = Rover.brake_set<br><br>    <em># if got stuck go to stuck mode<br>    </em><strong>elif </strong>Rover.vel &lt;= 0 <strong>and </strong>Rover.total_time - Rover.stuck_time &gt; 10:<br>        Rover.throttle = 0<br>        <em># Set brake to stored brake value<br>        </em>Rover.brake = Rover.brake_set<br>        Rover.steer = 0<br>        Rover.mode.append(<strong>&#39;stuck&#39;</strong>)<br>        Rover.stuck_time = Rover.total_time<br>    <strong>else</strong>:<br>        <em># Approach slowly<br>        </em>slow_speed = Rover.max_vel / 2<br>        <strong>if </strong>Rover.vel &lt; slow_speed:<br>            Rover.throttle = 0.2<br>            Rover.brake = 0<br>        <strong>else</strong>:  <em># Else break<br>            </em>Rover.throttle = 0<br>            Rover.brake = Rover.brake_set</pre><p>Below is a video of the Rover picking up some rocks. Notice that for the 3rd rock it goes around large obstacles to retrieve it from a really tight spot!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTgAcPZE1jXo%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTgAcPZE1jXo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTgAcPZE1jXo%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/d46f73ddf65e8a35dc31b2796d90854c/href">https://medium.com/media/d46f73ddf65e8a35dc31b2796d90854c/href</a></iframe><h3>Changes to RoverState</h3><p>I&#39;ve made a few changes to the RoverState class on drive_rover.py script mostly to accommodate for new attributes and to increase the maximum speed to 3m/s and max throttle to 50%. I&#39;ve also increased stop_forward to 100 pixels to allow for more space to break due to the increase of the max speed.</p><h3>Results</h3><p>The Rover does a good job following the left wall avoiding trouble by getting unstuck if necessary. It also collects most of the sample rocks it finds on its path. It maps up to 97% of the terrain with a fidelity of 73.5%.</p><p>Bellow is a 8x video of the Rover from start to finish:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8jY9X0X2I38%3Fstart%3D5%26feature%3Doembed%26start%3D5&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8jY9X0X2I38&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8jY9X0X2I38%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/c13e56a1a93384bf4cddc544ad95f86e/href">https://medium.com/media/c13e56a1a93384bf4cddc544ad95f86e/href</a></iframe><h3>Improvements and Future Work</h3><p>I&#39;m really happy with my submission but there are a few things I wish I had the time to tackle:</p><h4>Return to the starting point</h4><p>The final piece of the puzzle was to have the Rover to go back to the initial position and come to a complete stop. Unfortunately I&#39;m already a week past the suggested deadline so I&#39;ll have to skip this one.</p><p>There are many ways to implement this but the easiest (and for what I would go first) would be to save the initial position when the simulation starts and query if the Rover is close to this position AND all (or most) of the rock samples have been already collected. This condition would bring the Rover to a new state: &quot;home&quot;</p><p>Once in the home state the Rover would, just like for the rock state, slow down and steer on the direction of the initial position, stoping when close enough.</p><h4>Collect all the sample rocks</h4><p>One of the problems that I notice with my state machine is that it goes back to a previous state whenever a rock is no longer in sight. This is problematic for rocks that are hidden under tight spots. When the Rover approaches and breaks violently that causes the camera to miss the rock for a few frames causing the state to go back to forward mode skipping the rock completely.</p><p>To solve this would require improvements on both the state tracking and also the control of the Rover to avoid slamming the breaks when approaching a rock.</p><h4>Use a PID controller to avoid oscillating behavior</h4><p>Lastly, I would like to use a PID controller to make the Rover steering feel smoother and more natural. I’ve checked and PID controller is going to be covered in future lessons.</p><h3>Conclusion</h3><p>This was a great challenge and a lots of fun! The Python Notebook was a helpful starting point but also left a lot of issues unsolved so I would have to figure them out by myself. I&#39;m really excited with the results I got and with the concepts I learn in this lesson. I&#39;m now eager to move on to the ROS Essentials Lesson!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d8165a53a78" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>