<?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 Michael Chein on Medium]]></title>
        <description><![CDATA[Stories by Michael Chein on Medium]]></description>
        <link>https://medium.com/@michaelchein?source=rss-5557dfb2d00f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BZRJNH-U-Eqh0muLk1GkHw.png</url>
            <title>Stories by Michael Chein on Medium</title>
            <link>https://medium.com/@michaelchein?source=rss-5557dfb2d00f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:51:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michaelchein/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[Keeping your kids active during quarantine by turning their bicycle into a keyboard]]></title>
            <link>https://medium.com/data-science/keeping-your-kids-in-shape-during-quarantine-by-turning-their-bicycle-into-a-keyboard-e1f8a34fac2e?source=rss-5557dfb2d00f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1f8a34fac2e</guid>
            <category><![CDATA[kids-and-tech]]></category>
            <category><![CDATA[cycling]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[makers]]></category>
            <dc:creator><![CDATA[Michael Chein]]></dc:creator>
            <pubDate>Mon, 04 May 2020 02:43:57 GMT</pubDate>
            <atom:updated>2020-10-11T18:43:45.205Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this short tutorial, I’ll walk you through the process of turning any bicycle into an arcade-like controller for computer games.</h4><p>Despite not setting the <em>best</em> example for leading a healthy lifestyle, my wife and I do try to eat our greens, avoid too much junk, and keep in shape. Our 5 year old on the other hand, couldn’t care less about doing any physical activity, unless it gets him closer to his (my…) iPad.</p><p>Normally, This issue is partially remedied simply by being a kid, which involves a fair amount of running, climbing, falling… and recently cycling! But unfortunately, with the advent of the COVID-19 pandemic, we can’t really do any of that.</p><p>So, I turned his bicycles into a keyboard.</p><p>Now, he can play his favourite computer games and exercise at the same time! In this short article, I’ll walk you through the process of building your very own <em>keyboard bike</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*QWa3afuRmRX62fjw.gif" /></figure><h3>Foundations:</h3><p>The first step is turning the bicycle into indoor training bikes by getting the rear wheel to spin freely without touching the ground, and allow the handlebars to turn freely as well. If your kid is propelled forward, you should NOT proceed to the following steps.</p><p>There are many ways of getting the bike to remain in place while spinning the pedals. Hanging the bicycle from the ceiling, digging a hole in the floor beneath the wheel and many more. I personally used the training wheels to support the rear, but this is your place to get creative, and more importantly, <strong>be responsible</strong>. I am deliberately avoiding getting into too much detail about my implementation of this part (you can get a pretty good idea from the various pictures and gifs in this article…) as it is your responsibility to make sure that the bicycle are secure and safe to use.</p><h3>The plan</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*na5VtELM1XiOrigO.png" /></figure><p>After securing the bike so that it can be pedalled in place, we will connect sensors to capture the rotation of the rear wheel, position of the handle bars and some buttons for extra control (these can be easily programmed later to map any keyboard key). Data from all sensors will be captured and transformed by an Arduino that will function as a keyboard and send keystrokes to a computer running a (most likely racing) game.</p><h3>Hardware</h3><p>We must use a board that can function as a USB keyboard. I used <a href="https://store.arduino.cc/arduino-leonardo-with-headers">Arduino Leonardo</a>.</p><p>I used 3 types of sensors:<br><strong>1</strong>. <a href="https://www.allegromicro.com/en/products/discontinued-product-archive/a1301-2"><strong>A1302 Hall Effect Sensor</strong></a><strong> </strong>— This sensor changes its output voltage when in the proximity of a magnetic field. We will use it to transform the rotation of the rear wheel to a forward key press.<br><strong>2.</strong> <a href="https://www.sparkfun.com/products/9939"><strong>10K ohm linear potentiometer</strong></a><strong> </strong>— Used to transform the handlebar orientation to left/right keys.<br><strong>3.</strong> <a href="https://www.sparkfun.com/products/13013"><strong>Microswitch</strong></a> — used as extra controllers. I <strong>highly</strong> recommend using this type of switches (limit switch) and not going for some fancy buttons. these switches are very responsive, whereas buttons can sometimes be challenging for a kid to press.</p><h3>Connecting the parts</h3><h4>Hall effect sensor</h4><p>By placing magnets on the rear wheel, and positioning the sensor close (as close as possible without touching the wheel), we can sense the wheel’s rotation as the magnets pass by the sensor. I used two magnets equally spaced (that is ~180 degrees apart).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*VZpZHYFhwk6VEabC.gif" /></figure><p><strong>A tip for attaching the magnets -</strong></p><p>You could probably find a more elegant solution, but the one I used here is to wrap the magnets in plastic wrap and twist the ends, like a candy wrap (I am referring to the white blobs seen spinning with the wheel in the gif above). Then use the loose ends to tie the magnets to the wheel’s spokes, and secure with hot glue.</p><p>In order to get the sensor (this is referring to the red vertical rod in the gif, the sensor itself is located at its end) as close to the wheel as possible I mounted it to a flexible wire (I used some heavy duty electrical wire but any wire that will flex and keep its position will do).</p><h4>Potentiometer</h4><p>The potentiometer needs to be connected to the pivot point of the handlebars. There should be a socket for an allen wrench at that point. I used a fitting driver bit and connected it to the potentiometer. Originally, my plan was to solder both parts together, but driver bits have low (none) solder-ability. I ended up taking a short piece of straw (seen in the gif below in violet) sticking the potentiometer and driver bit from both sides, and injecting it with hot glue, to keep everything together. It’s solid as a rock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/0*w6aae36901ngQosw.gif" /></figure><p>As for securing the potentiometer to the bike frame, you will again need to get creative. my solution (which can be seen in the trailer gif and in the image at the end of the article showing all components detached from the bike) was based on making a plexiglass “arm” to hold the potentiometer in place, and may not work for your child’s bike. The idea is simple, the potentiometer needs to spin with the handlebars. Simple as it is, the implementation can be quite challenging…</p><h4>Switches</h4><p>I placed one of the switches behind the (redundant) front wheel brake lever, and the other one behind the not redundant back wheel brake lever, and disconnected this brake, so that the switches are pressed by pressing the brakes, which feels very natural.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/0*btWpihduBsv6e1YM.gif" /></figure><p>Again, I’m not taking any responsibility here. if you feel the supports you made in part 1 are not strong enough and are worried about obstructing and/or disconnecting brakes, you can, and should place the buttons somewhere else. No right or wrong, as long as it’s comfortable and safe. I limited myself to two buttons but you can obviously go as high as the board allows.</p><h3>Wiring</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P7C3bk8u_qdUxP4P.png" /></figure><h3>A note on thinking ahead.</h3><p>After completing <em>keyboard-bike version 1.0</em>, I set up to improve it by making sure I can easily disconnect all components and reassemble them again as quickly as possible, this required some tweaking, that could have been avoided if I had thought of this at the get go. It took me nearly <em>2 hours</em> to upgrade to <em>keyboard-bike version 2.0</em>, but it now takes <em>less than a minute</em> to assemble/disassemble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zzSS1OFl6_hhNK-T.png" /></figure><p>Another point to keep in mind is what’s the best place to secure the board. I thoughtlessly put it on the side my son gets on and off the bike. In retrospect, I should have chosen the other side…</p><h3>Code</h3><p>As explained in the hardware section, the <em>keyboard bike</em> setup is composed of 3 types of sensors: Hall effect sensor, potentiometer, and buttons. I’ll explain the code for each component separately.</p><h4>Hall effect sensor</h4><p>The hall effect sensor is “activated” when the wheel spins and the magnets pass by the sensor, inducing a change in output voltage. For this part, I switched on the key (forward key in my case) whenever there was an absolute change in voltage above a certain threshold (hall_effect_threshold). I then keep it on and start counting back for a certain amount of time (drive_decay_const). This allows tuning the amount of motion you get from each &quot;spike&quot;. Increase the value of drive_decay_const to get more movement.</p><h4>Potentiometer</h4><p>Here we’re basically trying to convert an “analog” motion of turning the handlebars into a “binary” left or right clicks. A continuous press is way too dramatic if you just want to make small adjustments, so the amount of turn needs to be represented as “click amount”. I’m doing this by activating and deactivating turning movement at a set interval (interval), so that turning the handlebars beyond a certain threshold, will start pressing intermittently. In addition, I add a delay while the button is activated, that grows with the amount of turn. So for higher angle turns, the button will be pressed for a longer duration (that is, each click will be longer) resulting in a more aggressive turn. Also, notice that I&#39;m initialising pot_center at setup. this is helpful for cases where the potentiometer gets disconnected from the socket. Instead of having to relocate the center, you can just reset the board, and the center will be reset.</p><h4>Switches</h4><p>Nothing special here. Just replace the activated key to suit your needs. The code here is for playing <a href="https://supertuxkart.net/Main_Page">SuperTuxKart</a> which is a great racing game for kids, but the bike could obviously be adjusted for many other games. We also use it to play Minecraft, which works great.</p><pre>/*<br>bicycle_keyboard<br>*/#include &quot;Keyboard.h&quot;<br>const int hall_effect_threshold = 1      // threshold for hall effect sensor.<br>const int turn_threshold = 35;           // threshold for detecting a left/right movement. <br>const int drive_decay_const = 100;       // drive_decay speed of car (larger =&gt; slower decreasing / faster car)<br>const int turn_decay_const = 0.75;       // multiplier for intensity of turn. higher value =&gt; sharper turns. <br>const char button_1_val = &#39; &#39;;           // value for button 1<br>const char button_2_val = &#39;n&#39;;           // value for button 2<br>const long interval = 200;               // interval for allowing not allowing turns.<br>const int button_1 = 2;                  // button_1 pin <br>const int button_2 = 3;                  // button_2 pin<br>int pot_center = 500;                    // center point for potentiometer. this value is being reset in setup.<br>int prev_hallSensorValue = 0;            // initial value for sensor<br>const int delay_time = 1;                // delay between reads<br>int drive_decay = 0;                     // initial drive_decay value<br>unsigned long previousMillis = 0;        // initial value<br>bool allow_turn = true;                  // allow turn is a boolean to only allow turns every passing interval <br>int turn_amount = 0;                     // initial value<br>void setup() {<br>  Serial.begin(9600);<br>  Keyboard.begin();<br>  pinMode(button_1, INPUT);<br>  pinMode(button_2, INPUT);<br>  pot_center = analogRead(A1);<br>}<br>void loop() {<br>  unsigned long currentMillis = millis();<br>  int hallSensorValue = analogRead(A0);<br>  int pot = analogRead(A1);//  Serial.println(hallSensorValue);<br>//  Serial.println(pot);  delay(delay_time);        // delay in between reads for stability  // DRIVE:<br>  if (abs(hallSensorValue- prev_hallSensorValue) &gt;1){<br>    prev_hallSensorValue = hallSensorValue;<br>    Keyboard.press(KEY_UP_ARROW);<br>    drive_decay = drive_decay_const;<br>  }<br>  else{<br>    if (drive_decay &lt;= 0){<br>        Keyboard.release(KEY_UP_ARROW);<br>        }<br>    else{<br>      drive_decay -=1;<br>      }<br>    }if (allow_turn==true){//TURN RIGHT<br>  if (pot &lt; pot_center - turn_threshold) {<br>    Keyboard.press(KEY_RIGHT_ARROW);<br>    } <br>// TURN LEFT<br>  if (pot &gt; pot_center + turn_threshold){<br>    Keyboard.press(KEY_LEFT_ARROW);<br>  }}<br>    if (currentMillis - previousMillis &gt;= interval) { // interval has passed<br>    previousMillis = currentMillis;<br>    turn_amount = abs(pot-pot_center);    // switch allow turn state:<br>    if (allow_turn == true) {<br>      if (turn_amount &gt; turn_threshold){<br>          delay(turn_amount); //keep button pressed longer the more aggressive the turn.<br>        }<br>      allow_turn = false;<br>    } else {<br>      allow_turn = true;<br>      }<br>     // release the turn keys:<br>      Keyboard.release(KEY_RIGHT_ARROW);<br>      Keyboard.release(KEY_LEFT_ARROW);<br>    }  //check buttons<br>  if (digitalRead(button_1) == HIGH){<br>    Keyboard.press(button_1_val);<br>    }<br>   else{<br>     Keyboard.release(button_1_val);<br>    }  if (digitalRead(button_2) == HIGH){<br>    Keyboard.press(button_2_val);<br>    }<br>   else{<br>     Keyboard.release(button_2_val);<br>    }<br>}</pre><h3>Summary</h3><p>To conclude, I hope I did a good job of explaining how to get the <em>keyboard bike</em> built. If you chose to build one, and find that I have not, don’t hesitate to post a comment or send me a message.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1f8a34fac2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/keeping-your-kids-in-shape-during-quarantine-by-turning-their-bicycle-into-a-keyboard-e1f8a34fac2e">Keeping your kids active during quarantine by turning their bicycle into a keyboard</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backpropagation for people who are afraid of math]]></title>
            <link>https://medium.com/data-science/backpropagation-for-people-who-are-afraid-of-math-936a2cbebed7?source=rss-5557dfb2d00f------2</link>
            <guid isPermaLink="false">https://medium.com/p/936a2cbebed7</guid>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Michael Chein]]></dc:creator>
            <pubDate>Thu, 14 Feb 2019 15:58:38 GMT</pubDate>
            <atom:updated>2019-02-15T18:02:09.836Z</atom:updated>
            <content:encoded><![CDATA[<p>Backpropagation is one of the most important concepts in machine learning. There are many online resources that explain the intuition behind this algorithm (IMO the best of these is the backpropagation lecture in the Stanford <a href="http://cs231n.stanford.edu/">cs231n video lectures</a>. Another very good source, is <a href="https://en.wikipedia.org/wiki/Backpropagation">this</a>), but getting from the intuition to practice, can be (put gently) quite challenging.</p><p>After spending more hours then i’d like to admit, trying to get all the sizes of my layers and weights to fit, constantly forgetting what’s what, and what’s connected where, I sat down and drew some diagrams that illustrates the entire process. Consider it a visual pseudocode.</p><h3>The Challenge: From intuition to practice</h3><p>So, assuming you have a good intuitive understanding of what the algorithm should be doing, but are having trouble getting it to work, this post is for you!</p><p>Now, to be clear, this post will NOT make any attempt to explain the intuition part. As I wrote previously, there are many good and reliable resources that do just that. This is a simple (as simple as the algorithm allows..) practical guide to help you get your code to work. In fact, your code will probably work if you follow these steps with no intuition whatsoever. Still, I highly encourage you to read a bit about the <a href="https://en.wikipedia.org/wiki/Perceptron">perceptron</a> (Note, the perceptron uses a non differentiable step activation function, so you can’t really use backpropagation, but its structure, and weights updating method did form the basis for more complex neural networks). This is the bare bone neural network, consisting of only one layer. Understanding how to update the weights of a simple network, is REALLY helpful before jumping into a more complex one.</p><p>When training a network, we repeat the following steps (for <em>n</em> epoches):</p><ol><li>Perform forward pass.</li><li>Calculate ∆W (the delta to be added to each weight) via backpropagation.</li><li>Update the weights.</li></ol><p>In this article, I am going to focus on step #2.</p><p>Ready? Let’s jump in!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FJDKxRN0Bvmm2c%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fterminator-gif-arnold-schwarzenegger-JDKxRN0Bvmm2c&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2FJDKxRN0Bvmm2c%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="232" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeef114b39e7862d0e28961a0fab1eef/href">https://medium.com/media/aeef114b39e7862d0e28961a0fab1eef/href</a></iframe><h3>Deciphering the equation</h3><p>The illustration below is a schematic representation of an arbitrary network. As the process of backpropagation is basically the same for every step (depending on the <a href="https://medium.com/the-theory-of-everything/understanding-activation-functions-in-neural-networks-9491262884e0">activation function</a> you use). We are only looking at the final layers (You can regard layer L95 as the input layer, if that makes you feel more secure. It makes no difference as far as the calculation is concerned).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYCa1g9X_j11o4JWoQV1cg.png" /></figure><p>As you can see, our arbitrary network has 5 neurons on layer 95, then 2 neurons on layer 96, then 4, 3, 3, and 1 neuron for the output layer (L100). All layers are connected by weights, marked (traditionally) by lines.<br>Notice that each node is separated into <em>Z</em> and <em>O</em>. For each node, the <em>Z</em> values are calculated by multiplying the <em>O </em>values of the previous layer, with the weights connecting them with that node. <em>O</em> is obtained by applying a non linear activation function on <em>Z</em>. Now, below you will find the dreaded gradient calculation. Fear not! We will go over each expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*FFEmXNTGeNcN995ANFl6zg.png" /></figure><p>When trying to update and optimize the network’s weights, we are trying to find-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/59/1*HcPLH3PcK4Y1WUORSQ3Lpg.png" /></figure><p>, The derivative of the loss with regard to the weights (“how does a change to the weights effects the loss”), and using the chain rule, divide this task into three:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/1*iyR3Q3jzpot_3GrIwqeAyQ.png" /></figure><p>The derivative of the loss with regard to the next layer. This is the loss “passed upstream” from the output layer. or in other words- “How does a change to the next layer, effects the loss”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/1*sug_AV0S74zKFWYij6m7fg.png" /></figure><p>The derivative of the next layer with regard to the current layer (which can be interpreted as “how a change in the current layer effects the next layer”), which is simply the weights connecting to the next layer multiplied by the derivative of its activation function. and-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/59/1*K_SPSZeYuy4EsUj2LplWvA.png" /></figure><p>- (“How does a change to the weights affect the current layer”), which is the previous layer’s <em>O</em> values, multiplied by the current layer’s activation function derivative.</p><p>To make things clearer, I’ve written the actual calculations, color coded to our network, for the last two layers of our network, L100 and L99.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGPTU4aCUiLY2f8_L6nnVw.png" /></figure><p>Notice that the derivative term related to each calculation appears below it. The two derivatives associated with the loss, appearing in red, are of utmost importance, as they are used in the calculations for the previous layers. This can be seen clearly in the next diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jV2brg3c6K7RvB_BK_VnUw.png" /></figure><p>Notice how ∂Loss <strong>propagates</strong> down the layers. Looking at this pattern, you should start seeing how this could be implemented in code. Also notice that I’ve highlighted the last two layers, which form the before mentioned Perceptron.</p><p>Note that I didn’t mention multiplying the entire expression by the learning rate (α) in this diagram, as it seemed too crowded and shadowed the take home messages, which is the application of the chain rule. you should definitely play with different α values to get the best performance. In any case, α does appear in the next diagram.</p><h3>Backpropagating over a batch of instances</h3><p>An important point to notice is that each layer in the schematic representations we saw, is in fact a vector, representing the computations done for a <strong>single</strong> instance. Usually we would like to input a batch of instances into the network. This will be clearer after going over the next diagram, which shows the calculation for a batch of <em>n </em>instances. Notice that this is the same exact network (5 neurons for layer L95, 2 neurons for layer L96 and so on…), only that we are now looking at <em>n</em> instances and not just one.</p><p>The most challenging part for me, when implementing backpropagation, was to get the sizes of the different layers and weights and gradient matrices to play nice. This illustration aims to set things in order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pXNLsJ0iaA2gk502jxdBA.png" /></figure><p>On top you will see the schematic network. The actual size of <em>n</em> makes no difference (for the calculations. obviously it does make a difference in the larger scheme of things…), for as you will notice, when we perform matrix multiplications while backpropagating, we always sum over <em>n</em>. that is to say, the length of <em>n</em> is “lost” during matrix multiplication. And this is exactly what we want, to sum over the loss from all instances in our batch.</p><p>The rest of the diagram is divided into two sections:</p><ul><li><strong>Forward pass.</strong></li><li><strong>Backpropagation.</strong></li></ul><p>The <strong>forward pass</strong> should be pretty obvious to most of you. If it’s not, I would recommend reading about matrix multiplications before moving any further. One thing I will point out is the fact that each weight matrix takes a layer of size <em>(n,k)</em> and outputs a layer of size <em>(n,j)</em>. such weight matrix will be of size <em>(k,j)</em>.<br>You will probably notice that this diagram is missing the bias unit. That is because I wanted to keep it as clear as possible, and focus on how the different matrices sizes fit into the backpropagation process. There is a short section on adding the bias unit below.</p><p>The <strong>backpropagation</strong> part is a “bit” trickier… :)<br>This section of the diagram is divided into <strong>three subsections</strong>:</p><h4><strong>1. Variables</strong></h4><p>Here I list the different elements of the calculation, and most importantly, their shape. A few notes on this part:</p><ol><li><em>Z</em> refers to the layer’s values before activation.</li><li><em>O</em> refers to the layer’s values after activation.</li><li><em>σ</em> refers to the activation function.</li><li><em>g’</em> refers to the derivative of the activation function.</li></ol><p>Notice that this section groups the variables constituting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/1*sug_AV0S74zKFWYij6m7fg.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/1*iyR3Q3jzpot_3GrIwqeAyQ.png" /></figure><p>at the top (highlighted in red), and those constituting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/59/1*K_SPSZeYuy4EsUj2LplWvA.png" /></figure><p>at the bottom (highlighted in blue).</p><h4><strong>2. Calculation</strong></h4><p>This is where all the drama takes place. There is actually nothing new here. These are the same exact calculations seen on the previous diagrams, but with matrix sizes clearly written and depicted. Also, when to use element wise multiplication, and when to use matrix multiplication is clearly stated (matrix multiplication is denoted as @, as this is the shorthand for Numpy.dot. You will see it in action in the code section below), as well as when you need to transpose a matrix. The diagram and following code, assumes a squared loss function. Its derivative is defined as output - labels.</p><h4>3. Weight update</h4><p>All that’s left is to update our weights by adding ∆w to each weight matrix. Notice that we only perform the updates once we finished backpropagating.</p><h3>Code</h3><p>A few notes about this section:</p><ol><li>For readability purposes, the code presented here is pseudocode.</li><li>As this post is meant to be used as a practical guide, I encourage you to go over the diagrams and try to write your <strong>own</strong> implementation <strong>before</strong> looking at the code example. The diagrams have all the information you will need to successfully build it yourself. Look at the diagrams and see how the gradient is passed from one layer to the next. Make sure you understand what is multiplied by what, and what axes are summed over. See how we obtain a ∆W matrix in the shape fitting our layer’s weights in each iteration.</li><li>There are plenty of solutions online. This <a href="https://iamtrask.github.io/2015/07/12/basic-python-network/">one</a> I highly recommend as it is very simple to understand. My own implementation was largely based on it.</li><li>The code assumes using the sigmoid activation function. Due to the fact that the derivative of the sigmoid function (σ(z) *(1-σ(z))) requires only the <em>O</em> values (which are of course σ(z)<em>)</em>, we don&#39;t need the neuron&#39;s values before activation (<em>Z</em>). For implementation using different activation functions, you will need to save the <em>Z</em> values when doing a forward pass.</li></ol><h4>Using a loop</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbfd9775475186a4d4d4adf7158d886f/href">https://medium.com/media/bbfd9775475186a4d4d4adf7158d886f/href</a></iframe><h4>Using recursion</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1827eca94b21cd051c46456d2bd215a/href">https://medium.com/media/d1827eca94b21cd051c46456d2bd215a/href</a></iframe><h3>Adding a bias unit</h3><p>You may have noticed the previous diagrams were missing the bias units. I chose to leave out the bias from these diagrams as I wanted to keep them as simple and intuitive as possible , but you should definitely consider adding it!<br>You can add a bias “manually” for each layer, and then calculate the derivative of the loss in respect to that bias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*ZaEcaXt9D16CJ0tPt4yuVA.png" /></figure><p>We already know how to calculate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/39/1*zczgCjNGP25aT4jpKQvIxA.png" /></figure><p>, and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/54/1*v8qM0LBr8Dg9neIe-bkDJA.png" /></figure><p>is just the activation function derivative of the current layer.</p><p>You could also add the bias to the weights matrix. This basically just means appending a vector of bias neurons (a vector of 1’s) to each layer, and initialize the weight matrices shape accordingly (just like you do in simple linear regression). The one thing to keep in mind though, is that the bias units themselves should never be updated in the forward pass, as they are connected to the neurons of the <strong>next</strong> layer, but NOT to the neurons of the <strong>previous</strong> layer (See diagram).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*9oE40gugpQELmTZ9hoEwaA.png" /></figure><p>One way you can approach this is to avoid updating these neurons, but this can get tricky, especially in the backward pass (Full disclosure, this is what I did, and I don’t recommend it…). A simpler solution is to do the forward and backward pass normally, but re-initialize the bias neurons to 1 after each layer update.</p><h3>Some useful tips</h3><ul><li>Do <strong>NOT</strong> update the weights while back-propagating!! Remember that the next iteration (the previous layer) will need these (non-updated) weights to compute the loss. You can either save the ∆w’s, and update the weights at the end of the backpropagation part (like I’m doing in the code examples), or constantly update the weights two layers ahead, which in my opinion, is confusing, and overly complicated.</li><li>If a layer is not activated by a nonlinear function (for example the output layer), the gradient is just 1.</li><li>The fact that your program doesn’t crash, doesn’t mean that it works. Make sure your network converges, and that the loss decreases.</li><li>The fact that your network converges and your loss decreases, doesn’t mean it’s working optimally. compare your results to other implementations. play around with the learning rate, and the structure of the network.</li><li>Try different initialization methods for the weights. This can have a <strong>huge</strong> effect on performance.</li></ul><h3>Summary</h3><p>Backpropagation can be a tough nut to crack, but if you wish to have a good understanding of how neural networks work, you should avoid jumping into higher level solutions such as <a href="https://www.tensorflow.org/">TensorFlow</a> or <a href="https://pytorch.org/">Pytorch</a> before implementing a simple network yourself. This is the basis for all deep learning and is <a href="https://medium.com/@karpathy/yes-you-should-understand-backprop-e2f06eab496b">crucial</a> for successfully working with more complicated networks. It’s also fun (when it works).</p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=936a2cbebed7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/backpropagation-for-people-who-are-afraid-of-math-936a2cbebed7">Backpropagation for people who are afraid of math</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performing multidimensional matrix operations using numpy’s broadcasting]]></title>
            <link>https://medium.com/data-science/performing-multidimensional-matrix-operations-using-numpys-broadcasting-cf33e3029170?source=rss-5557dfb2d00f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf33e3029170</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Michael Chein]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 22:04:41 GMT</pubDate>
            <atom:updated>2019-02-16T10:42:34.093Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performing multidimensional matrix operations using Numpy’s broadcasting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTSHRZoGHt56gmcmb7cLPQ.jpeg" /><figcaption>Tensor manipulation…</figcaption></figure><p>Numpy’s <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html">broadcasting</a> feature can be somewhat confusing for new users of this library, but as it allows for very clean, elegant and FUN coding. It is definitely worth the effort of getting used to. In this short article, I wanted to show a nice implementation of broadcasting to save some for loops and even computation time.</p><p>Let’s start with a simple case.</p><p>The basic concept is that when adding or multiplying two vectors of sizes <em>(m,1)</em> and <em>(1,m)</em>, numpy will broadcast (duplicate the vector) so that it allows the calculation. For example multiplying a vector <em>[1,2,3,4,…10]</em> with a transposed version of itself, will yield the multiplication table. For Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQ_oRvxidBm-84Bjqv3TEQ.png" /><figcaption>Broadcasting a vector into a matrix. A miniature multiplication table.</figcaption></figure><p>In this example, we multiply a one-dimensional vector (V) of size <em>(3,1)</em> and the transposed version of it, which is of size <em>(1,3)</em>, and get back a <em>(3,3)</em> matrix, which is the <a href="https://en.wikipedia.org/wiki/Outer_product">outer product</a> of V.</p><p>If you still find this confusing, the next illustration breaks down the process into 2 steps, making it clearer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9h-BKUsWrMC0gfJJX58jOg.png" /><figcaption>Broadcasting in slow motion.</figcaption></figure><p>You can think of broadcasting as simply duplicating both our vectors into a <em>(3,3)</em> matrix, and then performing element-wise multiplication.</p><p>We have just broadcasted a 1 dimensional array into a 2 dimensional matrix, however, we could use this to broadcast a 2 dimensional array (or matrix) into a 3 dimensional one (tensor). Just imagine that you needed to perform V*V.T for multiple vectors of the same length. You could simply stack them together, and get all the results in one pass.</p><h3>Case study</h3><p>In this case, I am looking to generate a Euclidean distance matrix for the <a href="https://en.wikipedia.org/wiki/Iris_flower_data_set">iris data set</a>. The Euclidean equation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*33ddTk_7IMiDYU015NGFmQ.png" /></figure><p>Obtaining the table could obviously be performed using two nested for loops:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eccb51bfba67011e1f9110e6ea258082/href">https://medium.com/media/eccb51bfba67011e1f9110e6ea258082/href</a></iframe><p>However, it can also be performed using matrix operations (which are both about 100 times faster, and much cooler).</p><p>We take the data set (represented as &#39;A&#39; in the illustration),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*1HgzLIE6ZsG76LTRUi_cAw.png" /><figcaption>A rectangle representing the iris data set, in which case m=150 and n=4.</figcaption></figure><p>create a 3D copy of it, and rotate it to the orientation shown as &#39;B&#39; in the illustration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*ebfF0aIpm9-8Gu3ivbJgEQ.png" /><figcaption>We can use numpy’s rot90 function to rotate a matrix. See code below.</figcaption></figure><p>We then create another copy and rotate it as represented by &#39;C&#39;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*tnig2m1cfCDNSKl3OTNhMw.png" /><figcaption>Copy and rotate again.</figcaption></figure><p>B-C will generate (via broadcasting!) a 3D cube (&#39;D&#39;), sized <em>(m,m,n)</em> which represents the calculation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*JL7edHUM2uw5QD3_gzOQ6g.png" /></figure><p>for each instance (<em>m</em>) and feature (<em>n</em>) of the original dataset vectors (<em>n</em>=4 in the iris data set).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*wzrtP_j9it6dZwEZcJUTeA.png" /><figcaption>Notice that we are summing up the features for all instances at once!</figcaption></figure><p>Then, we simply raise the entire cube to the power of 2, sum the result in the axis representing the features (see illustration above), and square.</p><p>The result is the Distance matrix (&#39;E&#39;)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*0QrwzcNipZo6hFqhEjYmHg.png" /><figcaption>This is the Euclidean distance matrix. It might seems like it only contains the letter ‘E’, but in fact it holds the distance between all instance pairs. Twice. The diagonal is the distance between every instance with itself, and if it’s not equal to zero, then you should double check your code…</figcaption></figure><p>If you got lost in all these matrix somersaults, go back and look at the equation for calculating the Euclidean matrix. All we did was to solve this equation for several vectors simultaneously.</p><h3>code:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/919bf9f9f8ece9910c3701fc308fbfa2/href">https://medium.com/media/919bf9f9f8ece9910c3701fc308fbfa2/href</a></iframe><h3>Summary</h3><p>Broadcasting is a very clean and efficient method whenever performing the same calculation on several instances. As an exercise, I encourage you to try and use broadcasting on 2 3D arrays (let’s say you have <em>n </em>vectors, belonging to <em>k</em> classes). This means you will need to broadcast into the 4th dimension. It is impossible to <a href="https://www.youtube.com/watch?v=N7K5KjOdLD8">imagine</a> of course, but implementing it follows the same logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf33e3029170" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/performing-multidimensional-matrix-operations-using-numpys-broadcasting-cf33e3029170">Performing multidimensional matrix operations using numpy’s broadcasting</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>