<?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 Harsh Panchal on Medium]]></title>
        <description><![CDATA[Stories by Harsh Panchal on Medium]]></description>
        <link>https://medium.com/@harshpanchal874?source=rss-b9416d02a1b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yw6YLWBkjKMxDFH8N183Vg.jpeg</url>
            <title>Stories by Harsh Panchal on Medium</title>
            <link>https://medium.com/@harshpanchal874?source=rss-b9416d02a1b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:25:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshpanchal874/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[Introduction to Reinforcement Learning (RL) in PyTorch]]></title>
            <link>https://medium.com/analytics-vidhya/introduction-to-reinforcement-learning-rl-in-pytorch-c0862989cc0e?source=rss-b9416d02a1b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0862989cc0e</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Harsh Panchal]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 18:28:44 GMT</pubDate>
            <atom:updated>2021-09-06T06:10:03.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YECeOxlko9KoOJNw8RNm3A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ZiQkhI7417A">Alina Grubnyak</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Recap of Supervised Learning</h3><p>So far, we’ve primarily concerned ourselves with supervised learning problems (mostly classification). In supervised learning, we are given some sort of training data consisting of input/output pairs, with the goal being to be able to predict the output given some new inputs after learning the model. For example, we previously looked at a Convolutional Neural Network (CNN) classification model for MNIST; given a training set of 60000 digit images and corresponding digit labels (e.g. ‘5’), we learned a model that was capable of predicting the digit label of new MNIST images. In order words, something like (but not exactly) this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*d3UWG3u5dj0n6ZChEWAojA.png" /><figcaption>Image by author</figcaption></figure><p>What if we want to learn how to perform more complex behaviors, where data collection can be expensive? How do you teach a robot to walk? Self-driving cars? How do you defeat human champions in the game of Go?</p><h3>Reinforcement Learning</h3><p>Enter Reinforcement Learning. In Reinforcement Learning, our model (commonly referred to as an <em>agent</em> in this context) interacts with an <em>environment</em> by taking <em>actions</em> 𝑎a and receives some sort of feedback from the environment in the form of a <em>reward</em> 𝑟. In this sense, reinforcement learning algorithms learn by experience. We call the trajectory of going from start to finish of a task an <em>episode</em>, and often our agent will learn by undergoing many episodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*VdUkjb0pKedLL-Zt1k5KzQ.png" /><figcaption>Image by author</figcaption></figure><p>Many reinforcement learning algorithms are modeled as Markov Decision Processes (MDPs). In these settings, we have a concept of a <em>state</em> 𝑠, which encapsulates the situation of the agent (e.g. location, velocity). From each state 𝑠𝑡, the agent takes an action 𝑎𝑡, which results in a transition from one state 𝑠𝑡 to another 𝑠𝑡+1. In many settings, there is stochasticity in this transition, meaning that there’s is a distribution over 𝑠𝑡+1 conditioned on 𝑠𝑡 and 𝑎𝑡. Often, several of these states are considered episode-ending, after which the agent can no longer make any transitions or collect any more reward. These correspond to states such as reaching the final goal, a game concluding, or falling of a cliff. In the end, our goal is to learn a <em>policy</em> 𝜋 or a mapping from states to actions.</p><p>In an MDP, we assume that we can always tell which state 𝑠𝑡 our agents is in. However, this isn’t always the case. Sometimes, all we have access to are observations 𝑜𝑡 that provide information the state 𝑠𝑡st, but enough to precisely pinpoint the exact one. We call such settings Partially Observable Markov Decision Processes (POMDPs). Imagine for example a <a href="https://en.wikipedia.org/wiki/Roomba">Roomba</a> being trained to navigate a living room with RL. From its infrared and mechanical “bump” sensors, it receives partial information (𝑜𝑡ot) as to where it might be, but not a definitive location (𝑠𝑡). Operating as a POMDP adds a whole layer of complexity to RL algorithms. For the rest of day though, we’ll focus on MDPs, as their much simpler and easier to use to teach basic concepts.</p><h4>A simple MDP example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*FIw75Hr2D1NiqT7JME7Bbg.png" /><figcaption>Image by author</figcaption></figure><p>In the above example, we can see the 3 possible states for the agent as 𝑠0, 𝑠1, and 𝑠2, with 2 actions 𝑎0 and 𝑎1 available from each state. We can see that each action doesn’t lead to a deterministic transition to the next stage, as shown by multiple paths from each action. Note that each of the outcomes of action is labeled with a small black number between 0 and 1. This denotes the probability of that outcome (which state we end up at) given the action; as these are probabilities, the sum of the probabilities of arriving at each of the next states 𝑠𝑡+1 given a previous state 𝑠𝑡st and selected action 𝑎𝑡 is 1.</p><h4>Objective</h4><p>The goal of the agent is to maximize the total reward 𝑅R it can receive over a number of steps. It is important to ensure the reward actually captures the true goal we want the agent to achieve. The agent will dutifully attempt to maximize the objective it is given, without any considerations to any implicit objectives that a human may desire. There are more than a few (amusing) anecdotes of RL agents learning undesirable behaviors by exploiting some aspect of the reward function. As such, defining this reward requires special care.</p><p>One countermeasure commonly deployed by RL researchers is the concept of <em>discounted</em> rewards. This is done with a multiplicative term 𝛾: a reward 𝑇 step in the future is discounted as 𝛾𝑇𝑟𝑇. Using discounting encourages the agent to finish the task sooner rather than later, a common implicit criterion. With discounting then, the RL agent’s goal is to maximize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*1PGyeepqkfWKYMrk2bJM1w.png" /><figcaption>Image by author</figcaption></figure><p>This is far from the complete solution to making our rewards accurately capture our desired objectives, but achieving higher rewards sooner rather than later is an almost universal preference, so we almost always add it. Designing a good reward function can be art is highly dependent on the task.</p><h4>Reinforcement Learning as Supervised Learning?</h4><p>At first, this doesn’t seem too different from the supervised methods we’ve looked at before, and some natural questions might arise:</p><ul><li>Why can’t we just treat RL as a supervised task? Why can’t we use the reward (or rather, the negative of the reward) as our supervised loss?</li></ul><p>Unlike in supervised learning, in reinforcement learning, we often don’t have a pre-apportioned dataset to learn from. In some problems set-ups, we may have examples of other agents (oftentimes humans) performing the desired task, but these aren’t necessarily optimal examples of how to maximize the reward, which is what we want to learn. In most RL settings, we don’t have any examples of state-action trajectories beyond what our agent experiences through trial-and-error, which are even more suboptimal.</p><h3>Open AI Gym</h3><p>Before we dive any deeper into implementing reinforcement learning models, first we need an environment. Remember, the goal is to learn an agent that can interact with an environment in the way we want, so we need something that our agent can interact with and receive rewards from. In robotics, this is often the real world (or some set-up in the real world). However, it is oftentimes cheaper and quicker to first test our algorithms in simulated settings. There are a number of tasks that are popular benchmarks for the reinforcement learning community, such as <a href="https://en.wikipedia.org/wiki/Inverted_pendulum">cart pole</a>, <a href="https://en.wikipedia.org/wiki/Mountain_car_problem">mountain car</a>, or <a href="https://gym.openai.com/envs/#atari">Atari 2600 games</a>. In the spirit of accelerating progress and promoting openness in the research community, Open AI has very nicely coded up <a href="https://gym.openai.com/">Open AI Gym</a>, which has implementations of many of these environments for public use. We will be using these environments, as it allows us to focus on the algorithms themselves, instead of worrying about implementing each problem setting ourselves.</p><p>To use it, we first need to download and install it. Make sure you’re in your PyTorch environment first!</p><pre><em># If you environment isn&#39;t currently active, activate it:</em><br><em># conda activate pytorch</em></pre><pre>pip install gym</pre><p>Once it’s installed, we can import it like any other Python module:</p><pre>import gym</pre><h3>FrozenLake (a Grid World)</h3><p>Let’s start with a simple environment: FrozenLake. Here’s the official description from OpenAI gym:</p><blockquote>Winter is here. You and your friends were tossing around a frisbee at the park when you made a wild throw that left the frisbee out in the middle of the lake. The water is mostly frozen, but there are a few holes where the ice has melted. If you step into one of those holes, you’ll fall into the freezing water. At this time, there’s an international frisbee shortage, so it’s absolutely imperative that you navigate across the lake and retrieve the disc. However, the ice is slippery, so you won’t always move in the direction you intend.</blockquote><p>A visualization of FrozenLake as a grid world:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*0g7sbpQeHHzxDyU89wuntA.png" /><figcaption>Image by author</figcaption></figure><p>At the start of an episode, we begin in the upper left corner (S). Our goal is to move ourselves to the lower right corner (G), avoiding falling into the holes (H). Icy water is cold.</p><p>In reinforcement learning terms, each of the 16 locations on the grid is a state, and action is attempting to move in one of four directions (left, down, right, up). Each move will result in the agent’s state changing from 𝑠𝑡 to 𝑠𝑡+1 as it changes location unless it attempts to move in the direction of a wall, which results in the agent’s state not changing (the agent doesn’t move). We receive a positive reward of “+1” for reaching the goal (G), discounted according to how long it took. While there is not a negative reward for falling into a hole (H), the agent still pays a penalty in the sense that falling into the hole is episode-ending and therefore prevents it from receiving any reward. We want to learn a policy 𝜋 that takes us from our starting location (S) to the goal (G) in as few steps as possible.</p><p>To really establish what we are trying to accomplish here, it’s worth debunking a few common initial misconceptions:</p><ul><li><strong>Knowledge of the states and transition probabilities:</strong> From the top-down view, your first thought might be to plot out a path from the start to the finish, just as you would with a maze. However, this view is provided to us the algorithm designers so we can visualize the problem at hand. The agent learning the task does <em>not</em> get this prior knowledge; all we are about to tell it is that there are going to be 16 states and 4 possible actions from each state. A more proper analogy would be if I blindfolded you and dropped you in the middle of a frozen lake, and told you your state (location) every time you decided to take a step in one of four directions, then set off fireworks when you stepped on the frisbee.</li><li><strong>Knowledge of the goal (reward):</strong> In OpenAI’s official description of the environment, you (the agent) know what you’re hoping to accomplish: You want to retrieve the frisbee while avoiding falling through the ice. The agent does <em>not</em> know this. Rather, it learns the goal by experiencing rewards (or penalties), and the algorithm updates its policy such that it will be more (or less) likely to do those actions again. Note that this means that if an agent never experiences certain rewards, it won’t know they exist.</li><li><strong>Prior knowledge of pathfinding, physics, etc.:</strong> As a human, even if you haven’t solved this task before, you still bring a tremendous amount of prior knowledge to this problem. For example, you know the shortest path to a destination is a line. You know that North, South, East, and West, are directions and that going North and then South brings you back to where you already were. You know ice is slippery. You know icy water is cold. You know being in icy cold water is bad. It’s important to keep in mind that our agent will begin knowing none of these things; its initial policy is essentially picking actions completely at random. By the end of the training, it still won’t know what abstract concepts like “North/South,” “cold,” or “slippery” mean, but it will have (hopefully) learned a good policy that allows it to complete the goal.</li></ul><h4>Interacting with FrozenLake</h4><p>This example is simple enough that we could code the environment and its interface ourselves fairly easily, but OpenAI has already done it, and we’d like to focus on the algorithm of solving it as much as possible. We can create an instantiation of FrozenLake in a single line of code:</p><p>In [ ]:</p><pre>env <strong>=</strong> gym.make(&#39;FrozenLake-v0&#39;)</pre><p>Open AI Gym environments provide a mechanism to observe the state of the environment, and since FrozenLake is an MDP (as opposed to POMDP), the observation is the state itself. For FrozenLake, there are 16 grid locations on the map, meaning we have 16 states. We can confirm this by looking at the size of the observation_space attribute for the environment we just created.</p><p>In [ ]:</p><pre>env.observation_space</pre><p>Our agent will interact with this environment causing its state to change. For FrozenLake, we have 4 options, each corresponding to attempting to step in a particular direction: [Left, Down, Right, Up]. We can confirm this by looking at the size of action_space of our environment.</p><p>In [ ]:</p><pre>env.action_space</pre><p>Before interacting with the environment, we have to first reset it to initialize it. Resetting also returns an observation of the first state after reset. In FrozenLake, we always start in the upper left corner, which corresponds to state 0. As such, we see the reset() command returning 0.</p><p>In [ ]:</p><pre>env.reset()</pre><p>We can visualize the FrozenLake environment by calling render(). In more complex tasks this will actually add frames to a video showing our agent&#39;s progress, but for FrozenLake, it just prints out a text representation, with the highlighted character showing our agent&#39;s current location. We can see that we started in the upper-left corner, on the &quot;S,&quot; as promised.</p><p>In [ ]:</p><pre>env.render()</pre><p>Now, let’s try moving. One thing to keep in mind is that the original FrozenLake environment is “slippery.” Because of the ice, if you try to go in one direction, you end up with a 1/3 chance of going in the direction you meant and the two adjacent directions each. For example, if we try going right, we have equal probabilities of slipping and going up and down instead. This makes things a little more complicated, so for now, let’s first turn off the stochasticity and make this a deterministic transition instead. We do this by registering a new type of environment, and then instantiating a copy of the said environment, making sure to reset it first.</p><p>In [ ]:</p><pre># Non-slippery version</pre><pre>from gym.envs.registration import register<br>register(<br>    id=&#39;FrozenLakeNotSlippery-v0&#39;,<br>    entry_point=&#39;gym.envs.toy_text:FrozenLakeEnv&#39;,<br>    kwargs={&#39;map_name&#39; : &#39;4x4&#39;, &#39;is_slippery&#39;: False},<br>)<br>env = gym.make(&#39;FrozenLakeNotSlippery-v0&#39;)<br>env.reset()</pre><p>We advance time in an OpenAI environment with the step() method, which takes as argument an action. Let&#39;s trying moving right, which corresponds to the action 2. Notice that the output is a tuple of four elements: the next observation (object), the reward (float), whether or not the episode is done (boolean), and a dictionary of information (dict) that may be useful for debugging (this dict shouldn&#39;t be used in the final algorithm itself).</p><p>In [ ]:</p><pre>env.step(2)</pre><p>Next, let’s render() to visualize what happened. Observe that this particular environment prints out the action we took in parentheses up top, in this case &quot;(Right)&quot;, and then shows the result of that action. Notice that while most of the time, we succeed in going in the direction we want to, occasionally we slip on the ice and go in a direction we didn&#39;t intend.</p><p>In [ ]:</p><pre>env.render()</pre><p>We can keep doing this as many times as we want. Since we’re in Jupyter, we can just keep running the same cell (making small edits to change our action).</p><p>Notice that once we fall into a hole, the episode is over, and we can no longer do anything. The same is true after reaching the goal.</p><p>In [ ]:</p><pre>env.step(0)<br>env.render()</pre><p>Before we get into any RL, let’s see how random actions perform in this environment:</p><p>In [ ]:</p><pre>env.reset()<br>done = False</pre><pre>while not done:<br>    env.render()<br>    action = env.action_space.sample()<br>    _, _, done, _ = env.step(action)</pre><p>Hm. Not great. Alright, so clearly picking random steps isn’t very likely to take us to the goal. It’s apparent just from looking at the map that there’re much better policies that we can learn. How are we going to do so?</p><h4>Q-learning</h4><p>There are many algorithms that we can use, but let’s choose Q-learning, which we covered earlier today. Remember, in Q-learning (and SARSA, it turns out), we’re trying to learn the Q values for the states in our system.</p><p>The Q value for a policy 𝜋 is a function of the state 𝑠s and action 𝑎a and is defined as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*lWQrngK5iBxLpkzLSL9zcQ.png" /><figcaption>Image by author</figcaption></figure><p>Intuitively, the Q value is the total reward (including discounting) that the agent will gain if it takes action 𝑎a from state 𝑠 and then follows policy 𝜋 for the rest of the episode. As one might expect, if Q is known exactly, the agent will attain the highest reward from 𝑠s if the policy 𝜋 is to pick the 𝑎a with the highest Q value.</p><p>Okay, so if we know the Q values for the system, then we can trivially find the optimal policy. So what are the Q values of the system? Well, in the beginning, we don’t know, but we can try to learn them through experience. This is where Q-learning comes in. Q-learning iteratively updates the Q values in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*hqspje0MZkSIyrDylp0YQA.png" /><figcaption>Image by author</figcaption></figure><p>Notice that Q-learning is an <em>off-policy</em> method, in the sense that you don’t actually learn from the trajectory you actually took (otherwise it’d be SARSA). Instead, we learn from the <em>greedy</em> transition, i.e. the best action we know how to take.</p><p>And that’s it! We run our agent through many episodes, experiencing many 𝑠𝑡→𝑎𝑡→𝑠𝑡+1 transitions and rewards, and just like that, we eventually learn a good Q function (and thus a good policy). Now, of course, there are a bunch of small details and tweaks to make this work in practice, but we’ll get to those later.</p><h4>Q-learning in FrozenLake</h4><p>FrozenLake is a very simple setting, one that we would call a toy problem. With only 16 states and 4 actions, there are only 64 state-action pairs possible (16x4=64), less if we account for the goal and the holes being episode ending (for simplicity though, we won’t). With these few state-action pairs, we can actually solve this problem tabularly. Let’s set up a Q table, and initialize the Q-values for all state-action pairs to zeros. Note that while we could, we’re actually not going to need PyTorch in this example; PyTorch’s autograd and neural network libraries are unnecessary here, as we’re only going to be modifying a table of numbers. Instead, we’ll use a Numpy array to store the Q table.</p><p>In [ ]:</p><pre>import numpy as np</pre><pre>#Initialize table with all zeros to be uniform<br>Q = np.zeros([env.observation_space.n, env.action_space.n])</pre><p>A few hyperparameters we’re going to set:</p><ul><li>alpha: learning rate for the Q function</li><li>gamma: discount rate for future rewards</li><li>num_episodes: number of episodes (trajectories from start to goal/hole) our agent will learn from</li></ul><p>We’re also going to store our rewards in an array called rs.</p><p>In [ ]:</p><pre># Learning parameters<br>alpha = 0.1<br>gamma = 0.95<br>num_episodes = 2000</pre><pre># array of reward for each episode<br>rs = np.zeros([num_episodes])</pre><p>Now for the bulk of the algorithm itself. Notice that we’re going to loop through the process num_episodes times, resetting the environment each time. At each step, we take the action with the highest Q value for our current state, with some randomness added in (especially at the beginning) to encourage exploration. After each action, we update our Q table greedily based on the reward experienced and the next best action. We also make sure to update our state, rinse, and repeat. We continue taking actions in an episode until it is, storing the final total reward for the episode.</p><p>In [ ]:</p><pre>for i in range(num_episodes):<br>    # Set total reward and time to zero, done to False<br>    r_sum_i = 0<br>    t = 0<br>    done = False<br>    <br>    #Reset environment and get first new observation<br>    s = env.reset()<br>    <br>    while not done:<br>        # Choose an action by greedily (with noise) from Q table<br>        a = np.argmax(Q[s,:] + np.random.randn(1, env.action_space.n)*(1./(i/10+1)))<br>        <br>        # Get new state and reward from environment<br>        s1, r, done, _ = env.step(a)<br>        <br>        # Update Q-Table with new knowledge<br>        Q[s,a] = (1 - alpha)*Q[s,a] + alpha*(r + gamma*np.max(Q[s1,:]))<br>        <br>        # Add reward to episode total<br>        r_sum_i += r*gamma**t<br>        <br>        # Update state and time<br>        s = s1<br>        t += 1<br>    rs[i] = r_sum_i</pre><p>How did we do? Let’s take a look at the rewards that we saved. We can plot the reward versus the episode number, and hopefully, we’ll see some sort of an increase over time. RL performance can be extremely noisy, so let’s instead plot a moving average.</p><p>In [ ]:</p><pre>## Plot reward vs episodes<br>import matplotlib.pyplot as plt</pre><pre># Sliding window average<br>r_cumsum = np.cumsum(np.insert(rs, 0, 0)) <br>r_cumsum = (r_cumsum[50:] - r_cumsum[:-50]) / 50</pre><pre># Plot<br>plt.plot(r_cumsum)<br>plt.show()</pre><p>Pretty good. We might also be interested in how often our agent actually reached the goal. This won’t account for how quickly the agent got there (which might also be of interest), but let’s ignore that for now. To prevent us from being overwhelmed by data points, let’s bucket the values into 10 stages, printing out how many episodes of each stage resulted in finding the goal.</p><p>In [ ]:</p><pre># Print number of times the goal was reached<br>N = len(rs)//10<br>num_Gs = np.zeros(10)</pre><pre>for i in range(10):<br>    num_Gs[i] = np.sum(rs[i*N:(i+1)*N] &gt; 0)<br>    <br>print(&quot;Rewards: {0}&quot;.format(num_Gs))</pre><p>Our RL agent does a really good job at navigating the FrozenLake when its moves are deterministic, but after all, this is supposed to be <em>Frozen</em>Lake, so where’s the fun without the slipperiness? Let’s go back to the original environment and see how the agent does.</p><p>In [ ]:</p><pre>env = gym.make(&#39;FrozenLake-v0&#39;)</pre><pre>#Initialize table with all zeros to be uniform<br>Q = np.zeros([env.observation_space.n, env.action_space.n])</pre><pre># Learning parameters<br>alpha = 0.1<br>gamma = 0.95<br>num_episodes = 2000</pre><pre># array of reward for each episode<br>rs = np.zeros([num_episodes])</pre><pre>for i in range(num_episodes):<br>    # Set total reward and time to zero, done to False<br>    r_sum_i = 0<br>    t = 0<br>    done = False<br>    <br>    #Reset environment and get first new observation<br>    s = env.reset()<br>    <br>    while not done:<br>        # Choose an action by greedily (with noise) from Q table<br>        a = np.argmax(Q[s,:] + np.random.randn(1, env.action_space.n)*(1./(i/10+1)))<br>        <br>        # Get new state and reward from environment<br>        s1, r, done, _ = env.step(a)<br>        <br>        # Update Q-Table with new knowledge<br>        Q[s,a] = (1 - alpha)*Q[s,a] + alpha*(r + gamma*np.max(Q[s1,:]))<br>        <br>        # Add reward to episode total<br>        r_sum_i += r*gamma**t<br>        <br>        # Update state and time<br>        s = s1<br>        t += 1<br>    rs[i] = r_sum_i</pre><pre>## Plot reward vs episodes<br># Sliding window average<br>r_cumsum = np.cumsum(np.insert(rs, 0, 0)) <br>r_cumsum = (r_cumsum[50:] - r_cumsum[:-50]) / 50</pre><pre># Plot<br>plt.plot(r_cumsum)<br>plt.show()</pre><pre># Print number of times the goal was reached<br>N = len(rs)//10<br>num_Gs = np.zeros(10)</pre><pre>for i in range(10):<br>    num_Gs[i] = np.sum(rs[i*N:(i+1)*N] &gt; 0)<br>    <br>print(&quot;Rewards: {0}&quot;.format(num_Gs))</pre><p>Much harder. However, we can see that the model does eventually learn something.</p><h3>PyTorch in RL</h3><p>Hey, not bad. However, while the previous example was fun and simple, it was noticeably lacking any hint of PyTorch.</p><p>We could have used a PyTorch Tensor to store the Q table, but that&#39;s not any better than using a NumPy array. PyTorch&#39;s true utility comes from building neural networks and calculating/applying gradients automatically, which learning the Q table didn&#39;t need.</p><h4>Continuous domains</h4><p>In our previous example, we mentioned that with only 16 discrete states and 4 actions/states, the Q table only needed to hold 64 values, which is very manageable. However, what if the state or action space is continuous? You could discretize it, but then you have to pick a resolution, and your state-action space could explode exponentially. Treating these binned states or actions as completely different states is also ignoring that two consecutive bins are likely very similar in the needed policy. You can learn these relationships, but doing so is horribly sample inefficient.</p><p>Instead of learning a Q table then, perhaps a Q function would be more appropriate. This function would take in a state and action as an input and return a Q value as an output. The Q function may be very complex, but as we’ve learned over the past few days, neural networks are very flexible and good for approximating arbitrary functions. <a href="https://deepmind.com/research/dqn/">Deep Q Networks</a> take such an approach.</p><h3>Cart Pole</h3><p>Let’s look at the cart pole problem next. In this setting, we have a pole attached to a hinge on a cart, with the goal being to keep the pole vertical as long as possible, without traveling too far along the rail. Because of gravity, the pole will fall unless the cart is exactly beneath the pole’s center of gravity. To prevent the pole from falling, the agent can apply a force of +1 or -1 to the cart to move it left and right along a track. The agent receives a reward of +1 for every timestamp the pole remains vertical; the game ends when the pole falls past 15 degrees from vertical or the cart moves more than 2.4 units away from the center. We’re going to somewhat arbitrarily call “success” achieving a reward of +200; alternatively, the agent needs to avoid the aforementioned failure conditions for 200 ticks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*-0wDwEC5Gg7JgBoTeDFJFg.png" /><figcaption>Image by author</figcaption></figure><p>First, let’s create an instance of the cart pole environment:</p><p>In [ ]:</p><pre>env <strong>=</strong> gym.make(&#39;CartPole-v0&#39;)</pre><p>Again, we can look at the observation_space for this environment. Also similar to FrozenLake, since this version of the cart pole is an MDP (as opposed to POMDP), the observation is the state itself. We can see that the states for cart pole have 4 dimensions, which correspond to [cart position, cart velocity, pole angle, pole angular velocity]. Importantly, notice these states are <em>continuous</em> values.</p><p>In [ ]:</p><pre>env.observation_space</pre><p>We can look at them action_space again too. In cart pole, there are two actions available to the agent: [apply force left, apply force right]. We can see this by examining the action_space attribute:</p><p>In [ ]:</p><pre>env.action_space</pre><p>Resetting the environment returns our first observations, which we can see has 4 values corresponding to the 4 previously mentioned state variables.</p><p>In [ ]:</p><pre>env.reset()</pre><p>Before we get into any reinforcement learning, let’s see how we perform actions within the environment.</p><p>In [ ]:</p><pre>done = False</pre><pre>while not done:<br>    env.render()<br>    action = env.action_space.sample()<br>    _, _, done, _ = env.step(action)</pre><p>Okay, so clearly choosing a random action at every time step doesn’t really achieve our goal of keeping the pole vertical. We’re going to need something smarter.</p><p>Let’s close that rendering window. We do this with close(). Note that gym renderings can be a little finicky, especially on Windows; either close() or restarting your Jupyter kernel may be necessary to close the rendered window.</p><p>In [ ]:</p><pre>env.close()</pre><p>Cart pole is actually a fairly simple problem (it’s very low dimensional), and so there are simpler ways to do this, but since we’ve been having so much fun with deep learning, let’s use a neural network. Specifically, let’s build a DQN that uses Q-learning to learn how to balance the pole. We’re going to give our DQN agent 1000 episodes to try and reach the goal of 200 ticks.</p><p>There are a lot of small details that go into making these models work well, so instead of going through it piece by piece, the full code:</p><p>In [ ]:</p><pre># Based on: <a href="https://gym.openai.com/evaluations/eval_EIcM1ZBnQW2LBaFN6FY65g/">https://gym.openai.com/evaluations/eval_EIcM1ZBnQW2LBaFN6FY65g/</a></pre><pre>from collections import deque<br>import random<br>import math</pre><pre>import gym<br>import numpy as np<br>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F</pre><pre>class DQN(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.fc1 = nn.Linear(4, 24)<br>        self.fc2 = nn.Linear(24, 48)<br>        self.fc3 = nn.Linear(48, 2)</pre><pre>def forward(self, x):        <br>        x = self.fc1(x)<br>        x = F.relu(x)<br>        x = self.fc2(x)<br>        x = F.relu(x)<br>        x = self.fc3(x)<br>        return x</pre><pre>class DQNCartPoleSolver:<br>    def __init__(self, n_episodes=1000, n_win_ticks=195, max_env_steps=None, gamma=1.0, epsilon=1.0, epsilon_min=0.01, epsilon_log_decay=0.995, alpha=0.01, alpha_decay=0.01, batch_size=64, monitor=False, quiet=False):<br>        self.memory = deque(maxlen=100000)<br>        self.env = gym.make(&#39;CartPole-v0&#39;)<br>        if monitor: self.env = gym.wrappers.Monitor(self.env, &#39;../data/cartpole-1&#39;, force=True)<br>        self.gamma = gamma<br>        self.epsilon = epsilon<br>        self.epsilon_min = epsilon_min<br>        self.epsilon_decay = epsilon_log_decay<br>        self.alpha = alpha<br>        self.alpha_decay = alpha_decay<br>        self.n_episodes = n_episodes<br>        self.n_win_ticks = n_win_ticks<br>        self.batch_size = batch_size<br>        self.quiet = quiet<br>        if max_env_steps is not None: self.env._max_episode_steps = max_env_steps</pre><pre># Init model<br>        self.dqn = DQN()<br>        self.criterion = torch.nn.MSELoss()<br>        self.opt = torch.optim.Adam(self.dqn.parameters(), lr=0.01)</pre><pre>def get_epsilon(self, t):<br>        return max(self.epsilon_min, min(self.epsilon, 1.0 - math.log10((t + 1) * self.epsilon_decay)))</pre><pre>def preprocess_state(self, state):<br>        return torch.tensor(np.reshape(state, [1, 4]), dtype=torch.float32) <br>    <br>    def choose_action(self, state, epsilon):<br>        if (np.random.random() &lt;= epsilon):<br>            return self.env.action_space.sample() <br>        else:<br>            with torch.no_grad():<br>                return torch.argmax(self.dqn(state)).numpy()</pre><pre>def remember(self, state, action, reward, next_state, done):<br>        reward = torch.tensor(reward)<br>        self.memory.append((state, action, reward, next_state, done))<br>    <br>    def replay(self, batch_size):<br>        y_batch, y_target_batch = [], []<br>        minibatch = random.sample(self.memory, min(len(self.memory), batch_size))<br>        for state, action, reward, next_state, done in minibatch:<br>            y = self.dqn(state)<br>            y_target = y.clone().detach()<br>            with torch.no_grad():<br>                y_target[0][action] = reward if done else reward + self.gamma * torch.max(self.dqn(next_state)[0])<br>            y_batch.append(y[0])<br>            y_target_batch.append(y_target[0])<br>        <br>        y_batch = torch.cat(y_batch)<br>        y_target_batch = torch.cat(y_target_batch)<br>        <br>        self.opt.zero_grad()<br>        loss = self.criterion(y_batch, y_target_batch)<br>        loss.backward()<br>        self.opt.step()        <br>        <br>        if self.epsilon &gt; self.epsilon_min:<br>            self.epsilon *= self.epsilon_decay</pre><pre>def run(self):<br>        scores = deque(maxlen=100)</pre><pre>for e in range(self.n_episodes):<br>            state = self.preprocess_state(self.env.reset())<br>            done = False<br>            i = 0<br>            while not done:<br>                if e % 100 == 0 and not self.quiet:<br>                    self.env.render()<br>                action = self.choose_action(state, self.get_epsilon(e))<br>                next_state, reward, done, _ = self.env.step(action)<br>                next_state = self.preprocess_state(next_state)<br>                self.remember(state, action, reward, next_state, done)<br>                state = next_state<br>                i += 1</pre><pre>scores.append(i)<br>            mean_score = np.mean(scores)<br>            if mean_score &gt;= self.n_win_ticks and e &gt;= 100:<br>                if not self.quiet: print(&#39;Ran {} episodes. Solved after {} trials ✔&#39;.format(e, e - 100))<br>                return e - 100<br>            if e % 100 == 0 and not self.quiet:<br>                print(&#39;[Episode {}] - Mean survival time over last 100 episodes was {} ticks.&#39;.format(e, mean_score))</pre><pre>self.replay(self.batch_size)<br>        <br>        if not self.quiet: print(&#39;Did not solve after {} episodes      😞&#39;.format(e))<br>        return e</pre><pre>if __name__ == &#39;__main__&#39;:<br>    agent = DQNCartPoleSolver()<br>    agent.run()<br>    agent.env.close()</pre><p>Reinforcement learning can be kind of noisy. In some sense, it depends on your agent “lucking” into the right behavior so that it can learn from it, and occasionally one can get stuck in a bad rut. Even if your agent fails to “solve” the problem (i.e. reach 200 ticks), you should still see the mean survival time mostly climbing as the agent experiences more episodes. You may need to re-run learning a couple of times for the agent to reach 200 ticks.</p><p>Once you have reached this sentence you have gone through all the steps for introduction to Reinforcement Learning (RL) in PyTorch</p><p>Here is a summary of your accomplishment today:</p><p><strong>1. Supervised learning</strong></p><p><strong>2. Reinforcement Learning</strong></p><p><strong>3. Open AI Gym</strong></p><p><strong>4. FrozenLake (a Grid World)</strong></p><p><strong>5. PyTorch in RL</strong></p><p><strong>6. Cart Pole</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0862989cc0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/introduction-to-reinforcement-learning-rl-in-pytorch-c0862989cc0e">Introduction to Reinforcement Learning (RL) in PyTorch</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Natural Language Processing (NLP) in PyTorch]]></title>
            <link>https://levelup.gitconnected.com/introduction-to-natural-language-processing-nlp-in-pytorch-8b7344c9dfec?source=rss-b9416d02a1b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b7344c9dfec</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Harsh Panchal]]></dc:creator>
            <pubDate>Fri, 23 Jul 2021 17:39:57 GMT</pubDate>
            <atom:updated>2021-07-30T16:56:51.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5Vf07_3j_IfELV2mhiDRg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pietrozj">Pietro Jeng</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Word Embeddings</h3><p>Word embeddings, or word vectors, provide a way of mapping words from a vocabulary into a low-dimensional space, where words with similar meanings are close together. Let’s play around with a set of pre-trained word vectors, to get used to their properties. There exist many sets of pretrained word embeddings; here, we use ConceptNet Numberbatch, which provides a relatively small download in an easy-to-work-with format (h5).</p><pre># Download word vectors<br>from urllib.request import urlretrieve<br>import os<br>if not os.path.isfile(&#39;datasets/mini.h5&#39;):<br>    print(&quot;Downloading Conceptnet Numberbatch word embeddings...&quot;)<br>    conceptnet_url = &#39;<a href="http://conceptnet.s3.amazonaws.com/precomputed-data/2016/numberbatch/17.06/mini.h5&#39;">http://conceptnet.s3.amazonaws.com/precomputed-data/2016/numberbatch/17.06/mini.h5&#39;</a><br>    urlretrieve(conceptnet_url, &#39;datasets/mini.h5&#39;)</pre><p>To read an h5 file, we’ll need to use the h5py package. If you followed the PyTorch installation instructions in 1A, you should have it downloaded already. Otherwise, you can install it with</p><pre><em># If you environment isn&#39;t currently active, activate it:</em><br><em># conda activate pytorch</em></pre><pre>pip install h5py</pre><p>You may need to re-open this notebook for the installation to take effect.</p><p>Below, we use the package to open the mini.h5 file we just downloaded. We extract from the file a list of utf-8-encoded-words, as well as their 300-d vectors.</p><pre># Load the file and pull out words and embeddings<br>import h5py</pre><pre>with h5py.File(&#39;datasets/mini.h5&#39;, &#39;r&#39;) as f:<br>    all_words = [word.decode(&#39;utf-8&#39;) for word in f[&#39;mat&#39;][&#39;axis1&#39;][:]]<br>    all_embeddings = f[&#39;mat&#39;][&#39;block0_values&#39;][:]<br>    <br>print(&quot;all_words dimensions: {}&quot;.format(len(all_words)))<br>print(&quot;all_embeddings dimensions: {}&quot;.format(all_embeddings.shape))</pre><pre>print(&quot;Random example word: {}&quot;.format(all_words[1337]))</pre><p>Now, all_words is a list of 𝑉 strings (what we call our <em>vocabulary</em>), and all_embeddings is a 𝑉×300 matrix. The strings are of the form /c/language_code/word—for example, /c/en/cat and /c/es/gato.</p><p>We are interested only in the English words. We use Python list comprehensions to pull out the indices of the English words, then extract just the English words (stripping the six-character /c/en/ prefix) and their embeddings.</p><pre># Restrict our vocabulary to just the English words<br>english_words = [word[6:] for word in all_words if word.startswith(&#39;/c/en/&#39;)]<br>english_word_indices = [i for i, word in enumerate(all_words) if word.startswith(&#39;/c/en/&#39;)]<br>english_embeddings = all_embeddings[english_word_indices]</pre><pre>print(&quot;Number of English words in all_words: {0}&quot;.format(len(english_words)))<br>print(&quot;english_embeddings dimensions: {0}&quot;.format(english_embeddings.shape))</pre><pre>print(english_words[1337])</pre><p>The magnitude of a word vector is less important than its direction; the magnitude can be thought of as representing the frequency of use, independent of the semantics of the word. Here, we will be interested in semantics, so we <em>normalize</em> our vectors, dividing each by its length. The result is that all of our word vectors are length 1, and as such, lie on a unit circle. The dot product of two vectors is proportional to the cosine of the angle between them, and provides a measure of similarity (the bigger the cosine, the smaller the angle).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*VBY52u4xClPcZ3_cZGfN3Q.png" /><figcaption>Image from author</figcaption></figure><pre>import numpy as np</pre><pre>norms = np.linalg.norm(english_embeddings, axis=1)<br>normalized_embeddings = english_embeddings.astype(&#39;float32&#39;) / norms.astype(&#39;float32&#39;).reshape([-1, 1])</pre><p>We want to look up words easily, so we create a dictionary that maps us from a word to its index in the word embeddings matrix.</p><pre>index = {word: i for i, word in enumerate(english_words)}</pre><p>Now we are ready to measure the similarity between pairs of words. We use NumPy to take dot products.</p><pre>def similarity_score(w1, w2):<br>    score = np.dot(normalized_embeddings[index[w1], :], normalized_embeddings[index[w2], :])<br>    return score</pre><pre># A word is as similar with itself as possible:<br>print(&#39;cat\tcat\t&#39;, similarity_score(&#39;cat&#39;, &#39;cat&#39;))</pre><pre># Closely related words still get high scores:<br>print(&#39;cat\tfeline\t&#39;, similarity_score(&#39;cat&#39;, &#39;feline&#39;))<br>print(&#39;cat\tdog\t&#39;, similarity_score(&#39;cat&#39;, &#39;dog&#39;))</pre><pre># Unrelated words, not so much<br>print(&#39;cat\tmoo\t&#39;, similarity_score(&#39;cat&#39;, &#39;moo&#39;))<br>print(&#39;cat\tfreeze\t&#39;, similarity_score(&#39;cat&#39;, &#39;freeze&#39;))</pre><pre># Antonyms are still considered related, sometimes more so than synonyms<br>print(&#39;antonym\topposite\t&#39;, similarity_score(&#39;antonym&#39;, &#39;opposite&#39;))<br>print(&#39;antonym\tsynonym\t&#39;, similarity_score(&#39;antonym&#39;, &#39;synonym&#39;))</pre><pre>int(&#39;antonym\tsynonym\t&#39;, similarity_score(&#39;antonym&#39;, &#39;synonym&#39;))</pre><p>We can also find, for instance, the most similar words to a given word</p><pre>def closest_to_vector(v, n):<br>    all_scores = np.dot(normalized_embeddings, v)<br>    best_words = list(map(lambda i: english_words[i], reversed(np.argsort(all_scores))))<br>    return best_words[:n]</pre><pre>def most_similar(w, n):<br>    return closest_to_vector(normalized_embeddings[index[w], :], n)</pre><pre>print(most_similar(&#39;cat&#39;, 10))<br>print(most_similar(&#39;dog&#39;, 10))<br>print(most_similar(&#39;duke&#39;, 10))</pre><p>We can also use closest_to_vector to find words &quot;nearby&quot; vectors that we create ourselves. This allows us to solve analogies. For example, in order to solve the analogy &quot;man : brother :: woman : ?&quot;, we can compute a new vector brother - man + woman: the meaning of brother, minus the meaning of man, plus the meaning of woman. We can then ask which words are closest, in the embedding space, to that new vector.</p><pre>def solve_analogy(a1, b1, a2):<br>    b2 = normalized_embeddings[index[b1], :] - normalized_embeddings[index[a1], :] + normalized_embeddings[index[a2], :]<br>    return closest_to_vector(b2, 1)</pre><pre>print(solve_analogy(&quot;man&quot;, &quot;brother&quot;, &quot;woman&quot;))<br>print(solve_analogy(&quot;man&quot;, &quot;husband&quot;, &quot;woman&quot;))<br>print(solve_analogy(&quot;spain&quot;, &quot;madrid&quot;, &quot;france&quot;))</pre><p>These three results are quite good, but in general, the results of these analogies can be disappointing. Try experimenting with other analogies, and see if you can think of ways to get around the problems you notice (i.e., modifications to the solve_analogy() algorithm).</p><h3>Using word embeddings in deep models</h3><p>Word embeddings are fun to play around with, but their primary use is that they allow us to think of words as existing in a continuous, Euclidean space; we can then use an existing arsenal of techniques for machine learning with continuous numerical data (like logistic regression or neural networks) to process text. Let’s take a look at an especially simple version of this. We’ll perform <em>sentiment analysis</em> on a set of movie reviews: in particular, we will attempt to classify a movie review as positive or negative based on its text.</p><p>We will use a <a href="http://people.ee.duke.edu/~lcarin/acl2018_swem.pdf">Simple Word Embedding Model</a> (SWEM, Shen, et al. 2018) to do so. We will represent a review as the <em>mean</em> of the embeddings of the words in the review. Then we’ll train a two-layer MLP (a neural network) to classify the review as positive or negative. As you might guess, using just the mean of the embeddings discards a lot of the information in a sentence, but for tasks like sentiment analysis, it can be surprisingly effective.</p><p>If you don’t have it already, download the movie-simple.txt file. Each line of that file contains</p><ol><li>the numeral 0 (for negative) or the numeral 1 (for positive), followed by</li><li>a tab (the whitespace character), and then</li><li>the review itself.</li></ol><p>Let’s first read the data file, parsing each line into an input representation and its corresponding label. Again, since we’re using SWEM, we’re going to take the mean of the word embeddings for all the words as our input.</p><pre>import string<br>remove_punct=str.maketrans(&#39;&#39;,&#39;&#39;,string.punctuation)</pre><pre># This function converts a line of our data file into<br># a tuple (x, y), where x is 300-dimensional representation<br># of the words in a review, and y is its label.<br>def convert_line_to_example(line):<br>    # Pull out the first character: that&#39;s our label (0 or 1)<br>    y = int(line[0])<br>    <br>    # Split the line into words using Python&#39;s split() function<br>    words = line[2:].translate(remove_punct).lower().split()<br>    <br>    # Look up the embeddings of each word, ignoring words not<br>    # in our pretrained vocabulary.<br>    embeddings = [normalized_embeddings[index[w]] for w in words<br>                  if w in index]<br>    <br>    # Take the mean of the embeddings<br>    x = np.mean(np.vstack(embeddings), axis=0)<br>    return x, y</pre><pre># Apply the function to each line in the file.<br>xs = []<br>ys = []<br>with open(&quot;datasets/movie-simple.txt&quot;, &quot;r&quot;, encoding=&#39;utf-8&#39;, errors=&#39;ignore&#39;) as f:<br>    for l in f.readlines():<br>        x, y = convert_line_to_example(l)<br>        xs.append(x)<br>        ys.append(y)</pre><pre># Concatenate all examples into a numpy array<br>xs = np.vstack(xs)<br>ys = np.vstack(ys)</pre><pre>print(&quot;Shape of inputs: {}&quot;.format(xs.shape))<br>print(&quot;Shape of labels: {}&quot;.format(ys.shape))</pre><pre>num_examples = xs.shape[0]</pre><p>Notice that with this setup, our input words have been converted to vectors as part of our preprocessing. This essentially locks our word embeddings in place throughout training, as opposed to learning the word embeddings. Learning word embeddings, either from scratch or fine-tuned from some pre-trained initialization, is often desirable, as it specializes them for the specific task. However, because our data set is relatively small and our computation budget for this demo, we’re going to forgo learning the word embeddings for this model. We’ll revisit this in a bit.</p><p>Now that we’ve parsed the data, let’s save 20% of the data (rounded to a whole number) for testing, using the rest for training. The file we loaded had all the negative reviews first, followed by all the positive reviews, so we need to shuffle it before we split it into the train and test splits. We’ll then convert the data into PyTorch Tensors so we can feed them into our model.</p><pre>print(&quot;First 20 labels before shuffling: {0}&quot;.format(ys[:20, 0]))</pre><pre>shuffle_idx = np.random.permutation(num_examples)<br>xs = xs[shuffle_idx, :]<br>ys = ys[shuffle_idx, :]</pre><pre>print(&quot;First 20 labels after shuffling: {0}&quot;.format(ys[:20, 0]))</pre><pre>import torch</pre><pre>num_train = 4*num_examples // 5</pre><pre>x_train = torch.tensor(xs[:num_train])<br>y_train = torch.tensor(ys[:num_train], dtype=torch.float32)</pre><pre>x_test = torch.tensor(xs[num_train:])<br>y_test = torch.tensor(ys[num_train:], dtype=torch.float32)</pre><p>We could format each batch individually as we feed it into the model, but to make it easier on ourselves, let’s create a TensorDataset and DataLoader as we’ve used in the past for MNIST.</p><pre>reviews_train = torch.utils.data.TensorDataset(x_train, y_train)<br>reviews_test = torch.utils.data.TensorDataset(x_test, y_test)</pre><pre>train_loader = torch.utils.data.DataLoader(reviews_train, batch_size=100, shuffle=True)<br>test_loader = torch.utils.data.DataLoader(reviews_test, batch_size=100, shuffle=False)</pre><p>Time to build our model in PyTorch.</p><pre>import torch.nn as nn<br>import torch.nn.functional as F</pre><p>First, we build the model, organized as a nn.Module. We could make the number of outputs for our MLP the number of classes for this dataset (i.e. 2). However, since we only have two output classes here (&quot;positive&quot; vs &quot;negative&quot;), we can instead produce a single output value, calling everything greater than 00 &quot;positive&quot; and everything less than 00 &quot;negative&quot;. If we pass this output through a sigmoid operation, then values are mapped to [0,1][0,1], with 0.50.5 being the classification threshold.</p><pre>class SWEM(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.fc1 = nn.Linear(300, 64)<br>        self.fc2 = nn.Linear(64, 1)</pre><pre>def forward(self, x):<br>        x = self.fc1(x)<br>        x = F.relu(x)<br>        x = self.fc2(x)<br>        return x</pre><p>To train the model, we instantiate the model. Notice that since we are only doing binary classification, we use the binary cross-entropy (BCE) loss instead of the cross-entropy loss we’ve seen before. We use the “with logits” version for numerical stability.</p><pre>## Training<br># Instantiate model<br>model = SWEM()</pre><pre># Binary cross-entropy (BCE) Loss and Adam Optimizer<br>criterion = nn.BCEWithLogitsLoss()<br>optimizer = torch.optim.Adam(model.parameters(), lr=0.001)</pre><pre># Iterate through train set minibatchs <br>for epoch in range(250):<br>    correct = 0<br>    num_examples = 0<br>    for inputs, labels in train_loader:<br>        # Zero out the gradients<br>        optimizer.zero_grad()<br>        <br>        # Forward pass<br>        y = model(inputs)<br>        loss = criterion(y, labels)<br>        <br>        # Backward pass<br>        loss.backward()<br>        optimizer.step()<br>        <br>        predictions = torch.round(torch.sigmoid(y))<br>        correct += torch.sum((predictions == labels).float())<br>        num_examples += len(inputs)<br>    <br>    # Print training progress<br>    if epoch % 25 == 0:<br>        acc = correct/num_examples<br>        print(&quot;Epoch: {0} \t Train Loss: {1} \t Train Acc: {2}&quot;.format(epoch, loss, acc))</pre><pre>## Testing<br>correct = 0<br>num_test = 0</pre><pre>with torch.no_grad():<br>    # Iterate through test set minibatchs <br>    for inputs, labels in test_loader:<br>        # Forward pass<br>        y = model(inputs)<br>        <br>        predictions = torch.round(torch.sigmoid(y))<br>        correct += torch.sum((predictions == labels).float())<br>        num_test += len(inputs)<br>    <br>print(&#39;Test accuracy: {}&#39;.format(correct/num_test))</pre><p>We can now examine what our model has learned, seeing how it responds to word vectors for different words:</p><pre># Check some words<br>words_to_test = [&quot;exciting&quot;, &quot;hated&quot;, &quot;boring&quot;, &quot;loved&quot;]</pre><pre>for word in words_to_test:<br>    x = torch.tensor(normalized_embeddings[index[word]].reshape(1, 300))<br>    print(&quot;Sentiment of the word &#39;{0}&#39;: {1}&quot;.format(word, torch.sigmoid(model(x))))</pre><p>Try some words of your own! You can also try changing up the model and re-training it to see how the results change. Can you modify the architecture to get better performance? Alternatively, can you simplify the model without sacrificing too much accuracy? What if you try to classify the mean embeddings directly?</p><h3>Learning Word Embeddings</h3><p>In the previous example, we used pre-trained word embeddings but didn’t learn them. The word embeddings were part of preprocessing and remained unchanged throughout training. If we have enough data though, we might prefer to learn the word embeddings along with our model. Pre-trained word embeddings are typically trained on large corpora with unsupervised objectives, and are often non-specific. If we have enough data, we may prefer to learn the word embeddings, either from scratch or with fine-tuning, as making them specific to the task may improve performance.</p><p>How do we learn word embeddings? To do so, we need to make them a part of our model, rather than as part of loading the data. In PyTorch, the preferred way to do so is with the nn.Embedding. Like the other nn layers we&#39;ve seen (e.g. nn.Linear), nn.Embedding must be instantiated first. There are two required arguments for instantiation are the number of embeddings (i.e. the vocabulary size 𝑉) and the dimension of word embeddings (300, in our previous example).</p><pre>VOCAB_SIZE = 5000<br>EMBED_DIM = 300</pre><pre>embedding = nn.Embedding(VOCAB_SIZE, EMBED_DIM)</pre><pre>embedding <strong>=</strong> nn.Embedding(VOCAB_SIZE, EMBED_DIM)</pre><p>Under the hood, this creates a word embedding matrix that is 5000×300.</p><pre>embedding.weight.size()</pre><p>Notice that this matrix is basically a 300-dimensional word embedding for each of the 5000 words, stacked on top of each other. Looking up a word embedding in this embedding matrix is simply selecting a specific row of this matrix, corresponding to the word.</p><p>When word embeddings are learned, nn.Embedding look-up is often one of the first operations in a model module. For example, if we were to learn the word embeddings for our previous SWEM model, the model might instead look like this:</p><pre>class SWEMWithEmbeddings(nn.Module):<br>    def __init__(self, vocab_size, embedding_size, hidden_dim, num_outputs):<br>        super().__init__()<br>        self.embedding = nn.Embedding(vocab_size, embedding_size)<br>        self.fc1 = nn.Linear(embedding_size, hidden_dim)<br>        self.fc2 = nn.Linear(hidden_dim, num_outputs)</pre><pre>def forward(self, x):<br>        x = self.embedding(x)<br>        x = torch.mean(x, dim=0)<br>        x = self.fc1(x)<br>        x = F.relu(x)<br>        x = self.fc2(x)<br>        return x</pre><p>Here we’ve abstracted the size of the various layers of the model as constructor arguments, so we need to specify those hyperparameters at initialization.</p><pre>model = SWEMWithEmbeddings(<br>    vocab_size = 5000,<br>    embedding_size = 300, <br>    hidden_dim = 64, <br>    num_outputs = 1,<br>)<br>print(model)</pre><p>Note that by making embedding part of our model, the expected input to the forward() function is now the word tokens for the input sentence, so we would have to modify our data input pipeline as well. We&#39;ll see how this might be done in the next notebook (4B).</p><h3>Recurrent Neural Networks (RNNs)</h3><p>In the context of deep learning, sequential data is commonly modeled with Recurrent Neural Networks (RNNs). As natural language can be viewed as a sequence of words, RNNs are commonly used for NLP. As with the fully connected and convolutional networks we’ve seen before, RNNs use combinations of linear and nonlinear transformations to project the input into higher-level representations, and these representations can be stacked with additional layers.</p><h4>Sentences as sequences</h4><p>The key difference between sequential models and the previous models we’ve seen is the presence of a “time” dimension: words in a sentence (or paragraph, document) have an ordering to them that convey meaning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*iZDuQcxeIUQtvJx4Syz_9A.png" /><figcaption>Image by author</figcaption></figure><p>In the example sequence above, the word “Recurrent” is the 𝑡=1 word, which we denote 𝑤1; similarly, “neural” is 𝑤2, and so on. As the preceding sections have hopefully impressed upon you, it is often more advantageous to model words as embedding vectors 𝑥1,…,𝑥𝑇, rather than one-hot vectors (which tokens 𝑤1,…𝑤𝑇 correspond to), so our first step is often to do an embedding table look-up for each input word. Let’s assume 300-dimensional word embeddings and, for simplicity, a minibatch of size 1.</p><pre>mb = 1<br>x_dim = 300 <br>sentence = [&quot;recurrent&quot;, &quot;neural&quot;, &quot;networks&quot;, &quot;are&quot;, &quot;great&quot;]</pre><pre>xs = []<br>for word in sentence:<br>    xs.append(torch.tensor(normalized_embeddings[index[word]]).view(1, x_dim))<br>    <br>xs = torch.stack(xs, dim=0)<br>print(&quot;xs shape: {}&quot;.format(xs.shape))</pre><p>Notice that we have formatted our inputs as (words×minibatch×embedding dimensionwords×minibatch×embedding dimension). This is the preferred input ordering for PyTorch RNNs.</p><p>Let’s say we want to process this example. In our previous sentiment analysis example, we just took the average embedding across time, treating the input as a “bag-of-words.” For simple problems, this can work surprisingly well, but as you might imagine, the ordering of words in a sentence is often important, and sometimes, we’d like to be able to model this temporal meaning as well. Enter RNNs.</p><h4>Review: Fully connected layer</h4><p>Before we introduce the RNN, let’s first again revisit the fully connected layer that we used in our logistic regression and multilayer perceptron examples, with a few changes in notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*0KyK1A_OEBG1MbIqcxf0Jg.png" /><figcaption>Image by author</figcaption></figure><p>Instead of calling the result of the fully connected layer 𝑦, we’re going to call it ℎ, for the hidden state. The variable 𝑦 is usually reserved for the final layer of the neural network; since logistic regression was a single layer, using 𝑦 was fine. However, if we assume there is more than one layer, it is more common to refer to the intermediate representation as ℎ. Note that we also use 𝑓() to denote a nonlinear activation function. In the past, we’ve seen 𝑓() as a ReLU, but this could also be a 𝜎() or tanh() nonlinearity. Visualized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*C9wZXSrH5nzmv1AWAZaXiQ.png" /><figcaption>Image by author</figcaption></figure><p>The key thing to notice here is that we project the input 𝑥x with a linear transformation (with 𝑊W and 𝑏b), and then apply a nonlinearity to the output, giving us ℎh. During training, our goal is to learn 𝑊W and 𝑏b.</p><h4>A basic RNN</h4><p>Unlike the previous examples we’ve seen using fully connected layers, sequential data have multiple inputs 𝑥1,…,𝑥𝑇, instead of a single 𝑥. We need to adapt our models accordingly for an RNN. While there are several variations, a common basic formulation for an RNN is the Elman RNN, which is as follows*:</p><p>ℎ𝑡=tanh((𝑥𝑡𝑊𝑥+𝑏𝑥)+(ℎ𝑡−1𝑊ℎ+𝑏ℎ))</p><p>where tanh()t is the hyperbolic tangent, a nonlinear activation function. RNNs process words one at a time in sequence (𝑥𝑡), producing a hidden state ℎ𝑡ht at every time step. The first half of the above equation should look familiar; as with the fully connected layer, we are linearly transforming each input 𝑥𝑡, and then applying a nonlinearity. Notice that we apply the same linear transformation (𝑊𝑥, 𝑏𝑥) at every time step. The difference is that we also apply a separate linear transform (𝑊ℎ, 𝑏ℎ) to the previously hidden state ℎ𝑡−1 and add it to our projected input. This feedback is called a <em>recurrent</em> connection.</p><p>These directed cycles in the RNN architecture give them the ability to model temporal dynamics, making them particularly suited for modeling sequences (e.g. text). We can visualize an RNN layer as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*uZVDIHTeizzvyEgaMTCwFg.png" /><figcaption>Image by author</figcaption></figure><p>We can unroll an RNN through time, making the sequential nature of the more obvious:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*uE9luJS3xLAgMfjY07593w.png" /><figcaption>Image by author</figcaption></figure><p>You can think of these recurrent connections as allowing the model to consider previous hidden states of a sequence when calculating the hidden state for the current input.</p><p>*Note: We don’t actually need two separate biases 𝑏𝑥 and 𝑏ℎ, as you can combine both biases into a single learnable parameter 𝑏. However, writing it separately helps make it clear that we’re performing a linear transformation on both 𝑥𝑡 and ℎ𝑡−1. Speaking of combining variables, we can also express the above operation by concatenating 𝑥𝑡xt and ℎ𝑡−1 into a single vector 𝑧𝑡, and then performing a single matrix multiply 𝑧𝑡𝑊𝑧+𝑏, where 𝑊𝑧 is essentially 𝑊𝑥 and 𝑊ℎ concatenated. Indeed this is how many “official” RNNs modules are implemented, as the reduction in the number of separate matrix multiply operations makes it computationally more efficient. These are implementation details though.</p><h4>RNNs in PyTorch</h4><p>How would we implement an RNN in PyTorch? There are quite a few ways, but let’s build the Elman RNN from scratch first, using the input sequence “recurrent neural networks are great”.</p><pre># As always, import PyTorch first<br>import numpy as np<br>import torch</pre><p>In an RNN, we project both the input 𝑥𝑡 and the previously hidden state ℎ𝑡−1 to some hidden dimension, which we’re going to choose to be 128. To perform these operations, we’re going to define some variables we’re going to learn.</p><pre>h_dim = 128</pre><pre># For projecting the input<br>Wx = torch.randn(x_dim, h_dim)/np.sqrt(x_dim)<br>Wx.requires_grad_()<br>bx = torch.zeros(h_dim, requires_grad=True)</pre><pre># For projecting the previous state<br>Wh = torch.randn(h_dim, h_dim)/np.sqrt(h_dim)<br>Wh.requires_grad_()<br>bh = torch.zeros(h_dim, requires_grad=True)</pre><pre>print(Wx.shape, bx.shape, Wh.shape, bh.shape)</pre><p>For convenience, we define a function for one time step of the RNN. This function takes the current input 𝑥𝑡 and previously hidden state ℎ𝑡−1, performs the linear transformations 𝑥𝑊𝑥+𝑏𝑥 and ℎ𝑊ℎ+𝑏ℎ, and then a hyperbolic tangent nonlinearity.</p><pre>def RNN_step(x, h):<br>    h_next = torch.tanh((torch.matmul(x, Wx) + bx) + (torch.matmul(h, Wh) + bh))</pre><pre>return h_next</pre><p>Each step of our RNN is going to require feeding in input (i.e. the word representation) and the previous hidden state (the summary of preceding sequence). Note that at the beginning of a sentence, we don’t have a previous hidden state, so we initialize it to some value, for example, all zeros:</p><pre># Word embedding for first word<br>x1 = xs[0, :, :]</pre><pre># Initialize hidden state to 0<br>h0 = torch.zeros([mb, h_dim])</pre><p>To take the one-time step of the RNN, we call the function we wrote, passing in 𝑥1 and ℎ0. In this case,</p><pre># Forward pass of one RNN step for time step t=1<br>h1 = RNN_step(x1, h0)</pre><pre>print(&quot;Hidden state h1 dimensions: {0}&quot;.format(h1.shape))</pre><p>We can call the RNN_step function again to get the next time step output from our RNN.</p><pre># Word embedding for second word<br>x2 = xs[1, :, :]</pre><pre># Forward pass of one RNN step for time step t=2<br>h2 = RNN_step(x2, h1)</pre><pre>print(&quot;Hidden state h2 dimensions: {0}&quot;.format(h2.shape))</pre><p>We can continue unrolling the RNN as far as we need to. For each step, we feed in the current input (𝑥𝑡) and previous hidden state (ℎ𝑡−1) to get a new output.</p><h4>Using torch.nn</h4><p>In practice, much like fully connected and convolutional layers, we typically don’t implement RNNs from scratch as above, instead of relying on higher-level APIs. PyTorch has RNNs implemented in the torch.nn library.</p><pre>import torch.nn</pre><pre>rnn = nn.RNN(x_dim, h_dim)<br>print(&quot;RNN parameter shapes: {}&quot;.format([p.shape for p in rnn.parameters()]))</pre><p>Note that the RNN created by torch.nn produces parameters of the same dimensions as our from the scratch example above.</p><p>To perform a forward pass with an RNN, we pass the entire input sequence to the forward() function, which returns the hidden states at every time step (hs) and the final hidden state (h_T).</p><pre>hs, h_T = rnn(xs)</pre><pre>print(&quot;Hidden states shape: {}&quot;.format(hs.shape))<br>print(&quot;Final hidden state shape: {}&quot;.format(h_T.shape))</pre><p>What do we do with these hidden states? It depends on the model and task. Just like multilayer perceptrons and convolutional neural networks, RNNs can be stacked in multiple layers as well. In this case, the outputs ℎ1,…,ℎ𝑇 are the sequential inputs to the next layer. If the RNN layer is the final layer, ℎ𝑇 or the mean/max of ℎ1,…,ℎ𝑇 can be used as a summary encoding of the data sequence. What is being predicted can also have an impact on what the RNN outputs are ultimately used for.</p><h4>Gated RNNs</h4><p>While the RNNs we’ve just explored can successfully model simple sequential data, they tend to struggle with longer sequences, with <a href="https://en.wikipedia.org/wiki/Vanishing_gradient_problem">vanishing gradients</a> an especially big problem. A number of RNN variants have been proposed over the years to mitigate this issue and have been shown empirically to be more effective. In particular, Long Short-Term Memory (LSTM) and the Gated Recurrent Unit (GRU) have seen wide use recently in deep learning. We’re not going to go into detail here about what structural differences they have from vanilla RNNs; a fantastic summary can be found <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">here</a>. Note that “RNN” as a name is somewhat overloaded: it can refer to both the basic recurrent model we went over previously or recurrent models in general (including LSTMs and GRUs).</p><p>LSTMs and GRUs layers can be created in much the same way as basic RNN layers. Again, rather than implementing it yourself, it’s recommended to use the torch.nn implementations, although we highly encourage that you peek at the source code so you understand what&#39;s going on under the hood.</p><pre>lstm = nn.LSTM(x_dim, h_dim)<br>print(&quot;LSTM parameters: {}&quot;.format([p.shape for p in lstm.parameters()]))</pre><pre>gru = nn.GRU(x_dim, h_dim)<br>print(&quot;GRU parameters: {}&quot;.format([p.shape for p in gru.parameters()]))</pre><h3>Torchtext</h3><p>Much like PyTorch has <a href="https://pytorch.org/docs/stable/torchvision/index.html">Torchvision</a> for computer vision, PyTorch also has <a href="https://torchtext.readthedocs.io/en/latest/">Torchtext</a> for natural language processing. As with Torchvision, Torchtext has a number of popular NLP benchmark datasets, across a wide range of tasks (e.g. sentiment analysis, language modeling, machine translation). It also has a few pre-trained word embeddings available as well, including the popular Global Vectors for Word Representation (GloVe). If you need to load your own dataset, Torchtext has a number of useful containers that can make the data pipeline easier.</p><p>You’ll need to install TorchText to use it:</p><pre><em># If you environment isn&#39;t currently active, activate it:</em><br><em># conda activate pytorch</em></pre><pre>pip install torchtext</pre><p>Once you have reached this sentence you have gone through all steps for Introduction to Natural Language Processing (NLP) in PyTorch</p><p>Here is a summary of your accomplishment today:</p><ul><li><strong>Word Embeddings</strong></li><li><strong>Using word embeddings in deep models</strong></li><li><strong>Learning Word Embeddings</strong></li><li><strong><em>Recurrent Neural Networks (RNNs): Sentences as sequences, Review: Fully connected layer, A basic RNN, RNNs in PyTorch, Using torch.nn, Gated RNNs,</em></strong></li><li><strong>Torchtext</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b7344c9dfec" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/introduction-to-natural-language-processing-nlp-in-pytorch-8b7344c9dfec">Introduction to Natural Language Processing (NLP) in PyTorch</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning and Its Applications: A Concise Review]]></title>
            <link>https://medium.com/geekculture/machine-learning-and-its-applications-a-concise-review-1c5510d0c23d?source=rss-b9416d02a1b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c5510d0c23d</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Harsh Panchal]]></dc:creator>
            <pubDate>Mon, 05 Jul 2021 18:40:48 GMT</pubDate>
            <atom:updated>2021-07-14T14:21:21.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onpj_KH4XMUUoKHeE6jshw.jpeg" /><figcaption>Image by <a href="https://wallpapercave.com/w/wp3205318">wallpapercave</a></figcaption></figure><p>With the widespread dissemination of information and the proliferation of databases, the question of how to extract data from useful information has become urgent. This article presents the definition of machine learning and its basic structure, as well as a number of machine learning methods such as rote learning, inductive learning, analogy learning, explained learning, learning based on neural networks, and knowledge discovery, among others. This article also introduces the goals of machine learning and identifies the machine learning growth trend.</p><h3>INTRODUCTION</h3><p>Learning has been the most important component of human intelligence and the most basic method of acquiring knowledge. Machine learning is the most basic method for making a machine intelligent. “If a computer can’t learn, it can’t be termed intelligent,” R.Shank once said. Learning is an integrated mental process that involves remembering, thinking, perception, feeling, and other mental functions all of which are intertwined. As a result, researchers from various fields offer a variety of interpretations and points of view based on their respective expertise.</p><h3>MACHINE LEARNING</h3><p>Machine learning is the study of ways to utilize computers to replicate human learning activities, as well as the study of computer self-improvement strategies for acquiring new knowledge and abilities, identifying current knowledge, and continuously improving performance and achievement.</p><p>Machine learning learns quicker than human learning, accumulates more knowledge, and spreads the results of learning more easily. As a result, any advancement made by humans in the field of machine learning would improve the capabilities of computers, having an impact on human society.</p><h3>MACHINE LEARNING’S BASIC MODEL</h3><p>As a starting point, use H Simon’s definition of learning to create the basic model depicted in Fig. 1. The quality of the information provided by the external environment to the system is the most important component in machine learning. The external environment is a collection of outside information that manifests itself in some way, and it reflects outside information sources; Learning is the process of converting external information to knowledge; it takes information from the outside environment first, then converts the information to knowledge and stores it in a repository; Because the environment supplies all types of information for the learning system, the quality of information has a direct impact on whether learning is easy or disorderly, and the repository holds many general principles that govern a part of the implementation activities.</p><p>The second component that influences the design of a learning system is the repository. Knowledge can be expressed in a variety of ways, including eigenvectors, first-order logic statements, production rules, semantic networks and frameworks, and so on. Each of these modes of representation has its own strengths.</p><p>When making a decision, consider four factors: strong expression, ease of inference, ease of modification repository, and ease of expansion of information. The implementation is the process of using the repository’s knowledge to complete a task and then feeding back the information gathered in the course of completing the task to the learning and guiding additional research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*Wby0MbW8J1ykvQvu_NJfGw.png" /><figcaption>Image by author</figcaption></figure><h3>THE MACHINE LEARNING METHODS</h3><h4><strong>Rote Learning</strong></h4><p>Rote learning functions like memory, storing new information, and retrieving it when needed. Calculation and reasoning learning systems do not require users to recall any of their prior knowledge. Knowledge accessibility is more stable and directing in the rote learning system. The system does not necessitate a lot of processing. Because the function takes the values of variables (X1, X2,…, Xn) as input and then calculates and outputs the values of functions (Y1, Y2,…, Yn), rote learning memorizes the simple storage of ((X1, X2,…, Xn), (Y1, Y2,…, Yn). When F(X1, X2,…, Xn) is required, the implementation section simply searches the memory for (Y1, Y2,…, Yn) rather than recalculating it. The following is a learning model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*egem74iqD9HDnn5_t8e6LA.png" /><figcaption>Image by author</figcaption></figure><h4><strong>Inductive Learning</strong></h4><p>Inductive consequence uses inductive approaches to distill general laws of things and summarize general knowledge from sufficient specific examples. It is the result of a chain reaction from the individual to the collective. Inductive learning is a learning method that applies inductive consequence.</p><p>Inductive learning can be separated into two types: learning by example and learning by observation, depending on whether or not it is guided by teachers. The first is learning with a teacher, while the second is learning without a teacher. Figure 3 depicts a learning system model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*hFS5p3c9f7Bbf3atjEzBoQ.png" /><figcaption>Image by author</figcaption></figure><p>The programming process selects the active examples by scanning the space of cases and submitting them to the interpretation process.</p><p>The programming method properly transforms the examples and converts the active examples to a concept of the space of rules, guiding the space of rules search.</p><ol><li><strong>The Learning of Examples</strong></li></ol><p>The learning of examples ends the general concept learning methods by using examples connected to a concept in the environment. Take a group of animals and inform the learning system which one is “Ma” and which one isn’t. When the sample size is large enough, the learning system can complete the conceptual model for “Ma,” allowing it to recognize and distinguish “Ma” from other animals.</p><p><strong>2. The Learning of Observed</strong></p><p>The purpose of observation learning, also known as a descriptive summary, is to discover general descriptions of laws or theories, describe observation sets, and specify the nature of specific objects.</p><h4><strong>Analog Learning</strong></h4><p>The analogy can plainly and succinctly express the similarity between objects. Analogy learning is a method of learning that involves comparing similar objects. Four major processes are involved in analogy learning:</p><p>1) Enter a set of known conditions as well as a set of undetermined conditions.</p><p>2) For each of the two conditions entered, search for the relevant relation between them using a comparable definition, as described in the description.</p><p>3) Using the similar transformation process, translated the concept, characters, procedures, and relationships to a new issue in order to gain new knowledge for solving new difficulties.</p><p>4) Verify the new knowledge received through the analogy of new problems, and store the proper knowledge. The knowledge that cannot be verified is just stored in the repository as referred knowledge.</p><p>The approach of analogous definition and transformation is the cornerstone of analog learning. With the objective of analog learning, the object based on similar definitions changes. If the goal of learning is to gain some new issue attributes, then analog should be based on the relationship between the state of new issues and the state of old problems; if the goal of learning is to solve new problems, then analog should be based on the relationship between the state of new issues and the state of old problems.</p><h4><strong>Explained Learning</strong></h4><p>Explained learning is learning that is dependent on interpretation. Explained learning examines and responds to current instances using information from the field and the concept knowledge is based on, resulting in a cause and effect explanation tree that delegates the process of responding to the instance. It acquires new information through explaining nature, token phenomena, and internal relations, among other things, in the process of obtaining new knowledge. Figure 4 depicts the generalized procedure based on interpretation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*x-L-n5gWyq8Nyl45GiJdHQ.png" /><figcaption>Image by author</figcaption></figure><p>When the system is learning, first determine why training instances are domain knowledge proofs of the goal concept, then expand the proof using operational rules, and finally obtain the universality description of the target concept using general knowledge expression formalization.</p><h4><strong>Neural network-based learning</strong></h4><p>The nature of a neural network is determined by two primary factors: the network’s topology structure, as well as the network’s proper values and work regulations. A network’s major characters can be created by combining the two. The challenge of network value modification is the learning problem of neural networks.</p><p>The value of a neural network can be determined in two ways: one through design calculations, and the other through the analysis of the network using specified criteria. The second method is used by the majority of neural networks to determine the value of their network. Backpropagation arithmetic, Hopfield network, and other well-known network models and learning algorithms are included in the well-known network model and learning algorithm.</p><h4><strong>The Search for Knowledge</strong></h4><p>The repository’s knowledge discovery process is a senior-managed process for identifying effective, unique, potential, helpful, and comprehending models from enormous volumes of data, as depicted in Fig. 5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*p2aJD_AYOBCm6eJAFf6R9g.png" /><figcaption>Image by author</figcaption></figure><p>Data selection is the process of extracting relevant data from a database to meet the demands of users. Data pre-processing prepares data for subsequent processing, verifies data integrity and consistency, analyzes noisy data, uses statistical methods to fill in data gaps, and creates an examined database. Data transformation selects data from a database that has been investigated, with the most common transformation methods being discrimination and clustering analysis. Data mining determines the type of knowledge to be discovered based on the needs of the users, then chooses a knowledge discovery algorithm based on the knowledge, and extracts the knowledge needed by the users from the database. Knowledge evaluation primarily assesses the acquired rules before determining whether or not they should be entered into a basic knowledge database. The process of knowledge discovery can be broken down into three parts. That is, data mining pretreatment, data mining, and data mining posttreatment. Banking, insurance, retail, health care, engineering and manufacturing, scientific research, satellite observation, and entertainment, among other businesses, have all used knowledge discovery successfully. It has been extremely beneficial in people’s scientific decision-making.</p><h3>MACHINE LEARNING IN APPLICATION</h3><p>Machine learning technology has been widely employed in marketing, banking, telecommunications, and network analysis, according to research.</p><p>Machine learning technology is more commonly employed in the field of marketing in the area of task classification and associated tasks; in the field of finance, machine learning technology is more widely used in forecasting tasks; Furthermore, machine learning is used in the field of data mining in conjunction with other applications; typical methods include neural network initialization, evolutionary computation in machine learning research, level classification of machine learning, and machine learning-based on rough set, among others.</p><h3>CONCLUSION</h3><p>The basic model of machine learning, as well as its application in a variety of domains, are discussed in this article. This article also defines machine learning and its basic structure, as well as describing a number of machine learning methods such as rote learning, inductive learning, analogy learning, explained learning, learning based on neural networks, and knowledge discovery, among others. Although basic study results in the application of machine learning have been obtained, the research is still in its early stages, and many challenges need to be investigated and resolved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c5510d0c23d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/machine-learning-and-its-applications-a-concise-review-1c5510d0c23d">Machine Learning and Its Applications: A Concise Review</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Convolutional Neural Networks (CNNs) in PyTorch]]></title>
            <link>https://python.plainenglish.io/introduction-to-convolutional-neural-networks-cnns-in-pytorch-d1a849aaf58c?source=rss-b9416d02a1b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1a849aaf58c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Harsh Panchal]]></dc:creator>
            <pubDate>Mon, 21 Jun 2021 17:24:03 GMT</pubDate>
            <atom:updated>2021-06-27T15:44:51.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QS72VBS3PEU7wBRiMkD1nA.jpeg" /></figure><h3>Representing images digitally</h3><p>While convolutional neural networks (CNNs) see a wide variety of uses, they were originally designed for images, and CNNs are still most commonly used for vision-related tasks. For today, we’ll primarily be focusing on CNNs for images. Before we dive into convolutions and neural networks, it’s worth prefacing with how images are represented by a computer, as this understanding will inform some of our design choices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*mZlhAHkEkYWaRgWaE7QtNg.png" /><figcaption>Image by author</figcaption></figure><p>With a 2D representation as above, we for the most part can only efficiently represent grayscale images. What if we want color? There are many schemes for storing color, but one of the most common ones is the <a href="https://en.wikipedia.org/wiki/RGB_color_model">RGB color model</a>. In such a system, we store 3 tables of pixel intensities (each called a <em>channel</em>), one each for the colors red, green, and blue (hence RGB), resulting in an 𝐻×𝑊×3 tensor. Pixel values for a particular channel indicate how much of the corresponding color the image has at a particular location.</p><p>Let’s load an image and see this:</p><pre>import imageio<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><pre># Read image<br>im = imageio.imread(&quot;./Figures/chapel.jpg&quot;)<br>print(&quot;Shape of the image tensor: {}&quot;.format(im.shape))<br>plt.imshow(im)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*oF9c_2xgKgVtpfWiK2IW7g.png" /><figcaption>Image by author</figcaption></figure><p>We can see that the image we loaded has a height and width of 620×1175, with 3 channels corresponding to RGB.</p><p>We can easily slice out and view individual color channels:</p><pre># Red channel<br>im_red = im[:,:,0]<br>print(im_red.shape)<br>plt.imshow(im_red, cmap=&#39;gray&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*u67C4g2AMaBfqd_Fd4Qgrw.png" /><figcaption>Image by author</figcaption></figure><pre># Blue channel<br>im_blue = im[:,:,2]<br>print(im_red.shape)<br>plt.imshow(im_blue, cmap=&#39;gray&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*HTJwQlrVvS2t1fKNS0_Icg.png" /><figcaption>Image by author</figcaption></figure><p>While we have so far considered only 3 channel RGB images, there are many settings in which we may consider a different number of channels. For example, <a href="https://en.wikipedia.org/wiki/Hyperspectral_imaging">hyperspectral imaging</a> uses a wide range of electromagnetic spectrums to characterize a scene. Such modalities may have hundreds of channels or more. Additionally, we’ll soon see that certain intermediate representations in a CNN can be considered images with many channels. However, we’ll focus much of today’s discussion on 1 channel grayscale and 3 channel RGB images as our inputs, as is most commonly the case in computer vision.</p><h3>Convolutions</h3><p>Convolutional neural networks (CNNs) are a class of neural networks that have convolutional layers. CNN&#39;s are particularly effective for data that have spatial structures and correlations (e.g. images). We’ll focus on CNN&#39;s applied to images in this tutorial. Recall that a multilayer perceptron (MLP) is entirely composed of fully connected layers, which are each a matrix multiply operation (and addition of a bias) followed by a non-linearity (e.g. sigmoid, ReLU). A convolutional layer is similar, except the matrix multiply operation is replaced with a convolution operation (in practice a cross-correlation). Note that a CNN need not be entirely composed of convolutional layers; in fact, many popular CNN architectures end in fully connected layers.</p><p>As before, since we’re building neural networks, let’s start by loading PyTorch. We’ll find NumPy useful as well, so we’ll also import that here.</p><pre>import numpy as np<br>import torch<br>import torch.nn.functional as F</pre><h4>Review: Fully connected layer</h4><p>In a fully connected layer, the input 𝑥∈ℝ𝑀×𝐶𝑖𝑛 is a vector (or, rather a batch of vectors), where 𝑀 is the minibatch size and 𝐶𝑖𝑛 is the dimensionality of the input. We first matrix multiply the input 𝑥 by a weight matrix 𝑊. This weight matrix has dimensions 𝑊∈ℝ𝐶𝑖𝑛×𝐶𝑜𝑢𝑡, where 𝐶𝑜𝑢𝑡 is the number of output units. We then add a bias for each output, which we do by adding 𝑏∈ℝ𝐶𝑜𝑢𝑡. The output 𝑦∈ℝ𝑀×𝐶𝑜𝑢𝑡 of the fully connected layer then:</p><p>𝑦=ReLU(𝑥𝑊+𝑏)</p><p>Remember, the values of 𝑊 and 𝑏 are variables that we are trying to learn for our model. Below, we visualize what the matrix operation looks like (bias term and activation function omitted).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*_MhJt38PK4wFLMU5Shyl4g.png" /><figcaption>Image by author</figcaption></figure><pre># Create a random flat input vector<br>x_fc = torch.randn(100, 784)</pre><pre># Create weight matrix variable<br>W = torch.randn(784, 10)/np.sqrt(784)<br>W.requires_grad_()</pre><pre># Create bias variable<br>b = torch.zeros(10, requires_grad=True)</pre><pre># Apply fully connected layer<br>y_preact = torch.matmul(x_fc, W) + b<br>y = F.relu(y_preact)</pre><pre># Print input/output shape<br>print(&quot;Input shape: {}&quot;.format(x_fc.shape))<br>print(&quot;Output shape: {}&quot;.format(y.shape))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*DtfNJLTnRPVWL7CQL5K7pQ.png" /><figcaption>Image by author</figcaption></figure><h4>Convolutional layer</h4><p>In a convolutional layer, we convolve the input 𝑥 with a convolutional kernel (aka filter), which we also call 𝑊, producing output 𝑦:</p><p>𝑦=ReLU(𝑊∗𝑥+𝑏)</p><p>In the context of CNNs, the output 𝑦 is often referred to as feature maps. As with a fully connected layer, the goal is to learn 𝑊 and 𝑏 for our model.</p><p>Unlike the input of a fully connected layer, which is 𝑥∈ℝ𝑀×𝐶𝑖𝑛, the dimensionality of image input is 4D: 𝑥∈ℝ𝑀×𝐶𝑖𝑛×𝐻𝑖𝑛×𝑊𝑖𝑛, where 𝑀 is still the batch size, 𝐶𝑖𝑛 is the number of channels of the input (e.g. 3 for RGB), and 𝐻𝑖𝑛 and 𝑊𝑖𝑛 are the height and width of the image.</p><p>The weight parameter 𝑊 is also different in a convolutional layer. Unlike the 2-D weight matrix for fully connected layers, the kernel is 4-D with dimensions 𝑊∈ℝ𝐶𝑜𝑢𝑡×𝐶𝑖𝑛×𝐻𝐾×𝑊𝐾, where 𝐻𝐾 and 𝑊𝐾 are the kernel height and weight, respectively. A common choice for 𝐻𝐾 and 𝑊𝐾 is 𝐻𝐾=𝑊𝐾=3 or 5, but this tends to vary depending on the architecture. Convolving the input with the kernel and adding a bias then gives an output 𝑦∈ℝ𝑀×𝐶𝑜𝑢𝑡×𝐻𝑜𝑢𝑡×𝑊𝑜𝑢𝑡. If we use “same” padding and a stride of 1 in our convolution (more on this later), our output will have the same spatial dimensions as the input: 𝐻𝑜𝑢𝑡=𝐻𝑖𝑛 and 𝑊𝑜𝑢𝑡=𝑊𝑖𝑛.</p><p>If you’re having trouble visualizing this operation in 4D, it’s easier to think about for a single member of the minibatch, one convolutional kernel at a time. Consider a stack of 𝐶𝑜𝑢𝑡 number of kernels, each of which is 3D (𝐶𝑖𝑛×𝐻𝐾×𝑊𝐾). This 3D volume is then slid across the input (which is also 3D: 𝐶𝑖𝑛×𝐻𝑖𝑛×𝑊𝑖𝑛) in the two spatial dimensions (along 𝐻𝑖𝑛 and 𝑊𝑖𝑛). The outputs of the multiplication of the kernel and the input at every location create a single feature map that is 𝐻𝑜𝑢𝑡×𝑊𝑜𝑢𝑡. Stacking the feature maps generated by each kernel gives the 3D output 𝐶𝑜𝑢𝑡×𝐻𝑜𝑢𝑡×𝑊𝑜𝑢𝑡. Repeat the process for all 𝑀 inputs in the minibatch, and we get a 4D output 𝑀×𝐶𝑜𝑢𝑡×𝐻𝑜𝑢𝑡×𝑊𝑜𝑢𝑡.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*CpgY8KPV8oGDPEtyaiXXPg.png" /><figcaption>Image by author</figcaption></figure><p>A few more things to note:</p><ul><li>Notice the ordering of the dimensions of the input (batch, channels in, height, width). This is commonly referred to as 𝑁𝐶𝐻𝑊 ordering. Many other languages and libraries (e.g. MATLAB, TensorFlow, the image example at the beginning of this notebook) instead of default to the slightly different 𝑁𝐻𝑊𝐶 ordering. PyTorch defaults to 𝑁𝐶𝐻𝑊, as it more efficient computationally, especially with CUDA.</li><li>An additional argument for the convolution is the <em>stride</em>, which controls how far we slide the convolutional filter as we move it along the input image. The convolutional operator, from its signal processing roots, by default considers a stride length of 1 in all dimensions, but in some situations, we would like to consider strides more than 1 (or even less than 1). More on this later.</li><li>In the context of signal processing, convolutions usually result in outputs that are larger than the input size, which results from when the kernel “hangs off the edge” of the input on both sides. This might not always be desirable. We can control this by controlling the padding of the input. Typically, we use to pad the input to ensure the output has the same spatial dimensions as the input (assuming a stride of 1); this makes it easier for us to keep track of the size of our model is.</li></ul><p>Let’s implement this convolution operator in code. There is a convolution implementation in torch.nn.functional, which we use here.</p><pre># Create a random image input tensor<br>x_cnn = torch.randn(100, 1, 28, 28)</pre><pre># Create convolutional kernel variable<br>W1 = torch.randn(16, 1, 3, 3)/np.sqrt(1*3*3)<br>W1.requires_grad_()</pre><pre># Create bias variable<br>b1 = torch.zeros(16, requires_grad=True)</pre><pre># Apply convolutional layer<br>conv1_preact = F.conv2d(x_cnn, W1, bias=b1, stride=1, padding=1)<br>conv1 = F.relu(conv1_preact)</pre><pre># Print input/output shape<br>print(&quot;Input shape: {}&quot;.format(x_cnn.shape))<br>print(&quot;Convolution output shape: {}&quot;.format(conv1.shape))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*ZRgkzBMRObUVA3EO2ap_Kg.png" /><figcaption>Image by author</figcaption></figure><p>Just like in an MLP, we can stack multiple of these convolutional layers. In the <em>Representing Images Digitally</em> section, we briefly mentioned considering images with channels of more than 3. Observe that the input to the second layer (i.e. the output of the first layer) can be viewed as an “image” with 𝐶𝑜𝑢𝑡Cout channels. Instead of each channel representing a color content though, each channel effectively represents how much the original input image activated a particular convolutional kernel. Given 𝐶𝑜𝑢𝑡Cout kernels that are each 𝐶𝑖𝑛×𝐻𝐾×𝑊𝐾, this results in 𝐶𝑜𝑢𝑡 channels for the output of the convolution.</p><p>Note that we need to change the dimensions of the convolutional kernel such that its input channels match the number of output channels of the previous layer:</p><pre># 2nd layer variables<br>W2 = torch.randn(32, 16, 3, 3)/np.sqrt(16*3*3)<br>W2.requires_grad_()<br>b2 = torch.zeros(32, requires_grad=True)</pre><pre># Apply 2nd convolutional layer<br>conv2 = F.relu(F.conv2d(conv1, W2, bias=b2, stride=1, padding=1))</pre><pre># Print output shape<br>print(&quot;Second convolution output shape: {}&quot;.format(conv2.shape))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*jWemdXLFZwLe2YzLl3VGmw.png" /><figcaption>Image by author</figcaption></figure><p>In fact, we typically perform these convolution operations many times. Popular CNN architectures for image analysis today can be 100+ layers.</p><h3>Reshaping</h3><p>You’ll commonly find yourself needing to reshape tensors while building CNNs. The PyTorch function for doing so is view(). Anyone familiar with NumPy will find it very similar to np.reshape(). Importantly, the new dimensions must be chosen so that it is possible to rearrange the input into the shape of the output (i.e. the total number of elements must be the same). As with NumPy, you can optionally replace one of the dimensions with a -1, which tells torch to infer the missing dimension.</p><pre>M = torch.zeros(4, 3)</pre><pre>M2 = M.view(1,1,12)<br>M3 = M.view(2,1,2,3)<br>M4 = M.view(-1,2,3)<br>M5 = M.view(-1)</pre><p>To get an idea of why reshaping is needed in a CNN, let’s look at a diagram of a simple CNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*hrMCERkSv3U6Ke4VqqLCPA.png" /><figcaption>Image by author</figcaption></figure><p>First of all, the CNN expects a 4D input, with the dimensions corresponding to [batch, channel, height, width]. Your data may not come in this format, so you may have to reshape it yourself.</p><pre># Reshape flat input image into a 4D batched image input<br>x_flat = torch.randn(100, 784)<br>x_reshaped = x_flat.view(-1, 1, 28, 28)</pre><pre># Print input shape<br>print(x_reshaped.shape)</pre><p>CNN architectures also commonly contain fully connected layers or a softmax, as we’re often interested in classification. Both of these expect 2D inputs with dimensions [batch, dim], so you have to &quot;flatten&quot; a CNN&#39;s 4D output to 2D. For example, to flatten the convolutional feature maps we created earlier:</p><pre># Flatten convolutional feature maps into a vector<br>h_flat = conv2.view(-1, 28*28*32)</pre><pre># Print output shape<br>print(h_flat.shape)</pre><h3>Pooling and striding</h3><p>Almost all CNN architectures incorporate either pooling or striding. This is done for several reasons, including:</p><ul><li>Dimensionality reduction: pooling and striding operations reduce computational complexity by shrinking the number of values passed to the next layer. For example, a 2x2 max pool reduces the size of the feature maps by a factor of 4.</li><li>Translational invariance: Oftentimes in computer vision, we’d prefer that shifting the input by a few pixels doesn’t change the output. Pooling and striding reduce sensitivity to exact pixel locations.</li><li>Increasing receptive field: by summarizing a window with a single value, subsequent convolutional kernels are seeing a wider swath of the original input image. For example, a max pool on some input followed by a 3x3 convolution results in a kernel “seeing” a 6x6 region instead of 3x3.</li></ul><h4>Pooling</h4><p>The two most common forms of pooling are max pooling and average pooling. Both reduce values within a window to a single value, on a per-feature-map basis. Max pooling takes the maximum value of the window as the output value; average pooling takes the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*ozbUWNu4kqQSBGZ4zgAucA.png" /><figcaption>Image by author</figcaption></figure><pre># Taking the output we&#39;ve been working with so far, first print its current size<br>print(&quot;Shape of conv2 feature maps before pooling: {0}&quot;.format(conv2.shape))</pre><pre># Max pool and then print new shape<br>max_pool2 = F.max_pool2d(conv2, kernel_size=2)<br>print(&quot;Shape of conv2 feature maps after max pooling: {0}&quot;.format(max_pool2.shape))</pre><pre># Average pool and then print new shape<br>avg_pool2 = F.avg_pool2d(conv2, kernel_size=2)<br>print(&quot;Shape of conv2 feature maps after avg pooling: {0}&quot;.format(avg_pool2.shape))</pre><p>We can confirm that the two types of pooling behave how we’d expect:</p><pre># Recreate values in pooling figure and make it 4D<br>feature_map_fig = torch.tensor(np.array([[1,1,2,4],<br>                                        [5,6,7,8],<br>                                        [3,2,1,0],<br>                                        [1,2,3,4]], dtype=np.float32))<br>fmap_fig = feature_map_fig.view(1,1,4,4)<br>print(&quot;Feature map shape pre-pooling: {}&quot;.format(fmap_fig.shape))</pre><pre># Maxpool<br>max_pool_fig = F.max_pool2d(fmap_fig, kernel_size=2)<br>print(&quot;\nMax pool&quot;)<br>print(&quot;Shape: {}&quot;.format(max_pool_fig.shape))<br>print(torch.squeeze(max_pool_fig))</pre><pre># Avgpool<br>avg_pool_fig = F.avg_pool2d(fmap_fig, kernel_size=2)<br>print(&quot;\nAvg pool&quot;)<br>print(&quot;Shape: {}&quot;.format(avg_pool_fig.shape))<br>print(torch.squeeze(avg_pool_fig))</pre><h4>Striding</h4><p>One might expect that pixels in an image have a high correlation with neighboring pixels, so we can save computation by skipping positions while sliding the convolutional kernel. By default, a CNN slides across the input one pixel at a time, which we call a stride of 1. By instead striding by 2, we skip calculating 75% of the values of the output feature map, which yields a feature map that’s half the size in each spatial direction. Note, while pooling is an operation done after the convolution, striding is part of the convolution operation itself.</p><pre># Since striding is part of the convolution operation, we&#39;ll start with the feature maps before the 2nd convolution<br>print(&quot;Shape of conv1 feature maps: {0}&quot;.format(conv1.shape))</pre><pre># Apply 2nd convolutional layer, with striding of 2<br>conv2_strided = F.relu(F.conv2d(conv1, W2, bias=b2, stride=2, padding=1))</pre><pre># Print output shape<br>print(&quot;Shape of conv2 feature maps with stride of 2: {0}&quot;.format(conv2_strided.shape))Building a custom CNN</pre><p>Let&#39;s revisit MNIST digit classification, but this time, we&#39;ll use the following CNN as our classifier: 5×5 convolution -&gt; 2×2 max pool -&gt; 5×5 convolution -&gt; 2×2 max pool -&gt; fully connected to ℝ256 -&gt; fully connected to ℝ10 (prediction). ReLU activation functions will be used to impose non-linearities. Remember, convolutions produce 4-D outputs, and fully connected layers expect 2-D inputs, so tensors must be reshaped when transitioning from one to the other.</p><p>We can build this CNN with the components introduced before, but as with the logistic regression example, it may prove helpful to instead organize our model with a nn.Module.</p><pre>import torch.nn as nn</pre><pre>class MNIST_CNN(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.conv1 = nn.Conv2d(1, 32, kernel_size=5, padding=2)<br>        self.conv2 = nn.Conv2d(32, 64, kernel_size=5, padding=2)<br>        self.fc1 = nn.Linear(7*7*64, 256)<br>        self.fc2 = nn.Linear(256, 10)</pre><pre>def forward(self, x):<br>        # conv layer 1<br>        x = self.conv1(x)<br>        x = F.relu(x)<br>        x = F.max_pool2d(x, kernel_size=2)<br>        <br>        # conv layer 2<br>        x = self.conv2(x)<br>        x = F.relu(x)<br>        x = F.max_pool2d(x, kernel_size=2)<br>        <br>        # fc layer 1<br>        x = x.view(-1, 7*7*64)<br>        x = self.fc1(x)<br>        x = F.relu(x)<br>        <br>        # fc layer 2<br>        x = self.fc2(x)<br>        return x</pre><p>Notice how our nn.Module contains several operations chained together. The code for submodule initialization, which creates all the stateful parameters associated with each operation, is placed in the __init__() function, where it is run once during object instantiation. Meanwhile, the code describing the forward pass, which is used every time the model is run, is placed in the forward() method. Printing an instantiated model shows the model summary:</p><pre>model = MNIST_CNN()<br>print(model)</pre><p>We can drop this model into our logistic regression training code, with few modifications beyond changing the model itself. A few other changes:</p><ul><li>CNN&#39;s expect a 4-D input, so we no longer have to reshape the images before feeding them to our neural network.</li><li>Since CNNs are a little more complex than models we’ve worked with before, we’re going to increase the number of epochs (complete passes through the training data) during training.</li><li>We switch from a vanilla stochastic gradient descent optimizer to the <a href="https://arxiv.org/abs/1412.6980">Adam</a> optimizer, which tends to do well for neural networks.</li></ul><pre>import numpy as np<br>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>from torchvision import datasets, transforms<br>from tqdm.notebook import tqdm, trange</pre><pre># Load the data<br>mnist_train = datasets.MNIST(root=&quot;./datasets&quot;, train=True, transform=transforms.ToTensor(), download=True)</pre><pre>mnist_test = datasets.MNIST(root=&quot;./datasets&quot;, train=False, transform=transforms.ToTensor(), download=True)</pre><pre>train_loader = torch.utils.data.DataLoader(mnist_train, batch_size=100, shuffle=True)</pre><pre>test_loader = torch.utils.data.DataLoader(mnist_test, batch_size=100, shuffle=False)</pre><pre>## Training<br># Instantiate model  <br>model = MNIST_CNN()  # &lt;---- change here</pre><pre># Loss and Optimizer<br>criterion = nn.CrossEntropyLoss()<br>optimizer = torch.optim.Adam(model.parameters(), lr=0.001)  # &lt;---- change here</pre><pre># Iterate through train set minibatchs <br>for epoch in trange(3):  # &lt;---- change here<br>    for images, labels in tqdm(train_loader):<br>        # Zero out the gradients<br>        optimizer.zero_grad()</pre><pre># Forward pass<br>        x = images  # &lt;---- change here <br>        y = model(x)<br>        loss = criterion(y, labels)<br>        # Backward pass<br>        loss.backward()<br>        optimizer.step()</pre><pre>## Testing<br>correct = 0<br>total = len(mnist_test)</pre><pre>with torch.no_grad():<br>    # Iterate through test set minibatchs <br>    for images, labels in tqdm(test_loader):<br>        # Forward pass<br>        x = images  # &lt;---- change here <br>        y = model(x)</pre><pre>predictions = torch.argmax(y, dim=1)<br>        correct += torch.sum((predictions == labels).float())</pre><pre>print(&#39;Test accuracy: {}&#39;.format(correct/total))</pre><p>If you are running this notebook on the CPU, training this CNN might take a while. On the other hand, if you use a GPU, this model should train in seconds. This is why we usually prefer to use GPUs when we have them.</p><h3>Torchvision</h3><h4>Datasets and transforms</h4><p>As any experienced ML practioner will say, data wrangling is often half (sometimes even 90%) of the battle when building a model. Often, we have to write significant code to handle downloading, organizing, formatting, shuffling, pre-processing, augmenting, and batching examples. We’d like to standardize data handling for popular datasets so that the comparisons we make are specific to the models themselves.</p><p>Enter <a href="https://pytorch.org/docs/stable/torchvision/index.html">Torchvision</a>. Torchvision includes easy-to-use APIs for downloading and loading many popular vision datasets. We’ve previously seen this in action for downloading the MNIST dataset:</p><pre>from torchvision import datasets</pre><pre>mnist_train = datasets.MNIST(root=&quot;./datasets&quot;, train=True, transform=transforms.ToTensor(), download=True)</pre><p>Of course, there are <a href="https://pytorch.org/docs/stable/torchvision/datasets.html">many more</a>. Currently, datasets for image classification (e.g. MNIST, CIFAR, ImageNet), object detection (VOC, COCO, Cityscapes), and video action recognition (UCF101, Kinetics) are included.</p><p>For formatting, pre-processing, and augmenting, <a href="https://pytorch.org/docs/stable/torchvision/transforms.html">transforms</a> can come in handy. Again, we’ve seen this before (see above), when we used a transform to convert the MNIST data from PIL images to PyTorch tensors. However, transforms can be used for much more. Preprocessing steps like data whitening are common before feeding the data into the model. Also, in many cases, we use data augmentations to artificially inflate our dataset and learn invariances. Transforms are a versatile tool for all of these.</p><h4>Leveraging popular convolutional neural networks</h4><p>While you certainly can build your own custom CNNs as we did above, more often than not, it’s better to use one of the popular existing architectures. The Torchvision documentation has a <a href="https://pytorch.org/docs/stable/torchvision/models.html">list of supported CNN&#39;s</a>, as well as some performance characteristics. There are several reasons for using one of these CNNs instead of designing your own.</p><p>First, for image datasets larger and more complex than MNIST (which is basically all of them), a fair amount of network depth and width is often necessary. For example, some of the popular CNNs can be over 100 layers deep, with several tricks and details beyond what we’ve covered in this notebook. Coding all of this yourself has a high potential for error, especially when you’re first getting started. Instead, you can create the CNN architecture using Torchvision, using a couple of lines:</p><pre>import torchvision.models as models<br>resnet18 = models.resnet18()<br>print(resnet18)</pre><p>Loading a working CNN architecture in a couple of lines can save a significant amount of time both implementing and debugging.</p><p>The second, perhaps even more important, a reason to use one of these existing architectures is the ability to use pre-trained weights. Early on in the recent resurgence of deep learning, people discovered that the weights of a CNN trained for ImageNet classification were highly transferable. For example, it is common to use the weights of an ImageNet-trained CNN as a weight initialization for other vision tasks, or even to freeze the bulk of the weights and only re-train the final classification layer(s) on a new task. This is significant, as, in most settings, we rarely have enough labeled data to train a powerful CNN from scratch without overfitting. Loading pre-trained CNN is also pretty simple, involving an additional argument to the previous cell block:</p><pre># resnet18 = models.resnet18(pretrained=True)</pre><p><em>Note that this line of code is commented out, as running it will initiate a download of the pre-trained weights, which is a fairly large file.</em></p><p>A full tutorial on using pre-trained CNNs is a little beyond the scope of this notebook. See <a href="https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html">this tutorial</a> for an example.</p><h4>Other computer vision tasks</h4><p>The base CNN architectures were often designed for image classification, but the same CNNs are often used as the backbone of most modern computer vision models. These other models often take this base CNN and include additional networks or make other architecture changes to adapt them to other tasks, such as object detection. Torchvision contains a few models (and pre-trained weights) for object detection, segmentation, and video action recognition. For example, to load a <a href="https://arxiv.org/abs/1506.01497">Faster R-CNN</a> with a <a href="https://arxiv.org/abs/1512.03385">ResNet50</a> convolutional feature extractor with <a href="https://arxiv.org/abs/1612.03144">Feature Pyramid Networks</a> pre-trained on <a href="http://cocodataset.org/#home">MS COCO</a>:</p><pre># object_detector = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)</pre><p><em>Again, this line has been commented out to prevent loading a large network for this demo.</em></p><p>Torchvision’s selection of non-classification models is relatively light, and not particularly flexible. Several other libraries are available, depending on the task. For example, for object detection and segmentation, Facebook AI Research’s <a href="https://github.com/facebookresearch/detectron2">Detectron2</a> highly recommends.</p><p>Once you have reached this sentence you have gone through all steps for Introduction to Convolutional Neural Networks (CNNs) PyTorch.</p><p>Here is a summary of your accomplishment today:</p><ul><li>Representing images digitally</li><li>Convolutions: Review: Fully connected layer, Convolutional layer,</li><li>Reshaping</li><li>Pooling and striding: Pooling, Striding</li><li>Building a custom CNN</li><li>Torchvision: Datasets and transforms, Leveraging popular convolutional neural networks, other computer vision tasks</li></ul><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1a849aaf58c" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/introduction-to-convolutional-neural-networks-cnns-in-pytorch-d1a849aaf58c">Introduction to Convolutional Neural Networks (CNNs) in PyTorch</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handwritten digit classification using neural network in Pytorch]]></title>
            <link>https://medium.datadriveninvestor.com/handwritten-digit-classification-using-neural-network-in-pytorch-eeef32c7a94?source=rss-b9416d02a1b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeef32c7a94</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[mnist]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Harsh Panchal]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 09:00:10 GMT</pubDate>
            <atom:updated>2021-06-14T09:00:10.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUKx2Mokt9i9zmc7E4gyAA.jpeg" /><figcaption>photo by <a href="https://wallpapercave.com/w/wp6077863">wallpapercave</a></figcaption></figure><p>In this article, we’re going to build a very simple neural network in PyTorch to do handwritten digit classification. First, we’ll start with some exploration of the MNIST dataset, explaining how we load and format the data. We’ll then jump into motivating and then implementing the logistic regression model, including the forward and backward pass, loss functions, and optimizers. After training the model, we’ll evaluate how we did and visualize what we’ve learned. Finally, we’ll refactor our code in an object-oriented manner, using higher-level APIs.</p><p>Before we get started, some imports for the packages we’ll be using:</p><pre>%matplotlib inline</pre><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import torch<br>from tqdm.notebook import tqdm</pre><h3>MNIST Dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*4y-3jJNB-c5YQvewhZ6JHQ.png" /><figcaption>Image by author</figcaption></figure><p>The MNIST dataset is a very popular machine learning dataset, consisting of 70000 grayscale images of handwritten digits, of dimensions 28x28. We’ll be using it as our example dataset for this section of the tutorial, with the goal being to predict which digit is in each image.</p><p>The first (and often most important) step in machine learning is preparing the data. This can include downloading, organizing, formatting, shuffling, pre-processing, augmenting, and batching examples so that they can be fed to a model. The torchvision package makes this easy by implementing many of these, allowing us to put these datasets into a usable form in only a few lines of code. First, let&#39;s download the train and test sets of MNIST:</p><pre>from torchvision import datasets, transforms</pre><pre>mnist_train = datasets.MNIST(root=&quot;./datasets&quot;, train=True, transform=transforms.ToTensor(), download=True)</pre><pre>mnist_test = datasets.MNIST(root=&quot;./datasets&quot;, train=False, transform=transforms.ToTensor(), download=True)</pre><pre>print(&quot;Number of MNIST training examples: {}&quot;.format(len(mnist_train)))</pre><pre>print(&quot;Number of MNIST test examples: {}&quot;.format(len(mnist_test)))<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*O-pMJMwVcgxWrGubh7VYNA.png" /><figcaption>Image by author</figcaption></figure><p>As we’d expect, 60000 of the MNIST examples are in the train set, and the rest are in the test set. We added the transform ToTensor() when formatting the dataset, to convert the input data from a Pillow Image type into a PyTorch Tensor. Tensors will eventually be the input type that we feed into our model.</p><p>Let’s look at an example image from the train set and its label. Notice that the image tensor defaults to something 3-dimensional. The &quot;1&quot; in the first dimension indicates that the image only has one channel (i.e. grayscale). We need to get rid of this to visualize the image with imshow.</p><pre># Pick out the 4th (0-indexed) example from the training set<br>image, label = mnist_train[3]</pre><pre># Plot the image<br>print(&quot;Default image shape: {}&quot;.format(image.shape))<br>image = image.reshape([28,28])</pre><pre>print(&quot;Reshaped image shape: {}&quot;.format(image.shape))<br>plt.imshow(image, cmap=&quot;gray&quot;)</pre><pre># Print the label<br>print(&quot;The label for this image: {}&quot;.format(label))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*WiKwwSJSxjQNyY7DmqbRoQ.png" /><figcaption>Image by author</figcaption></figure><p>While we could work directly with the data as a torchvision.dataset, we&#39;ll find it useful to use a DataLoader, which will take care of shuffling and batching:</p><pre>train_loader = torch.utils.data.DataLoader(mnist_train, batch_size=100, shuffle=True)</pre><pre>test_loader = torch.utils.data.DataLoader(mnist_test, batch_size=100, shuffle=False)</pre><p>An example of a minibatch drawn from a DataLoader:</p><pre>data_train_iter = iter(train_loader)<br>images, labels = data_train_iter.next()</pre><pre>print(&quot;Shape of the minibatch of images: {}&quot;.format(images.shape))<br>print(&quot;Shape of the minibatch of labels: {}&quot;.format(labels.shape))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*JyOXAB_8P89J6YHKXBeu1w.png" /><figcaption>Image by author</figcaption></figure><h3>Logistic Regression Model</h3><p>Now that we have a good feel for how to load our data, let’s start putting together our model. In this tutorial, we’ll be building a logistic regression model, which is essentially a fully connected neural network without any hidden layers. While fairly basic, logistic regression can perform surprisingly well on many simple classification tasks.</p><h4>The forward pass</h4><p>While our data inputs (which we’ll call x) are images (i.e. 2-dimensional), MNIST digits are pretty small, and the model we&#39;re using is very simple. Thus, we&#39;re going to be treating the input as flat vectors. To convert our inputs into row vectors (a.k.a. flattening), we can use, the equivalent of NumPy&#39;s reshape(). Also like NumPy, we can replace one of the dimensions of the reshaping with a -1, which tells PyTorch to infer this dimension based on the original dimensions and the other specified dimensions. Let&#39;s do try this flattening on the minibatch of 100 images we drew in the previous section.</p><pre>x = images.view(-1, 28*28)<br>print(&quot;The shape of input x: {}&quot;.format(x.shape))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*X4ItHDkrhg1_tKzdRRjnHA.png" /><figcaption>Image by author</figcaption></figure><p>To get our predicted probabilities of each digit, let’s first start with the probability of a digit being a 1 like the image above. For our simple model, we can start by applying a linear transformation. That is, we multiply each pixel 𝑥𝑖 of the input row vector by a weight 𝑤𝑖,1, sum them all together, and then add a bias 𝑏1. This is equivalent to a dot product between the class “1” weights and the input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*9U1tv_lxaHne35Hn2EiOdg.png" /><figcaption>Image by author</figcaption></figure><p>The magnitude of this result 𝑦1, we’ll take as being correlated to our belief in how likely we think the input digit was a 1. The higher the value of 𝑦1, the more likely we think the input image 𝑥 was a 1 (i.e., we’d hope we’d get a relatively large value for 𝑦1 for the above image). Remember though, our original goal was to identify all 10 digits, so we actually have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*cPnHIJBzUn27E4iT7KHDVA.png" /><figcaption>Image by author</figcaption></figure><p>We can express this in matrix form as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*rv85h_FI-GD0En6hNNeOAw.png" /><figcaption>Image by author</figcaption></figure><p>To take advantage of parallel computation, we commonly process multiple inputs 𝑥 at once, in a minibatch. We can stack each input 𝑥 into a matrix 𝑋, giving us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*hTtUQemKwnjqU2GCZtC-Rw.png" /><figcaption>Image by author</figcaption></figure><p>Visualizing the dimensions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*jXTquiigcKx_gmAoYH-AdQ.png" /><figcaption>Image by author</figcaption></figure><p>In our specific example, the minibatch size 𝑚m is 100, the dimension of the data is 28×28=784, and the number of classes 𝑐 is 10. While 𝑋 and 𝑌 are matrices due to the batching, conventionally, they are often given lowercase variable names, as if they were for a single example. We will use x and y throughout.</p><p>The weight 𝑊 and bias 𝑏 make up the parameters of this model. When we say that we want to “learn the model,” what we’re really trying to do is find good values for every element in 𝑊 and 𝑏. Before we begin learning, we need to initialize our parameters to some value, as a starting point. Here, we don’t really know what the best values are, so we going to initialize 𝑊 randomly (using something called <a href="http://proceedings.mlr.press/v9/glorot10a.html">Xavier initialization</a>), and set 𝑏 to a vector of zeros.</p><pre># Randomly initialize weights W<br>W = torch.randn(784, 10)/np.sqrt(784)<br>W.requires_grad_()</pre><pre># Initialize bias b as 0s<br>b = torch.zeros(10, requires_grad=True)</pre><p>As both W and b are parameters we wish to learn, we set requires_grad to True. This tells PyTorch&#39;s autograd to track the gradients for these two variables, and all the variables depending on W and b.</p><p>With these model parameters, we compute 𝑦:</p><pre># Linear transformation with W and b<br>y = torch.matmul(x, W) + b</pre><p>We can see for example what the predictions look like for the first example in our minibatch. Remember, the bigger the number, the more the model thinks the input 𝑥 is of that class.</p><pre>print(y[0,:])</pre><p>We can interpret these values (aka logits) 𝑦 as probabilities if we normalize them to be positive and add up to 1. In logistic regression, we do this with a softmax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*OMWyhbIPBIQbVYRJXbx_rg.png" /><figcaption>Image by author</figcaption></figure><p>Notice that because the range of the exponential function is always non-negative, and since we’re normalizing by the sum, the softmax achieves the desired property of producing values between 0 and 1 that sum to 1. If we look at the case with only 2 classes, we see that the softmax is the multi-class extension of the binary sigmoid function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*Lyk7VhrbFnz8ZWHh9BYUjA.png" /><figcaption>Image by author</figcaption></figure><p>We can compute the softmax ourselves using the above formula if we’d like, but PyTorch already has the softmax function in torch.nn.functional:</p><pre># Option 1: Softmax to probabilities from equation<br>py_eq = torch.exp(y) / torch.sum(torch.exp(y), dim=1, keepdim=True)</pre><pre>print(&quot;py[0] from equation: {}&quot;.format(py_eq[0]))</pre><pre># Option 2: Softmax to probabilities with torch.nn.functional<br>import torch.nn.functional as F<br>py = F.softmax(y, dim=1)<br>print(&quot;py[0] with torch.nn.functional.softmax: {}&quot;.format(py[0]))</pre><p>We&#39;ve now defined the forward pass of our model: given an input image, the graph returns the probabilities the model thinks the input is each of the 10 classes. Are we done?</p><h4>The cross-entropy loss</h4><p>This tutorial isn’t done yet, so you can probably guess that the answer is not quite. We don’t know the values of 𝑊 and 𝑏 yet! Remember how we initialized them randomly? Before we adjust any of the weights, we need a way to measure how the model is doing. Specifically, we’re going to measure how badly the model is doing. We do this with a <em>loss</em> function, which takes the model’s prediction and returns a single number (i.e. a scalar) summarizing model performance. This loss will inform how we adjust the parameters of the model.</p><p>The loss we commonly use in classification is cross-entropy, a concept from information theory. Explaining exactly what the cross-entropy represents goes slightly beyond the scope of this course, but you can think of it as a way of quantifying how far apart one distribution 𝑦′ is from another 𝑦.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*Tktur8GH4DZg2VSQ8IX3Gg.png" /><figcaption>Image by author</figcaption></figure><p>In our case, 𝑦 is the set of probabilities predicted by the model (𝑝𝑦 above); 𝑦′ is the target distribution. What is the target distribution? It’s the true label, which is what we wanted the model to predict.</p><p>Cross-entropy not only captures how <em>correct</em> (max probability corresponds to the right answer) the model’s answers are, it also accounts for how <em>confident</em> (high confidence incorrect answers) they are. This encourages the model to produce very high probabilities for correct answers while driving down the probabilities for the wrong answers, instead of merely being satisfied with it being the argmax.</p><p>We focus here on supervised learning, a setting in which we have the labels. We DataLoader automatically includes the corresponding labels for each of our inputs. Here are the labels from the first time we retrieved a minibatch:</p><pre>print(labels.shape)</pre><p>Like the softmax operation, we can implement the cross-entropy directly from the equation, using the softmax output. However, as with the softmax, torch.nn.functional already has the cross-entropy loss implemented as well.</p><pre># Cross-entropy loss from equation<br>cross_entropy_eq = torch.mean(-torch.log(py_eq)[range(labels.shape[0]),labels])<br>print(&quot;cross entropy from equation: {}&quot;.format(cross_entropy_eq))</pre><pre># Option 2: cross-entropy loss with torch.nn.functional<br>cross_entropy = F.cross_entropy(y, labels)<br>print(&quot;cross entropy with torch.nn.functional.cross_entropy: {}&quot;.format(cross_entropy))</pre><p>Note that PyTorch’s cross-entropy loss combines the softmax operator and cross-entropy into a single operation, for numerical stability reasons. Don’t do the softmax twice! Make sure to feed in the pre-softmax logits y, not the post-softmax probabilities py.</p><h4>The backward pass</h4><p>Now that we have the loss as a way of quantifying how badly the model is doing, we can improve our model by changing the parameters in a way that minimizes the loss. For neural networks, the common way of doing this is with backpropagation: we take the gradient of the loss with respect to 𝑊 and 𝑏b and take a step in the direction that reduces our loss.</p><p>If we were not using a deep learning framework like PyTorch, we would have to go through and derive all the gradients ourselves by hand, then code them into our program. We certainly still could. However, with modern auto-differentiation libraries, it’s much faster and easier to let the computer do it.</p><p>First, we need to create an optimizer. There are many choices, but since logistic regression is fairly simple, we’ll use standard stochastic gradient descent (SGD), which makes the following update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*UTJ9-17rnQAiaJdEQUJUKw.png" /><figcaption>Image by author</figcaption></figure><p>where 𝜃 is a parameter, 𝛼 is our learning rate (step size), and ∇𝜃L is the gradient of our loss with respect to 𝜃.</p><pre># Optimizer<br>optimizer = torch.optim.SGD([W,b], lr=0.1)</pre><p>When we created our parameters 𝑊 and 𝑏, we indicated that they require gradients. To compute the gradients for 𝑊 and 𝑏, we call the backward() function on the cross-entropy loss.</p><pre>cross_entropy.backward()</pre><p>Each of the variables that required gradients have now accumulated gradients. We can see these for example on b:</p><pre>b.grad</pre><p>To apply the gradients, we could manually update 𝑊 and 𝑏 using the update rule 𝜃𝑡+1=𝜃𝑡−𝛼∇𝜃L, but since we have an optimizer, we can tell it to perform the update step for us:</p><pre>optimizer.step()</pre><p>We set our learning rate to 0.1, so b has been updated by -0.1*b.grad:</p><pre>b</pre><p>We’ve now successfully trained on a minibatch! However, one minibatch probably isn’t enough. At this point, we’ve trained the model on 100 examples out of the 60000 in the training set. We’re going to need to repeat this process, for more of the data.</p><p>One more thing to keep in mind though: gradients calculated backward() don&#39;t override the old values; instead, they accumulate. Therefore, you&#39;ll want to clear the gradient buffers before you compute gradients for the next minibatch.</p><pre>print(&quot;b.grad before zero_grad(): {}&quot;.format(b.grad))<br>optimizer.zero_grad()<br>print(&quot;b.grad after zero_grad(): {}&quot;.format(b.grad))</pre><h4>Model Training</h4><p>To train the model, we just need to repeat what we just did for more mini-batches from the training set. As a recap, the steps were:</p><ol><li>Draw a minibatch</li><li>Zero the gradients in the buffers for W and b</li><li>Perform the forward pass (compute prediction, calculate loss)</li><li>Perform the backward pass (compute gradients, perform SGD step)</li></ol><p>Going through the entire dataset once is referred to as an epoch. In many cases, we train neural networks for multiple epochs, but here, a single epoch is enough. We also wrap the train_loader with tqdm. This isn&#39;t necessary, but it adds a handy progress bar so we can track our training progress.</p><pre># Iterate through train set minibatchs <br>for images, labels in tqdm(train_loader):<br>    # Zero out the gradients<br>    optimizer.zero_grad()<br>    <br>    # Forward pass<br>    x = images.view(-1, 28*28)<br>    y = torch.matmul(x, W) + b<br>    cross_entropy = F.cross_entropy(y, labels)<br>    # Backward pass<br>    cross_entropy.backward()<br>    optimizer.step()</pre><h4>Testing</h4><p>Now let’s see how we did! For every image in our test set, we run the data through the model and take the digit in which we have the highest confidence as our answer. We then compute an accuracy by seeing how many we got correct. We’re going to wrap evaluation with torch.no_grad(), as we&#39;re not interested in computing gradients during evaluation. By turning off the autograd engine, we can speed up evaluation.</p><pre>correct = 0<br>total = len(mnist_test)</pre><pre>with torch.no_grad():<br>    # Iterate through test set minibatchs <br>    for images, labels in tqdm(test_loader):<br>        # Forward pass<br>        x = images.view(-1, 28*28)<br>        y = torch.matmul(x, W) + b<br>        <br>        predictions = torch.argmax(y, dim=1)<br>        correct += torch.sum((predictions == labels).float())<br>    <br>print(&#39;Test accuracy: {}&#39;.format(correct/total))</pre><p>Not bad for a simple model and a few lines of code. Before we conclude this example, there’s one more interesting thing we can do. Normally, it can be difficult to inspect exactly what the filters in a model are doing, but since this model is so simple, and the weights transform the data directly to their logits, we can actually visualize what the model’s learning by simply plotting the weights. The results look pretty reasonable:</p><pre># Get weights<br>fig, ax = plt.subplots(1, 10, figsize=(20, 2))</pre><pre>for digit in range(10):<br>    ax[digit].imshow(W[:,digit].detach().view(28,28), cmap=&#39;gray&#39;)</pre><p>As we can see, the model learned a template for each digit. Remember that our model takes a dot product between the weights of each digit and input. Therefore, the more the input matches the template for a digit, the higher the value of the dot product for that digit will be, which makes the model more likely to predict that digit.</p><h4>The Full Code</h4><p>The entire model, with the complete model definition, training, and evaluation (but minus the weights visualization) as independently runnable code:</p><pre>import numpy as np<br>import torch<br>import torch.nn.functional as F<br>from torchvision import datasets, transforms<br>from tqdm.notebook import tqdm</pre><pre># Load the data<br>mnist_train = datasets.MNIST(root=&quot;./datasets&quot;, train=True, transform=transforms.ToTensor(), download=True)<br>mnist_test = datasets.MNIST(root=&quot;./datasets&quot;, train=False, transform=transforms.ToTensor(), download=True)<br>train_loader = torch.utils.data.DataLoader(mnist_train, batch_size=100, shuffle=True)<br>test_loader = torch.utils.data.DataLoader(mnist_test, batch_size=100, shuffle=False)</pre><pre>## Training<br># Initialize parameters<br>W = torch.randn(784, 10)/np.sqrt(784)<br>W.requires_grad_()<br>b = torch.zeros(10, requires_grad=True)</pre><pre># Optimizer<br>optimizer = torch.optim.SGD([W,b], lr=0.1)</pre><pre># Iterate through train set minibatchs <br>for images, labels in tqdm(train_loader):<br>    # Zero out the gradients<br>    optimizer.zero_grad()<br>    <br>    # Forward pass<br>    x = images.view(-1, 28*28)<br>    y = torch.matmul(x, W) + b<br>    cross_entropy = F.cross_entropy(y, labels)<br>    # Backward pass<br>    cross_entropy.backward()<br>    optimizer.step()</pre><pre>## Testing<br>correct = 0<br>total = len(mnist_test)</pre><pre>with torch.no_grad():<br>    # Iterate through test set minibatchs <br>    for images, labels in tqdm(test_loader):<br>        # Forward pass<br>        x = images.view(-1, 28*28)<br>        y = torch.matmul(x, W) + b<br>        <br>        predictions = torch.argmax(y, dim=1)<br>        correct += torch.sum((predictions == labels).float())<br>    <br>print(&#39;Test accuracy: {}&#39;.format(correct/total))</pre><p>Note: The accuracy from the full version directly above might return a slightly different test accuracy from the step-by-step version we first went through. We trained our model with stochastic gradient descent (SGD), with the word “stochastic” highlighting that training is an inherently random process.</p><h3>Higher-level APIs</h3><p>So far, we’ve primarily been building neural networks with fairy basic PyTorch operations. We did this to provide a clearer picture of how models actually work and what’s going on under the hood. This can be important as you’re learning concepts and the various frameworks, and sometimes the low-level control is necessary if you’re trying to build something novel.</p><p>However, most of the time, we do find ourselves repeating the same fairly standard lines of code, which can slow us down. Worse, it clutters up our code unnecessarily and introduces room for bugs and typos. And finally, as researchers or engineers, we would like to spend most of our time thinking on the highest levels of abstractions: I want to add a convolution layer here, then a fully-connected there, etc. Having to code all the small details are distractions that can detract from our ability to translate ideas into code. For this reason, PyTorch has higher-level abstractions to help speed up implementation and improve model organization. While there are many ways to organize PyTorch code, one common paradigm is with torch.nn.Module.</p><h4>Object-oriented Refactorization</h4><p>It often makes sense for us to code our models in an <a href="https://realpython.com/python3-object-oriented-programming/">object-oriented manner</a>. To understand why to let’s look back at the linear transformation 𝑦=𝑥W+𝑏 that we used for logistic regression. We can see that while the operation consisted of matrix multiplication and addition, also associated with this operation was the instantiation of two parameters W and b, and these two parameters conceptually <em>belong</em> to the transform. As such, it would make sense to bundle up the instantiation of the two parameters with the actual transformation:</p><pre># Note: illustrative example only; see below for torch.nn usage<br>class xW_plus_b:<br>    def __init__(self, dim_in, dim_out):<br>        self.W = torch.randn(dim_in, dim_out)/np.sqrt(dim_in)<br>        self.W.requires_grad_()<br>        self.b = torch.zeros(dim_out, requires_grad=True)<br>        <br>    def forward(self, x):<br>        return torch.matmul(x, self.W) + self.b</pre><p>To use what we just wrote, we can create an xW_plus_b instance using its __init__() method (the constructor). In this case, we&#39;re going to set the dimensions to be 784 and 10, as we did in our logistic regression example above. This creates an xW_plus_b instance with two parameters W and b.</p><pre># Note: illustrative example only; see below for torch.nn usage<br>lin_custom = xW_plus_b(784, 10)<br>print(&quot;W: {}&quot;.format(lin_custom.W.shape))<br>print(&quot;b: {}&quot;.format(lin_custom.b.shape))</pre><p>After instantiating the instance, we can perform the actual linear transform of our custom xW_plus_b class by calling the instance&#39;s forward() function:</p><pre># Note: illustrative example only; see below for torch.nn usage<br>x_rand = torch.randn(1,784)<br>y = lin_custom.forward(x_rand)<br>print(y.shape)</pre><h4>Using torch.nn</h4><p>While we can certainly implement our own classes for the operations we’d like to use, we don’t have to, as PyTorch already has them in the torch.nn sublibrary.</p><pre>import torch.nn as nn</pre><p>For example, the linear transform example we just went through is called torch.nn.Linear:</p><pre>lin = nn.Linear(784, 10)<br>print(&quot;Linear parameters: {}&quot;.format([p.shape for p in lin.parameters()]))</pre><pre>y = lin(x_rand)<br>print(y.shape)</pre><p>The implementation nn.Linear has a few more things under the hood (notice for example that the forward() function is aliased with calling the instance itself), but in spirit, it operates in much the same way as our custom xW_plus_b class. In the first line, we instantiate an Linear object, which automatically creates weight and bias variables of the specified dimensions. The fourth line then calls the forward() function (aliased with the object call), which performs the linear transformation.</p><h4>Using torch.nn.Module</h4><p>The torch.nn.Linear the class we just saw is a subclass of torch.nn.Module. However, Modules do not have to just describe a single operation; they can also define a chain of operations, each of which may also be Modules. As such, we can place our entire neural network within a Module. In this case, the module can track all of its associated parameters, some of which may also be associated with a submodule (e.g. nn.Linear), while also defining the forward() function, in one place.</p><pre>class MNIST_Logistic_Regression(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.lin = nn.Linear(784, 10)</pre><pre>def forward(self, x):<br>        return self.lin(x)</pre><p>In this particular example, we didn’t need to chain any operations, but we’ll see this come in handy as we move on to more complex models. Additionally, the nn.Module that we subclassed has a few other nice features. For example:</p><ul><li>The forward() function of a nn.Module will call the forward() the function of any child nn.Modules.</li><li>print() will print out a formatted summary of our model, recursively summarizing any child nn.Modules as well.</li><li>The parameters() the function will return a generator that returns all parameters of an nn.Module (including those of any children).</li></ul><pre>model = MNIST_Logistic_Regression()<br>y = model(x_rand)<br>print(&quot;The model: \n{}&quot;.format(model))<br>print(&quot;\nParameters: \n{}&quot;.format(list(model.parameters())))<br>print(&quot;\nOutput shape: \n{}&quot;.format(y.shape))</pre><h4>Full code with nn.Module</h4><p>Refactoring our previous complete logistic regression code to use a nn.Module:</p><pre>import numpy as np<br>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>from torchvision import datasets, transforms<br>from tqdm.notebook import tqdm</pre><pre>class MNIST_Logistic_Regression(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        self.lin = nn.Linear(784, 10)</pre><pre>def forward(self, x):<br>        return self.lin(x)</pre><pre># Load the data<br>mnist_train = datasets.MNIST(root=&quot;./datasets&quot;, train=True, transform=transforms.ToTensor(), download=True)<br>mnist_test = datasets.MNIST(root=&quot;./datasets&quot;, train=False, transform=transforms.ToTensor(), download=True)<br>train_loader = torch.utils.data.DataLoader(mnist_train, batch_size=100, shuffle=True)<br>test_loader = torch.utils.data.DataLoader(mnist_test, batch_size=100, shuffle=False)</pre><pre>## Training<br># Instantiate model<br>model = MNIST_Logistic_Regression()</pre><pre># Loss and Optimizer<br>criterion = nn.CrossEntropyLoss()<br>optimizer = torch.optim.SGD(model.parameters(), lr=0.1)</pre><pre># Iterate through train set minibatchs <br>for images, labels in tqdm(train_loader):<br>    # Zero out the gradients<br>    optimizer.zero_grad()<br>    <br>    # Forward pass<br>    x = images.view(-1, 28*28)<br>    y = model(x)<br>    loss = criterion(y, labels)<br>    # Backward pass<br>    loss.backward()<br>    optimizer.step()</pre><pre>## Testing<br>correct = 0<br>total = len(mnist_test)</pre><pre>with torch.no_grad():<br>    # Iterate through test set minibatchs <br>    for images, labels in tqdm(test_loader):<br>        # Forward pass<br>        x = images.view(-1, 28*28)<br>        y = model(x)<br>        <br>        predictions = torch.argmax(y, dim=1)<br>        correct += torch.sum((predictions == labels).float())<br>    <br>print(&#39;Test accuracy: {}&#39;.format(correct/total))</pre><p>While the benefits of organizing a model as a nn.Module may not be as obvious for a simple logistic regression model, such a programming style allows for much quicker and cleaner implementations for more complex models.</p><p>Once you have reached this sentence you have gone through all steps to build a very simple neural network in PyTorch to do handwritten digit classification.</p><p>Here is a summary of your accomplishment today:</p><ul><li><strong>MNIST Dataset</strong></li><li><strong>Logistic Regression Model: The forward pass, The cross-entropy loss, The backward pass</strong></li><li><strong>Model Training</strong></li><li><strong>Model Testing</strong></li><li><strong>Higher-level APIs: Object-oriented Refactorization, torch.nn.Module</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeef32c7a94" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/handwritten-digit-classification-using-neural-network-in-pytorch-eeef32c7a94">Handwritten digit classification using neural network in Pytorch</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python prerequisites to kick start your Machine Learning journey]]></title>
            <link>https://levelup.gitconnected.com/python-prerequisites-to-kick-start-your-machine-learning-journey-bd5d4fbf936f?source=rss-b9416d02a1b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5d4fbf936f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matplotlib]]></category>
            <dc:creator><![CDATA[Harsh Panchal]]></dc:creator>
            <pubDate>Tue, 01 Jun 2021 13:44:50 GMT</pubDate>
            <atom:updated>2021-06-01T13:44:50.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFHl1oYU172x7BIL4T1naQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaryanphoto">Joshua Reddekopp</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>Welcome to an Illustrated Guide on python prerequisites. This walk provides a comprehensive overview of the Python programming language features you will need to master for starting a basic machine learning journey. This guide includes lists, tuples, dictionaries, for-loops, if-statements, NumPy, and MatPlotLib.</p><h3><strong>1. Variables</strong></h3><p>In Python, we store all the pieces of data — numbers, characters, strings, everything — as objects, and refer to these objects using a variable. As a simple case, we can assign a variable value using an assignment operator, which is an “equal” sign:</p><pre>x = 1<br>y = 2<br>z = x + y<br>print(z)<br></pre><p>Note that we can make an assignment using certain values — such as assigning 1 in variable x and 2 in variable y — and we can give a value concerning other variables — such as variable in z the sum of x and y.</p><h3><strong>2. Collections</strong></h3><p>Python Collections allow us to place multiple data objects in one object that we can access or work across. There are a variety of built-in collections, and we will discuss three of them: lists, tuples, and dictionaries. Later, we will introduce another method of data collection using arrays from a library called NumPy.</p><p><strong>A. Lists</strong></p><p>The list contains a sequence of objects, usually represented by square brackets with commas between objects in the order in which they are listed below:</p><pre>list = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;]</pre><p>The above, <em>list</em> contains the order of the characters. The list, however, includes items for a variety of objects:</p><pre>varied_list = [&#39;a&#39;, 2, &#39;b&#39;, 3.14] # a list with elements of char, integer, and float types</pre><pre>nested_list = [&#39;hello&#39;, &#39;Harsh&#39;, [1.618, 42]] # a list within a list!</pre><p>Lists allow for so-called indexing, where a specific item of the list can be found. For example, say you wanted to grab the second element of varied_list above.</p><pre>second_element = varied_list[1]<br>print(second_element)</pre><p>Python is a so-called programming language with zero indexing. This simply means that the “first” item in the list or other data collection is displayed using “0” (zero) rather than “1”. That’s why, above, we capture the second varied_list item using the full index “1” instead of “2” as some might expect in a single reference language (such as Matlab).</p><p>Another feature of python indexing that facilitates the use of negative indexing. As we discussed above, the “first” item of the python list is indicated by the “0” index; therefore, it is probably natural to view the last item in the list as being indexed by “-1”. See the following examples of negative indexing:</p><pre>last_element = list[-1] #to print the last element of list<br>print(last_element)</pre><pre>last_element_2 = list[len(list)-1] #to print also the last element of list<br>print(last_element_2)</pre><pre>second_to_last_element = list[-2] #to print second to last element of list<br>print(second_to_last_element)</pre><p>Similar to indexing is list slicing, where the merging section of the list can be reached. A colon (:) is used to make a slice, with numbers that describe the positions that should start and end a piece. Below, we show that the beginning or end of a piece value can be omitted when a person slice from the beginning or end of a list. Also, note below that the slide start guide is included in the piece, but the slide end indicator is not included.</p><pre>NFL_list = [&quot;Charger&quot;, &quot;Bronco&quot;, &quot;Raider&quot;, &quot;Chief&quot;, &quot;Panther&quot;, &quot;Falcon&quot;, &quot;Cowboy&quot;, &quot;Eagle&quot;]</pre><pre>AFC_west_list = NFL_list[:4] # Slice to grab list indices 0, 1, 2, 3 -- &quot;Charger&quot;, &quot;Bronco&quot;, &quot;Raider&quot;, &quot;Chief&quot;<br>print(AFC_west_list)</pre><pre>NFC_south_list = NFL_list[4:6] # Slice list indices 4, 5 -- &quot;Panther&quot;, &quot;Falcon&quot;<br>print(NFC_south_list)</pre><pre>NFC_east_list = NFL_list[6:] # Slice list indices 6, 7 -- &quot;Cowboy&quot;, &quot;Eagle&quot;<br>print(NFC_east_list)</pre><p><strong>B. Tuples</strong></p><p>The tuple is a Python collection that is very similar to the list, with some subtle differences. For starters, tuples are shown using parenthesis instead of square brackets:</p><pre>x = 2<br>y = 3<br>coordinates = (x, y)</pre><p>The dynamic coordinates above are Tuple containing the variables x and y. This example was chosen to show again the differences between the general use of tuples compared to the list. While lists are often used to contain items of the same value in some sense, tuples are often used to contain the corresponding unit attribute. For example, as above, it makes sense to treat point links as a single unit. As another example, consider the following Tuple and the list of dates:</p><pre>year1 = 2022<br>month1 = &quot;May&quot;<br>day1 = 15<br>date1 = (month1, day1, year1)<br>year2 = 2021<br>month2 = &quot;June&quot;<br>day2 = 17<br>date2 = (month2, day2, year2)<br>years_list = [year1, year2]</pre><p>Note above that we have collected the attributes of one date into one Tuple: those pieces of information all define one “unit”. In contrast, in the list of years, we have collected different years in the code-snippet: the list values are the same (they are both years), but they do not define the same unit.</p><p>The difference I draw between the tuples and the list here is that which most Python programmers do, but not the one that is strictly enforced (i.e., you won’t find errors if you break this assembly!). Another subtle variation of tuples and lists includes the so-called Python mutability of variables. Mutability is so complex that we do not need to discuss it in our Python guide, but interested people are encouraged to read it further if they wish!</p><p><strong>C. Dictionaries</strong></p><p>Now that you’ve seen the parenthesis (for tuple) and the square brackets (for lists), you may be wondering what curly brackets are used for. Answer: Python dictionaries. The descriptive feature of the Python dictionary is that it has keys and related values. When defining a dictionary, this organization can be achieved using color (:) as done below:</p><pre>book_dictionary = {&quot;Title&quot;: &quot;Ulysses&quot;, &quot;Author&quot;: &quot;James Joyce&quot;, &quot;Year&quot;: 1818}</pre><pre>print(book_dictionary[&quot;Author&quot;])</pre><p>In addition, the keys to the book_dictionary are “Title”, “Author”, and “Year”, and each of these keys has the corresponding value. Note that key-value pairs are separated by commas. Using the keys allows us to access a dictionary clip by name, rather than needing to know the index of the passage we want, as is the case with lists and tuple. For example, above we might find Ulysses’s author using the “Author” key, instead of using the index. In fact, unlike a list or a Tuple, the order of the items in the dictionary does not matter, and dictionaries cannot be identified using numbers, which we see below when we try to reach the second item in the dictionary using the whole number:</p><pre>print(book_dictionary[1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*BqvcfW2UHPsF2q8XabCpjA.png" /><figcaption>Image by author</figcaption></figure><h3><strong>3. Control Flow</strong></h3><p>Like many popular programming languages, Python offers several ways to control the flow of execution within the system. Here, we will present the looping and conditional statements.</p><p>In the meantime, it’s important to let you know about a unique feature of Python language: indentation. While language like C uses curly braces to contain code statements within loops or conditionals, Python displays these statements by indentation. This feature lends readability to Python code, as you’ll see in the examples below.</p><p><strong>A. For-Loops</strong></p><p>Looping statements allow for repeated execution of code. For example, suppose we want to add all the numbers between zero (0) and ten (10), not including ten. Yes, we can do this in one line, but we can also use the loop to add one value at a time. Below is a simple link code that accompanies:</p><pre>sum = 0<br>for i in range(10):<br>    sum = sum + i<br>print(sum)<br>alternative_sum = 0+1+2+3+4+5+6+7+8+9<br>print(alternative_sum==sum)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/52/1*YHelVmxqHDrfOl8POtFgHA.png" /><figcaption>Image from author</figcaption></figure><p>The built-in range () function produces a sequence of values that we loop over, and note that the range (10) does not include 10 itself. In addition to looping through numbers using the range () function, we can also sort items listed, shown below:</p><pre>ingredients = [&quot;flour&quot;, &quot;sugar&quot;, &quot;eggs&quot;, &quot;oil&quot;, &quot;soda&quot;]<br>for ingredient in ingredients:<br>print(ingredient)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*Og8MRzxEkRLczuCblTHzeQ.png" /><figcaption>Image from author</figcaption></figure><p>In addition, the for-loop runs on top of the list of ingredients, and inside each loop of these items is called an ingredient. The use of singular/plural nouns to manage this iteration is a standard Python motif, but you do not need to use it in your program.</p><p><strong>B. Conditionals</strong></p><p>Usually when making a Program, one will want to execute only certain parts of the code where certain conditions are met, for example, when the variable has a certain value. This is accomplished using conditional statements: if, elif, else.</p><pre>for i in range(10):<br>    if i % 2 == 0: # % -- modulus operator -- returns the remainder after division<br>        print(&quot;{} is even&quot;.format(i))<br>    else:<br>        print(&quot;{} is odd&quot;.format(i))<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*FX9Ers51zggJG7l_T_iP0g.png" /><figcaption>Image from author</figcaption></figure><pre># Example of elif <br># Print the meteorological season for each month <br>print(&quot;In the Northern Hemisphere: \n&quot;)<br>month_integer = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] # i.e., January is 1, February is 2, etc...<br>for month in month_integer:<br>    if month &lt; 3:<br>        print(&quot;Month {} is in Winter&quot;.format(month))<br>    elif month &lt; 6:<br>        print(&quot;Month {} is in Spring&quot;.format(month))<br>    elif month &lt; 9:<br>        print(&quot;Month {} is in Summer&quot;.format(month))<br>    elif month &lt; 12:<br>        print(&quot;Month {} is in Fall&quot;.format(month))<br>    else: # This will put 12 (i.e., December) into Winter<br>        print(&quot;Month {} is in Winter&quot;.format(month))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*mDy2UkKjNRqfMMbkbOzRHw.png" /><figcaption>Image from author</figcaption></figure><h3><strong>4. List Comprehension</strong></h3><p>Python allows list comprehension where list elements are organized across a single line of code. Say, for example, that you wanted to add 1 to each item in the list of whole values. You can do this using the listing as follows:</p><pre>even_list = [2, 4, 6, 8]<br>odd_list = [even+1 for even in even_list]<br>print(odd_list)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*kVE16-ONvrkT8gp0DIbFbw.png" /><figcaption>Image from author</figcaption></figure><p>Note from above the similarities between the understanding of the list compensation and for loop; Python has a list compensation as a compact, “Pythonic” method for performing tasks that can be performed within a loop.</p><h3><strong>5. NumPy Library</strong></h3><p>NumPy’s library offers Python a wide range of scientific computing skills. Central to this is the Array object, which offers a different way of arranging values of the same type. Numpy layouts allow cutting and indexing similar to lists. Most importantly, Numpy has a tremendous amount of mathematical functions that can transform arrays and perform calculations between arrays. For those familiar with MatLab, these activities should be reminiscent of multiple matrix functions.</p><pre>import numpy as np</pre><pre>x = np.array([2, 4, 6]) # create a rank 1 array<br>A = np.array([[1, 2, 3], [4, 5, 6]]) # create a rank 2 array<br>B = np.array([[1, 2, 3], [4, 5, 6]])</pre><pre>print(&quot;Matrix A: \n&quot;)<br>print(A)</pre><pre>print(&quot;\nMatrix B: \n&quot;)<br>print(B)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*y8kyEXVS2ECV85dkWJdz2A.png" /><figcaption>Image from author</figcaption></figure><pre># Indexing/Slicing examples<br>print(A[0, :]) # index the first &quot;row&quot; and all columns<br>print(A[1, 2]) # index the second row, third column entry<br>print(A[:, 1]) # index entire second column<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/80/1*P8-wvz1k4akBnpc7h7HDVA.png" /><figcaption>Image from author</figcaption></figure><pre># Arithmetic Examples<br>C = A * 2 # multiplies every elemnt of A by two<br>D = A * B # elementwise multiplication rather than matrix multiplication<br>E = np.transpose(B)<br>F = np.matmul(A, E) # performs matrix multiplication -- could also use np.dot()<br>G = np.matmul(A, x) # performs matrix-vector multiplication -- again could also use np.dot()</pre><pre>print(&quot;\n Matrix E (the transpose of B): \n&quot;)<br>print(E)</pre><pre>print(&quot;\n Matrix F (result of matrix multiplication A x E): \n&quot;)<br>print(F)</pre><pre>print(&quot;\n Matrix G (result of matrix-vector multiplication A*x): \n&quot;)<br>print(G)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*2ZXTjZT9qK2lhT-fAinpDA.png" /><figcaption>Image from author</figcaption></figure><pre># Broadcasting Examples<br>H = A * x # &quot;broadcasts&quot; x for element-wise multiplication with the rows of A<br>print(H)<br>J = B + x # broadcasts for addition, again across rows<br>print(J)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*99xcMprHokeEHmI0qBMrMA.png" /><figcaption>Image from author</figcaption></figure><pre># max operation examples</pre><pre>X = np.array([[3, 9, 4], [10, 2, 7], [5, 11, 8]])<br>all_max = np.max(X) # gets the maximum value of matrix X<br>column_max = np.max(X, axis=0) # gets the maximum in each column -- returns a rank-1 array [10, 11, 8]<br>row_max = np.max(X, axis=1) # gets the maximum in each row -- returns a rank-1 array [9, 10, 11]</pre><pre># In addition to max, can similarly do min. Numpy also has argmax to return indices of maximal values<br>column_argmax = np.argmax(X, axis=0) # note that the &quot;index&quot; here is actually the row the maximum occurs for each column</pre><pre>print(&quot;Matrix X: \n&quot;)<br>print(X)<br>print(&quot;\n Maximum value in X: \n&quot;)<br>print(all_max)<br>print(&quot;\n Column-wise max of X: \n&quot;)<br>print(column_max)<br>print(&quot;\n Indices of column max: \n&quot;)<br>print(column_argmax)<br>print(&quot;\n Row-wise max of X: \n&quot;)<br>print(row_max)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*2dr4cQUPBZXHYOfGJdt9UA.png" /><figcaption>Image from author</figcaption></figure><pre># Sum operation examples<br># These work similarly to the max operations -- use the axis argument to denote if summing over rows or columns</pre><pre>total_sum = np.sum(X)<br>column_sum = np.sum(X, axis=0)<br>row_sum = np.sum(X, axis=1)</pre><pre>print(&quot;Matrix X: \n&quot;)<br>print(X)<br>print(&quot;\n Sum over all elements of X: \n&quot;)<br>print(total_sum)<br>print(&quot;\n Column-wise sum of X: \n&quot;)<br>print(column_sum)<br>print(&quot;\n Row-wise sum of X: \n&quot;)<br>print(row_sum)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*n2Abe-6dhzi5CLIwMdp9QA.png" /><figcaption>Image from author</figcaption></figure><pre># Matrix reshaping</pre><pre>X = np.arange(16) # makes a rank-1 array of integers from 0 to 15<br>X_square = np.reshape(X, (4, 4)) # reshape X into a 4 x 4 matrix<br>X_rank_3 = np.reshape(X, (2, 2, 4)) # reshape X to be 2 x 2 x 4 --a rank-3 array<br>                                    # consider as two rank-2 arrays with 2 rows and 4 columns<br>print(&quot;Rank-1 array X: \n&quot;)<br>print(X)<br>print(&quot;\n Reshaped into a square matrix: \n&quot;)<br>print(X_square)<br>print(&quot;\n Reshaped into a rank-3 array with dimensions 2 x 2 x 4: \n&quot;)<br>print(X_rank_3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*m-O7pbW2tnlxMhcGoXVbGw.png" /><figcaption>Image from author</figcaption></figure><h3><strong>6. Plotting</strong></h3><p>Much of the plotting you will do will be in the Matplotlib library, especially within the pyplot module. Properly named, the plot function is used to edit 2-D data, as shown below:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre># let’s start with parabola<br># Compute the parabola’s x and y coordinates<br>x = np.arange(-4, 4, 0.1)<br>y = np.square(x)</pre><pre># matplotlib for the plot<br>plt.plot(x, y, ‘b’) # color blue for the line<br>plt.xlabel(‘X-Axis Values’)<br>plt.ylabel(‘Y-Axis Values’)<br>plt.title(‘First Plot: A Parabola’)<br>plt.show() # display the plot</pre><figure><img alt="Image by author" src="https://cdn-images-1.medium.com/max/552/1*A9C957RhaaqmI2nTozj75g.png" /><figcaption>Image by author</figcaption></figure><p>Another function of Matplotlib you will encounter is an imshow used to display images. Remember that an image can be considered the array, with the elements showing the image&#39;s pixel values. As a simple example, here is the identity matrix:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre>X = np.identity(5)<br>identity_matrix_image = plt.imshow(X, cmap=”Greys_r”)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*rLZxJnPKY91iro-x5qEqRw.png" /><figcaption>Image by author</figcaption></figure><pre># plotting a random matrix, with a different colormap<br>A = np.random.randn(5, 5)<br>random_matrix_image = plt.imshow(A)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*rbk7O3HiEwJY38uaolkW8g.png" /><figcaption>Image by author</figcaption></figure><p>Once you have reached this sentence you have gone through all the python prerequisites for your exciting machine learning journey.</p><p>Here is a summary of your accomplishment today:</p><ol><li><strong>Variables</strong></li><li><strong>Collections: Lists, Tuples, Dictionaries</strong></li><li><strong>Control loops: For-loops, if-elif-else conditions</strong></li><li><strong>List compensation</strong></li><li><strong>Numpy</strong></li><li><strong>Plotting</strong></li></ol><h3>Level Up Coding</h3><p>Thanks for being a part of our community! <a href="https://www.youtube.com/channel/UC3v9kBR_ab4UHXXdknz8Fbg?sub_confirmation=1">Subscribe to our YouTube channel</a> or join the <a href="https://skilled.dev/"><strong>Skilled.dev coding interview course</strong></a>.</p><p><a href="https://skilled.dev/">Coding Interview Questions + Land Your Dev Job | Skilled.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5d4fbf936f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/python-prerequisites-to-kick-start-your-machine-learning-journey-bd5d4fbf936f">Python prerequisites to kick start your Machine Learning journey</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>