<?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 n0obcoder on Medium]]></title>
        <description><![CDATA[Stories by n0obcoder on Medium]]></description>
        <link>https://medium.com/@animesh7pointer?source=rss-17fda0baf966------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Jkk7ATR93FQcQnTVaWdRQg.jpeg</url>
            <title>Stories by n0obcoder on Medium</title>
            <link>https://medium.com/@animesh7pointer?source=rss-17fda0baf966------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:14:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@animesh7pointer/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[Wynk Radio: The ML Behind India’s Seamless Streams]]></title>
            <link>https://medium.com/airteldigital/wynk-radio-the-ml-behind-indias-seamless-streams-a39a1f79b75c?source=rss-17fda0baf966------2</link>
            <guid isPermaLink="false">https://medium.com/p/a39a1f79b75c</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[music-recommendations]]></category>
            <category><![CDATA[session-based-recommender]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[wynk-music]]></category>
            <dc:creator><![CDATA[n0obcoder]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 11:17:18 GMT</pubDate>
            <atom:updated>2023-11-14T12:39:24.633Z</atom:updated>
            <content:encoded><![CDATA[<p>Launched in 2014, <a href="https://wynk.in/music">Wynk Music</a>, a part of Airtel Digital Limited, is currently the #1 music streaming app in India in terms of downloads and daily active users. The music catalog offers 22 million+ songs in major global &amp; Indian regional languages. With 75 million monthly active users, and more than 100 million installs, Wynk Music continues to be India’s favorite music streaming app!</p><p>In this blog we will understand the role of Machine Learning in developing a recommender system that learns the music preferences of a user, and recommends best suited songs to them. The blog also puts light on the challenges that come along the way, and of course their solutions.</p><h3>Wynk Radio</h3><p>It is the brand new player in the Wynk App, which is powered by deep-learning based Next-Song-Prediction model. The new player brings entirely new listening and browsing experience to the users.</p><p>Its contemporary swipe-based navigation, coupled with our recommender system, makes finding favourite tunes effortless.</p><p>With uninterrupted playback, music flows smoothly, creating a cohesive and user-friendly experience. Even more impressively, Wynk Radio offers automated song recommendations that align with the changing preferences of the users, without requiring the entire listening history of the user.</p><p>Rendering the manual selection of songs obsolete, Wynk Radio takes care of the song preferences for the users. It lets users enjoy a tailored and uninterrupted music journey.</p><h3>Session-Based Recommender System</h3><p>It is a type of recommendation system designed to provide personalised recommendations for users based on their short-term behaviour or the current session.</p><p>Unlike traditional recommendation systems that rely on long-term user histories and preferences, session-based recommender systems focus and adapt to the user’s immediate context and behaviour within a single session.</p><h3>Next-Song-Prediction Model</h3><p>Being the Session-Based Recommender System that generates all the recommendations, NSP is truly the heart of the Wynk Radio.</p><p>It is an LSTM-based deep learning model that captures the preferences of a user, from the songs consumed in the session. It predicts the next song most likely to be consumed by a user, in an ongoing session by understanding and adapting to the changing preferences of a user in the that session.</p><blockquote>NSP Model showed <strong>~10% boost</strong> in streams per subscriber over the previous ML model in production</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgDvX9Gi5Zna4jtnj2s7Ww.png" /></figure><h3>Data Preparation for NSP Model</h3><p>Streaming of songs with an inactivity of less than 30 minutes is called a session. This sessions dataset is used for preparing the training and evaluation sets for NSP model.</p><p>Four weeks of streaming data is used for preparing the training set and next few days is used for preparing the evaluation set to make sure that there is no data leakage in the evaluation step.</p><p>There is a set of very popular songs having very high stream counts. Such popular songs have a clear dominance over the other songs in terms of occurrences. This results in popularity-bias in NSP model when trained on this data. The model learns to predict the most popular songs ignoring the other songs which might be equally relevant, or even more, in the session. This problem is tackled through data sampling techniques.</p><h3>Architecture of Next-Song-Prediction Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*SQ25wxqJ3wJyrENUzE6AUw.png" /></figure><p>Sequences of song IDs are the inputs to the model. There are two of such sequences for a session. One consists the songs that have been consumed (stream time ≥ 30 sec), and the other consists of the skipped songs (stream time &lt; 30 sec).</p><p>Then they are converted to song embeddings by making use of the Embedding Layer. The embeddings are then sent to the LSTM layer along with the hidden states. These hidden states are nothing but vectors representing the complete sequence till a particular time-step.</p><p>The output of the LSTM layers are passed through a series of Dense Layers, last of which is the classification layer that assigns probability scores for all the songs in the vocabulary.</p><h3>What is LSTM?</h3><p>Standing for <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">Long Short-Term Memory</a>, it is a type of artificial intelligence algorithm. It is good at understanding patterns in sequences of data. It makes predictions based on what it has seen before and what’s happening now. It is very useful for tasks like predicting the next word in a sentence or the next song in a session.</p><p>LSTM can theoretically handle sequential inputs of any length. LSTM has internal states which update for inputs of every time-step. These states are vectors containing floating point numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKhwsOYNUT5xU7Pyf6Znhg.png" /></figure><p>The LSTM layer forgets the irrelevant information, updates the hidden states with new inputs, and passes on the updates hidden states to the next time-step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*tbwxj-bO5jaAk3L4spwMqg.png" /></figure><h3>The Softmax Function</h3><p>It takes an input vector and transforms it into a set of values, a probability distribution, that sums up to 1. It is a great way to perform a classification task.</p><p>Computation involves exponentiating and normalising each element in the input vector. Like every great thing, Softmax also has its own limitations.</p><p>As the size of vocabulary increases, the computational cost of these operations grows significantly, leading to slower training and inference times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*2fIltNetCVXaVVAslN8ERg.png" /></figure><h3>Sampled-Softmax to the Rescue!</h3><p><a href="https://douglasorr.github.io/2021-10-training-objectives/3-sampled/article.html">Sampled-Softmax</a> fixes the limitation of plain softmax function. It is a technique used to address the computational and memory inefficiencies associated with using the full softmax function in the case of a large vocabulary size.</p><p>This is done by approximating the computation of the full softmax by considering only a small subset of classes (i.e. song IDs) from the entire vocabulary. It is a faster alternative of full softmax, with reasonable accuracy.</p><h3>Training and Evaluation of NSP Model</h3><p>The model training is powered by the formidable processing capabilities of multiple NVIDIA GPUs, enabling us to accelerate the training process and achieve impressive results</p><p>Every machine learning model needs to be evaluated on an evaluation set, and it is done by using suitable metrics. The main metrics used to evaluate the NSP model are Short-Term Prediction Score (SPS) and Recall.</p><h3>How is NSP Model Evaluated?</h3><p>The evaluation set consists of tens of thousand of test sequences or user sessions. These sequences are split at the centre. The first half of these sequences are the inputs to the model and the second half of these sequences are the ground truths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*ACEptfwN3EVQ7PLKg09A8g.png" /><figcaption>A test sequence with 8 items is split into two halves, input and ground-truth</figcaption></figure><h4>Short-term Prediction Success (SPS)</h4><p>SPS captures the ability of the model to predict the next item in the sequence, the ground truth. SPS is 1 if the next item (i.e. the first item in the second half of the test sequence) is present in the top_k recommendations, else 0.</p><p>For example, if the top 5 predictions from the model are [1, 3, 5, 7, 9], and the next item in the sequence is 7, then the SPS@5 is 1.<br>The final SPS is the average SPS for all the sequences in the eval set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*tiitU9QW3daXbC0XnjHbig.png" /></figure><h4>Recall</h4><p>It is defined as the number of correct recommendations divided by the number of unique items in second half of the test sequence, ground truth.</p><p>For example, if the top 5 predictions from the model are [1, 3, 5, 7, 9], and the second half of the sequence is [3, 3, 8, 10], then the recall@5 is 0.33.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIUTgpCnS5ZFUAT523nQfw.png" /></figure><h3>Deploying the Model</h3><p>NSP has been written in TensorFlow and it makes compatible to be deployed using TensorFlow Serving.</p><p>TensorFlow Serving offers a lot of benefits-</p><ul><li>Batching Parameters: TensorFlow Serving allows you to specify batching parameters when you configure a serving deployment.</li><li>Scalability: Designed for high performant throughput</li><li>Model Versioning: Supports easy management and deployment of different versions of machine learning models.</li><li>Flexible Deployment: Allows serving multiple models simultaneously, enabling A/B testing and experimentation.</li><li>Platform Agnostic: Works across different platforms and deployment environments, making it versatile for various deployment scenarios.</li></ul><h3>Problem of Predictability and its Solution</h3><p>Because of the nature of the model, the next song is predicted by picking up the item with highest probability. This means that for a fixed input, there would always be a fixed output. The output of the model is deterministic.</p><p>We use a technique called <a href="https://medium.com/mlearning-ai/softmax-temperature-5492e4007f71"><strong>Temperature-Based Sampling</strong></a> to introduce a little variety to the model outputs. Temperature is like a knob that can be adjusted to change probability distribution coming from the softmax function, and in turn, the quality of model’s outputs.</p><p>Higher temperature values (&gt; 1.0) make the output more random and varied, leading to a surprising and creative output. A very high value of temperature can make the probability distribution a uniform distribution adversely affecting the quality of the recommendations. Lower temperature values (&lt; 1.0) make the output more focused and deterministic, producing more predictable and controlled content.</p><p>Temperature needs to be adjusted on the basis of desired level of creativity and coherence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*vMxWWjq3Jit5ocJs1D1n5w.png" /></figure><h3>Long-Tail and OOV Items Handling</h3><p>The items in the vocabulary with low stream counts are called long-tail items. And the items which are not present in the vocabulary of the model are called out-of-vocab (OOV) items.</p><p>If long-tail or OOV items, are given as input to the NSP model, recommendation is generated by a fallback logic, the similar-songs model based on the <a href="https://medium.com/datadriveninvestor/word2vec-skip-gram-model-explained-383fa6ddc4ae">word2vec model</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*csNodUIjDXjLl076tKGt_A.png" /></figure><h3>Use of Skip-Signals</h3><p>Streaming of songs for less than 30 seconds is considered as a skip. A skipped song, shows a negative intent from the user. Despite being an indicator of negative intent from a user, it is a very strong signal for understanding users’ preferences in a session.</p><blockquote>NSP-with-skips showed a relative gain of <strong>~5%</strong> in SPS against NSP w/o skips</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4PkWcDeFw-ctGf9OnlNcA.png" /></figure><h3>Other Possible Use Cases</h3><h4>Song Radio</h4><p>One single song, a seed song, can be used to start a song radio which could generate a mix of songs, well-suited to be consumed in a session.</p><h4>Recommendations for User-Generated Playlists</h4><p>On Wynk, users can create and modify their custom playlists. NSP can be used to recommend songs to be added in such playlists, making it easier for the users to expand their existing playlists, maintaining the theme or the feel of the playlist at the same time.</p><p><em>Get in the groove with India’s Topmost rated App that can be downloaded from </em><a href="https://apps.apple.com/in/app/wynk-music-songs-podcasts/id845083955"><em>App Store</em></a><em> &amp; </em><a href="https://play.google.com/store/apps/details?id=com.bsbportal.music&amp;hl=en_US"><em>Play Store</em></a><em>.</em></p><p><em>Feel free to reach out to </em><a href="https://www.linkedin.com/in/vipulgaba/"><em>Vipul Gaba</em></a><em> and </em><a href="https://www.linkedin.com/in/animesh-animesh-b9a297b6/"><em>Animesh</em></a><em> for any feedback on Wynk Radio.</em></p><h3>References</h3><ol><li><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">https://colah.github.io/posts/2015-08-Understanding-LSTMs/</a></li><li><a href="https://douglasorr.github.io/2021-10-training-objectives/3-sampled/article.html">https://douglasorr.github.io/2021-10-training-objectives/3-sampled/article.html</a></li><li><a href="https://medium.com/@imisri1/how-to-set-sampling-temperature-for-gpt-models-762887df1fac">https://medium.com/@imisri1/how-to-set-sampling-temperature-for-gpt-models-762887df1fac</a></li><li><a href="https://medium.com/datadriveninvestor/word2vec-skip-gram-model-explained-383fa6ddc4ae">https://medium.com/datadriveninvestor/word2vec-skip-gram-model-explained-383fa6ddc4ae</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a39a1f79b75c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airteldigital/wynk-radio-the-ml-behind-indias-seamless-streams-a39a1f79b75c">Wynk Radio: The ML Behind India’s Seamless Streams</a> was originally published in <a href="https://medium.com/airteldigital">Airtel Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alias in Windows and it’s Fun Applications using Python]]></title>
            <link>https://medium.com/analytics-vidhya/alias-in-windows-and-its-fun-applications-using-python-5e3208b8c6b1?source=rss-17fda0baf966------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e3208b8c6b1</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[alias]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[n0obcoder]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 13:34:07 GMT</pubDate>
            <atom:updated>2022-07-23T07:41:52.246Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*naUEATohi5K2EV4mvh9VeQ.png" /><figcaption>Alias for Justice</figcaption></figure><p>I was wondering how could I possibly get a python script to run automatically every time I open the command-line. I believe that it could have some fun applications.</p><p>I imagined opening up the command-line and writing</p><p>todo “Learn Ableton Live 10”</p><p>to add “Learn Ableton Live 10” to a To-Do List (.txt file).</p><p>But how could I pull this off? I mean, obviously, the command-line does not recognize ‘todo’ command and how would I call a python script by hitting ‘todo’ anyway…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*VLv9BOHZ4YaUmLfEfQPR_w.png" /></figure><p>This is where ‘Alias’ comes into the picture!</p><h3>What is an Alias?</h3><p>An alias, as the name refers provides an alternate name for existing names. Alias is usually an easier-to-understand name for a defined data object.</p><p>For you to understand the idea of alias, I am going to say that “sup” is an alias to “wassup” which itself is an alias to “what’s up” 😛</p><p>So we are basically talking about making our own lingos in programming. Doesn’t it sound cool already? 😎</p><h3>How is Aliasing Useful?</h3><p>If you type ‘cls’ in a Windows command-line or ‘clear’ in Linux terminal and hit enter, it clears everything out from there. We could make an alias ‘c’ just to perform the same task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*vli3KMW7QbxsoxGl5qXeGA.png" /></figure><p>Also, we often have a directory which we frequently have to visit via the terminal by using the ‘cd’ command. It becomes very frustrating to use the ‘cd’ command every time we open a new terminal to enter into that directory, especially when the directory has a very long path. This is another appropriate use case of setting up an alias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*W7Anya91vIOJBGKBzF9K8w.png" /></figure><p>And similarly, we can make aliases for various different commands that are valid for a command-line.</p><h3>How to Create an Alias in Windows?</h3><p>Let’s now learn how to create an alias. Belonging to an intelligent species, you might have already figured out how to create an alias, after seeing the 2 examples that I used earlier.</p><p>You got that correct!</p><p>We use ‘doskey’ command to create an alias. We write ‘doskey’, then the alias name followed by the equal to sign (‘=’ ) further followed by the command that the alias is supposed to run.</p><h3>How to Call an Alias?</h3><p>Once we are done creating the alias, calling them is as simple as typing the name of the alias and hitting the enter key in the command-line!</p><p>Let’s see the alias ‘teleport’ that we created earlier in action now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*7tEPxnsDoEcPipbG37Vfag.png" /></figure><h3>Creating an Alias for a Python Program?</h3><p>Now that we know how to create an alias, it seems pretty straightforward to figure out the way how we can create an alias for calling a python script.</p><p>We use the ‘doskey’ command and assign the command for running a specific python script, to an alias using the equal to sign (‘=’).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*sO6Abi4pE96PWAVxyQGyWg.png" /></figure><p>Here my alias named “todo” is supposed to run the python script called “todo_list_maker.py” which is located at “C:/Users/anime/Documents/Python Scripts/todo_list_maker/”.</p><p>The python script “todo_list_maker.py” takes an input (a to-do list item) from the command-line and puts it in a todo_list.txt</p><p>But how do we pass in the arguments to our python script?</p><p>It is actually quite simple. All we need to do is add a dollar sign and an asterisk (“$*”) at the end of the alias assigning step in the way it is mentioned down below. It allows the inputs to the python script to be passed while calling the alias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*GVKljOZMXVVC82jc0KT0jA.png" /></figure><p>I have used <a href="https://docs.python.org/3/howto/argparse.html">argparser</a> for parsing the arguments from the command-line in todo_list_maker.py</p><p>Mentioned below is the python script ‘todo_list_maker.py’</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd06c540a4ba1411e99e1b8171a6a9ac/href">https://medium.com/media/cd06c540a4ba1411e99e1b8171a6a9ac/href</a></iframe><p>And following is the command that we need to use in the command-line to call the alias “todo” and add a to-do list item in the to-do list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*A6hIfeAYlpKmp5mS8Tbl5Q.png" /></figure><p>And as expected it generates a to-do list (.txt file) on the Desktop (by default)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*KC74BLKGwF52rtMg5v6i_A.png" /></figure><p>and adds the to-do list item in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*2YAORiIehqLGl8XmWuJmbw.png" /></figure><p>So this is how we create an alias for calling a python script and pass arguments in it through the alias.</p><p>But there is a last piece of information that I would like to add in this blog. The aliases do not work when we try to call them in a new command-line. This can be fixed by making a Batch or BAT file (.bat file) which would hold the command(s) that would run every time a new command-line terminal is opened.</p><p>In Windows, the batch file is a file that stores commands in a serial order. Command-line interpreter takes the file as an input and executes the stored commands in the same order. A batch file is simply a text file saved with the .bat file extension. It can be written using Notepad or any other text editor.</p><p>So we make a BAT file and save it at any location on the computer (Note this location as you would be using this location in a short while). Following is the BAT file that I made. It will first execute the “echo” command and then then the “doskey” command, each and every time a new command-line is opened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o264hg7ju-rCwv0HXpFZvA.png" /></figure><p>Now we go to the Windows Search option and type “cmd” and then click on “Open file location” option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRq-iTUUM3nhNrHggWLOqA.png" /></figure><p>We then right-click on the “Command Prompt” icon and select the “Properties” option.</p><p>Then we select the “Shortcut” tab and add</p><p>“/k C:\Users\anime\doskey_for_python.bat” (/k path_of _the _bat_file) in the “Target” field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*GzzgC6EBqHbQ5CAPZFskcw.png" /></figure><p>Hit “Apply” and ‘OK’ and we are done.</p><p>Now every time we open a new command-line, the BAT file is executed and our alias is ready to be used. This holds true even after we restart the computer which is exactly how we would want it to be.</p><p>So finally our “todo” command is ready to be used in the command-line to add new to-do list items in the to-do list.</p><p>We can now combine the idea of alias with the infinite functionalities that python brings to the table, to make fun commands do useful tasks!</p><h3>Code</h3><p>You can find the code for this “todo list maker” application on my GitHub account by clicking on this link <a href="https://github.com/n0obcoder/fun-with-python/tree/master/todo_list_maker"><strong>https://github.com/n0obcoder/fun-with-python/tree/master/todo_list_maker</strong></a></p><p>The README.md file provides a decent documentation of the todo_list_maker.py. Please feel free to explore it and add more functionalities to it 🙂</p><p>I am writing this blog because I have learned a lot by reading other’s blogs and I feel that I should also write and share my learnings and knowledge, as much as I can. So please leave your feedback in the comments section below to let me know how can I improve my future blogs! :D</p><p>Also I am an independent music artist who likes to play and record music in free-time. Maybe you can check out my artist page and show your support : )<br><a href="https://open.spotify.com/artist/7G2BgSnludIYl1gFyJKG6X?si=Bv5L4ZAVQrmIsl5SgGRAUw">8th Floor Harmony on Spotify!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e3208b8c6b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/alias-in-windows-and-its-fun-applications-using-python-5e3208b8c6b1">Alias in Windows and it’s Fun Applications using Python</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[Using Q-Learning in Numpy to teach an agent to play a game]]></title>
            <link>https://medium.com/data-science/using-q-learning-in-numpy-to-teach-an-agent-to-play-a-game-4fee32eb922a?source=rss-17fda0baf966------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fee32eb922a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[n0obcoder]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 06:31:56 GMT</pubDate>
            <atom:updated>2022-07-23T07:42:11.209Z</atom:updated>
            <content:encoded><![CDATA[<h3>Playing a Game Using Q-Learning in Numpy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvADcGrbHeiFJIHeTBDlUg.png" /></figure><p>There are some Machine Learning models which can be trained to map any given input to a desired output based on the input-output pair used during training. By input-output pair, I obviously mean the input and it’s respective ground truth or labels. Such algorithms are called Supervised Learning algorithms. Classification and Regression are some of it’s examples.</p><p>Also, there exists a class of machine learning models that look for underlying patterns in the data, without requiring the knowledge of the labels explicitly. These algorithms are called Unsupervised Learning algorithms. Clustering and Density Estimation are some of it’s examples.</p><p>Then there is this third kind of machine learning paradigm, alongside supervised learning and unsupervised learning, called the Reinforcement Learning which is fundamentally different from the prior two types.</p><p>This basically involves making sequential decisions in an environment in order to maximize the cumulative future rewards. I will explain this in greater detail in a while.</p><p><strong>Q</strong>-<strong>Learning </strong>is one such model-free Reinforcement Learning algorithm that learns to make correct actions under various circumstances.</p><p>Let us first get familiar with the very basic terminologies of a Reinforcement Learning set-up.</p><h3>Let’s get familiar with some basic RL terminologies</h3><p>There is something called an <strong>environment </strong>that literally consists of everything that the system is made up of. It has an <strong>agent </strong>that observes the environment (takes inputs from the environment) and then takes <strong>actions</strong> based on the inputs, changing the <strong>state </strong>of the environment and collecting <strong>rewards </strong>in the process.</p><p>Do not worry if this does not make perfect sense to you yet !</p><p>Let us try to understand this with the help of an example.</p><p>So there is a 6x6grid. We have our agent randomly spawned at one of the 6x6=36 possible cells in the grid. Similarly we have a bottle of beer and a deadly virus at two other cells in our grid world. The agent, the bottle of beer and the deadly virus will spawn at unique cell positions every time. The agent wants to reach to the bottle of beer avoiding the virus which might infect it and therefore end the game. The restriction on agent’s movement is that it can only move one cell in any diagonal direction.</p><p>In this set-up, our 6x6 grid-world is the <strong>environment</strong>. The agent has access to it’s relative position with respect to the bottle of beer (reward) and the deadly virus (enemy), and we call this information about the environment that the agent has access to, as <strong>state</strong>. And the agent can take certain predefined <strong>actions</strong>, like moving a cell in any of the four diagonal directions, depending on the current state of the environment. Agent’s action might get it a bottle of beer (a <strong>positive reward</strong>) or it might get the agent infected by the deadly virus (a <strong>negative reward</strong>). So the objective of the agent here is to learn about it’s environment by interacting with it and ultimately learn to take actions such that the future cumulative sum of rewards gets maximized.</p><p>The sequence of states, actions and rewards until it all ends (either by reaching to the beer bottle or getting infected by the virus), is called an <strong>episode</strong>.</p><p>The states which cause the episode to terminate are called the <strong>terminal states</strong>. In our example of the grid-world, the states in which the relative position of the agent either with respect to the beer bottle or the virus, becomes zero, are the terminal states.</p><p><strong>Return</strong> is the cumulative sum of the future rewards. This might reach infinity in cases where there are no terminal states, also known as <strong>Non-Episodic </strong>tasks. To make it a finite sum, we discount the future rewards using a discounting factor called <strong>gamma</strong>.</p><p>Following is the formula for return at time t, expressed in terms of rewards at various time steps. Here T is the final time step and <strong>Γ </strong>is the discount rate such that 0 ≤ <strong>Γ </strong>≤ 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_d-3CmNEnKne9q-J3fQYw.png" /></figure><p><strong>Value function </strong>are the functions of the states (or the state-action pairs) that estimate how good it is for the agent to be in a given state (or how good is it to perform a given action in a given state)</p><p>Value functions are always defined with respect to particular ways of acting, called policies.</p><p>A <strong>policy </strong>is nothing but a mapping from states to probabilities of selecting each possible action.</p><p>I would like to talk more about the <strong>state-action value function </strong>because we are going to make use of it in the rest of the blog.</p><p>So as mentioned earlier, a state-action function is a function that returns the expected return starting from a state ‘s’, taking action ‘a’ and thereafter following the policy <strong>π</strong>.</p><p>So comparing the values of a state-action function for a given state and all the actions in the action space, can lead us to the best possible action that can be taken in that state. And this is actually how our agent is going to choose the best action that can be taken in a given state.</p><p><strong>Q-Table</strong> is a table consisting of all the state-action pairs. It’s like a look-up table from where, if give a current state and action, we can get the state-action or the q-value.</p><p>We initialize the q-table with random numbers initially and then keep on updating the vales for each state-action pair as the agent continues to take various actions under various states. After a certain degree of exploration of the environment by the agent, we can, by using the q-table tell which would be the best action to be taken for any given state !</p><p>Isn’t that crazy ! :D</p><h3>Let’s get our hands dirty !</h3><p>We are going to learn how to implement q-learning now. This is going to be a fun ride. Fasten your seat belts :D</p><p>We start by importing all the necessary libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45789c147086fab08fa42262198febd1/href">https://medium.com/media/45789c147086fab08fa42262198febd1/href</a></iframe><p>Then we define all the hyperparameters of the q-learning algorithm and the display window.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15de8a03957bba8235a44efb33f621a9/href">https://medium.com/media/15de8a03957bba8235a44efb33f621a9/href</a></iframe><p>Next we define the path of the images for our agent, beer bottle (positive reward) and the virus (negative reward) and read them to be displayed on the screen. This is just to make the display window look interesting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1164cdc40f351784ca251e3ba7082af8/href">https://medium.com/media/1164cdc40f351784ca251e3ba7082af8/href</a></iframe><p>We need to make a class called <strong>‘Blob’</strong> which our agent, beer bottle and the virus would inherit. A Blob class object would have a spawning location (x and y coordinates) associated with it and it would be able to move diagonally depending on the input passed in it’s <strong>‘move’</strong> method. We would also be able to add to subtract two Blob objects. It would simple add or subtract the x and y coordinates of the two Blob objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4987afd8c653d75e1bb35d228946e8f/href">https://medium.com/media/a4987afd8c653d75e1bb35d228946e8f/href</a></iframe><p>Let’s define the q-table now, which will be used again and again to pick the best action under a given state. And we will constantly keep on updating this table to improve the decision making ability of our agent.</p><p>Note that the range here that we have taking for the state-space is <strong>-SIZE+1 to SIZE</strong>. This is because we have defined the state-space as the relative position of the agent from the beer bottle and the virus. So this can be positive or negative. For exmaple, if the SIZE of the grid-world is 6, then the relative position of the agent with respect to the beer bottle would vary from -5 to 5.</p><p>Don’t wory about the update rule for updating the q-values in the q-table for now. We will talk about that in a while.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecf36ce709deb216cabac1daa696dcb8/href">https://medium.com/media/ecf36ce709deb216cabac1daa696dcb8/href</a></iframe><p>In each episode, our agent, beer bottle and the virus need to be spawned at unique cell locations in the defined grid-world. But our Blob class simply spawns the guys at a random cell location in grid-world. This might lead to characters being spawned at the same location, which we do not want. So to take care of that we write a function which would take as input a list of tuples containing the coordinates of the guys already being spawned. This will ensure that any two of the guys, the agent, the beer bottle and the virus do not share their cell location.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfc069bc4cec283eadb03f37090ce396/href">https://medium.com/media/cfc069bc4cec283eadb03f37090ce396/href</a></iframe><p>With everything set up and defined, we start training the agent (updating the q-table).</p><p>This is where the magic happens.</p><p>Let’s understand it line by line. So we start off with a loop which would run for the defined number of episodes.</p><p>We initialize the player, beer and virus objects using the <strong>get_unique_spawning_location </strong>function and the <strong>Blob </strong>class that we have already defined earlier.</p><p>Then we make use of the <strong>SHOW_EVERY </strong>parameter to print the current value of epsilon, the mean reward so far (this is supposed to increase with training) and the display parameter <strong>‘show’</strong> that is used to display the grid-world in action.</p><p>Next we initialize the<strong> ‘episode_reward’</strong> to 0 and the agent starts taking actions for 200 timesteps.</p><p>For every timestep, we need the state of the environment, which we have defined as the relative position of the agent with respect to both the beer bottle and the virus.</p><p>Then agent would need to take an action, which again would depend on the curent value of epsilon. We sample a random number from a uniform distribution and compare it with the current value of epsilion. If the random value is greater than the current value of epsilon, the agent uses the q-table and picks the action that has the maximun q-value in the q-tablle. Else the agent takes a random action.</p><p>The first case where the agent makes use of the q-table to pick the action with highest q-value is referred to as <strong>Exploitation </strong>whereas the second case where the agent takes a random action is referred as <strong>Exploration</strong>. The parameter epsilon takes care of the <strong>Exploitaion-Exploration tradeoff</strong>.</p><p>We then check if the agent has reached to the beer bottle or if it has been infected by the virus. We define the reward of the current timestep accordingly.</p><p>The agent then takes the action resulting in a change in it’s state in the grid-world.</p><p>We then compute the new q-value and update the q-table using the below mentioned formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_M6HvopqYUBxjAEEE7ZK3Q.png" /></figure><p>For the purpose of displaying the grid-world and the guys, we make an empty canvas, resize it as per the <strong>DISPLAY_SIZE </strong>parameter and paste the images of the agent, beer bottle and virus at their respective current locations.</p><p>At last we break the loop either if the agent gets his beer or if he gets infected by the virus.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caa047d0aabdccbb3e3b5b0792d015f4/href">https://medium.com/media/caa047d0aabdccbb3e3b5b0792d015f4/href</a></iframe><p>We calculate the moving average and plot the rewards.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/956783506c3f15aa478ff4f0b1cf81a5/href">https://medium.com/media/956783506c3f15aa478ff4f0b1cf81a5/href</a></iframe><p>Finally we save the updated q-table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3227e819f19e1c2e18a8da18c5acad3b/href">https://medium.com/media/3227e819f19e1c2e18a8da18c5acad3b/href</a></iframe><h3>Result</h3><p>Following is the plot for the moving average of the rewards. It’s upward trend shows that the agent becomes smarter with more and more episodes of training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*M9Tdkis9-VoRNY_th4lucA.jpeg" /><figcaption>Moving Average</figcaption></figure><p>And here are some GIFs that show how the agent gets smarter with every episode of training.</p><p>Here is the thirsty agent looking for the bottle of beer with randomly initialized q-table. It means that the agent has no clue about the environment yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*V95r-iywnhAYgZ0Q7sn8PA.gif" /><figcaption>dumb agent wants beer but does not get it</figcaption></figure><p>After some training, the agent does a relatively better job of making sequential decisions. He is not very fast yet but he ends up finding the beer eventually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*55txIxQuv8VTs-95JNnBhA.gif" /><figcaption>hmmm, that’s better</figcaption></figure><p>Finally after thousands of episode of training, the agent gets really good at making sequential decisions and finds the beer in no time ! : D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*xooExiFLqb-gig95j62IwA.gif" /><figcaption>now that’s a smart-ass agent there ! B)</figcaption></figure><h3>Advantages of Q-Learning</h3><p>It is a simple concept to understand and implement. And it works great for environments with not a very huge state-action space.</p><h3>Limitations of Q-Learning</h3><p>Q-Learning involves look-ups from the q-table. And the q-table is made up of values for every single state-action pair possible. So as the state-space increases, the size of the q-table grows exponentially. So Q-Learning is good to train an agent in an environment with a small state-action space. For more complex set-ups , Deep Q-Learning is used.</p><h3>Code</h3><p>You can find the code for this q-learning project on my GitHub account by clicking on this link <a href="https://github.com/n0obcoder/Q-Learning"><strong>https://github.com/n0obcoder/Q-Learning</strong></a></p><h3>References</h3><ol><li><a href="https://www.youtube.com/playlist?list=PLQVvvaa0QuDezJFIOU5wDdfy4e9vdnx-7">https://www.youtube.com/playlist?list=PLQVvvaa0QuDezJFIOU5wDdfy4e9vdnx-7</a></li><li><a href="https://www.coursera.org/learn/fundamentals-of-reinforcement-learning">https://www.coursera.org/learn/fundamentals-of-reinforcement-learning</a></li><li><a href="https://web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf">https://web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf</a></li></ol><p>I am writing this blog because I have learned a lot by reading other’s blogs and I feel that I should also write and share my learnings and knowledge, as much as I can. So please leave your feedbacks in the comments section below to let me know how can I improve my future blogs ! :D</p><p>Also I am an independent music artist who likes to play and record music in free-time. Maybe you can check out my artist page and show your support : )<br><a href="https://open.spotify.com/artist/7G2BgSnludIYl1gFyJKG6X?si=Bv5L4ZAVQrmIsl5SgGRAUw">8th Floor Harmony on Spotify!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fee32eb922a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-q-learning-in-numpy-to-teach-an-agent-to-play-a-game-4fee32eb922a">Using Q-Learning in Numpy to teach an agent to play a game</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classification of Mobile Gallery Images  in PyTorch]]></title>
            <link>https://medium.com/data-science/classification-of-mobile-gallery-images-in-pytorch-8ba2d32ce2bf?source=rss-17fda0baf966------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba2d32ce2bf</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[n0obcoder]]></dc:creator>
            <pubDate>Sun, 24 Nov 2019 14:45:52 GMT</pubDate>
            <atom:updated>2022-07-23T07:42:36.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>Classification of Mobile Gallery Images in PyTorch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*Pji7oy2qnE3Hdc7HEQmy6w.png" /><figcaption>A Meme which is going to be used to train an Image Classifier !</figcaption></figure><p>I very often find myself in situations where my mobile galley is all messed up. I like my mobile gallery to be organised. This is how the idea of building a Mobile Gallery Image Classifier popped up in my head !</p><p>This mini-project sounds like a good practical application of a Deep Neural Network based Image Classifier to me. It promises to be a fun experience building your own Mobile Gallery Image Classifier.</p><p>So let’s get started ! : D</p><h4>STEP 1: Building a Custom Dataset</h4><p>We need to list down all the classes or categories that we would want our Image Classifier to output results from.</p><p>Since this is a mobile gallery image classifying project, I would pick the classes which I, very frequently came across, while going through my mobile gallery.</p><p>Following are the classes that I have selected-</p><ul><li>Cars</li><li>Memes</li><li>Mountains</li><li>Selfies</li><li>Trees</li><li>Whataspp_Screenshots</li></ul><p>Once we have the list of all the desired classes, we have to collect images for those.</p><p>There are a few different ways of collecting image data</p><ul><li>Manual collection- We can either use the existing images from our mobile gallery or click pictures of things which we have listed down as a target class.</li><li>Web Scrapping- There are ways in which we can scrape images from the web. This is one such python script which can be used for downloading images of a particular class.</li></ul><p>Once the images are downloaded, we have to separate them into different class directories. So we have have 6 directories containing images of the respective classes.</p><p>I personally used both the data collection methods mentioned above. I did download images for most of the classes using a python script which can be easily found on websites like <a href="https://stackoverflow.com/questions/20716842/python-download-images-from-google-image-search"><strong>stackoverflow</strong></a>. But since I could not find nice images of whatsapp screenshots on the internet, I had to collect them from my mobile phone.</p><p>Good News for you guys ! I have built a <strong>Mobile Gallery Image Dataset </strong>which I will be using in this blog, and I have made it public ! So you guys can use it for free, without going through the trouble of making one for yourself :D</p><p><a href="https://www.kaggle.com/n0obcoder/mobile-gallery-image-classification-data">mobile_gallery_image_classification</a></p><p>You can download the above mentioned dataset and extract it in the root directory such that the python script or the jupyter notebook file is in the same directory as the dataset directory. Make sure that the path of the dataset directory follows the one shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee7f7f24bf357e2d9982569f3c049741/href">https://medium.com/media/ee7f7f24bf357e2d9982569f3c049741/href</a></iframe><p>Here are a few samples from the mobile gallery image dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*SEzdlOJINfHmyq7Kxfg1PA.jpeg" /><figcaption>These are few of the sample images taken from the training data from the Mobile Image Gallery Dataset. Their respective classes: Memes (top-left), Cars (top-right), Trees (bottom-right) and Mountains (bottom-left)</figcaption></figure><h4>STEP 2: Data Pre-Processing and Making DataLoaders</h4><p>Once the dataset is ready, the next thing that we need to do is do some data pre-processing. And by data pre-processing, I mean performing some simple image processing operations like resizing, randomly flipping the image on the horizontal axis, converting the images(pixel having integer values ranging from 0 to 255) to tensors (pixel values having floating number ranging from 0.0 to 1.0) and at last, but not the least, normalizing the tensors by the using the ImageNet statistics (mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225]). Notice that we are working with <strong>BGR </strong>(color) images and not the grayscale (black and white) images.</p><p>Next, we make the dataset object by making use of the data path and the transforms /preprocessings that we want to apply on the image data.</p><p>We randomly split the dataset into train and validation datasets by defining a split percentage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbabeba16b2c6a4b72d4804dcea7ea54/href">https://medium.com/media/fbabeba16b2c6a4b72d4804dcea7ea54/href</a></iframe><p>At last, we make train and validation dataloader objects by defining a batch size. This would make the training and validation process amazingly fast by making use of the matrix multiplications.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd62d82b8d1b103c0f45011d9fd6923a/href">https://medium.com/media/fd62d82b8d1b103c0f45011d9fd6923a/href</a></iframe><h4>STEP 3: Defining a Suitable Model and Making the Necessary Tweaks</h4><p>First of all, we are going to use a Convolutional Neural Network based architecture because nothing beats CNNs when it comes to handling Images or for that matter, any type of data which has spatial relationship. Since there are already so many tried and tested CNN based architectures, we don’t need to experiment with a new one.</p><p>We are not going to write the architecture of our CNN based model on our own, but will use one of the many existing ones. There are two main reasons for doing so-</p><ol><li>These architectures have been tried and tested successfully on various datasets and have shown great results.</li><li>These architectures have been trained on huge public datasets and their pretrained weights have been made publicly available.</li></ol><p>There are a lot of pretrained models available in <a href="https://pytorch.org/docs/stable/torchvision/index.html#torchvision">torchvision</a>, like AlexNet, Resnet, VGG, InceptionNet, DenseNet etc. to choose from. We pick the model called Resnet34 because it’s neither too deep nor too shallow. It should not take a lot of computing power while training, in case you are planning on using this on a machine without a GPU card.</p><p>But there is one thing that we must pay attention to. The number of neurons in the last linear layer of such CNN based architectures represent all the classes that are present in our dataset. Originally Resnet34 was used to train on the ImageNet dataset which had 1000 classes. But we want this model to output predictions for only the number of classes that we have in our dataset (6 in our case). So we simply replace the last linear layer from this model with a new linear layer with 6 neurons, outputting the predictions for the 6 classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1314edbd910ba426a5fd121dc69897b/href">https://medium.com/media/e1314edbd910ba426a5fd121dc69897b/href</a></iframe><h4>STEP 4: Transfer Learning by Freezing and Un-Freezing the Layers</h4><p>It’s worth noting that since we are using a pre-trained model, it’s filter or the kernels have already learnt to recognize certain features. Let me try to explain this to you in greater details that what exactly are the features that these filters have learnt to recognize.</p><p>The filters in the initial convolutional layers learn the simple and basic features like the edges, colors and textures; the ones in the middle layers might learn shapes like circles and polygons; while the filters in the deeper layers learn more complex patters like a face or a flower petal etc. This will get more clear by looking at the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qR3g4d9PtK3AdmlHepavrQ.png" /><figcaption>Low-Level Features include edges, colors, textures. Mid-Level Features include simple shapes and geometries. High-Level Features include complex shapes and objects like faces, flowers etc.</figcaption></figure><p>We could obviously make use of the filters present in the initial and the middle layers since we need them to recognize the edges, colors, textures and the simple shapes in the input image. What we might not want to retain is the filters present in the last few convolutional and linear layers. So we train the mod…… Or should I say, we should fine-tune the model on our custom dataset with a small learning rate only for the last few layers (be it a convolution layer or a linear layer).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50754f1f4035c26bb918fcec777d606e/href">https://medium.com/media/50754f1f4035c26bb918fcec777d606e/href</a></iframe><p>We see that all the parameters are trainable at the beginning (requires_grad = True means that the parameter is learnable)</p><p>Let’s see what are the names of the layers so that we can freeze the last two of them</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe8a6a6a8fdbd74f345d5c7999e96e7e/href">https://medium.com/media/fe8a6a6a8fdbd74f345d5c7999e96e7e/href</a></iframe><p>So we freeze all the layers but a few at the end the network. This will make sure that only the unfrozen layers at the end of the network gets fine-tuned and the other layers remain unchanged.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e47120fa84b67d4e099515098bc0575/href">https://medium.com/media/8e47120fa84b67d4e099515098bc0575/href</a></iframe><p>Let’s print out the requires_grad for all the parameters and make sure that the desired changes have been made</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c90aa5c34d0ec96cab6f85dfb3c0abe/href">https://medium.com/media/7c90aa5c34d0ec96cab6f85dfb3c0abe/href</a></iframe><p>Yes, the changes have been made ! (See, the parameters present in ‘layer4’ and ‘fc’ have requires_grad = True and rest all the other parameters have requires_grad = False )</p><h4>STEP 5: Loss Function and Optimizer</h4><p>Ok. We have our data ready to be fed into into the model and the model is going to return the predictions. But how do we know if the predictions are correct or not ?</p><p>This is where the Loss Functions come into play ! : D</p><p>We can only compare two things when we have a scalar representation of them. And loss functions give us a scalar quantity, which makes it possible for us to compare. As simple as that : )</p><p>But how do we ensure that the loss keeps on reducing as we train the model, making the predictions better and better with each iteration ?</p><p>Yes you got that right people ! Optimizer to the rescue B )</p><p>Cross Entropy Loss is the standard loss function that the whole world uses for solving the problem of Multi-Class Classification problem. And Adam optimizer is one of the most popular optimizer choices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/134cc65662c513aee71c1138b64e180b/href">https://medium.com/media/134cc65662c513aee71c1138b64e180b/href</a></iframe><p>We are all set now. Let the training begin !!!</p><h4>STEP 6: Training and Validation</h4><p>After doing all the work of data proprocessing, picking up a suitable model, freezing up some of the layers, selecting the loss function and the optimizer, we are finally ready for the training of our neural network to begin.</p><p>Let’s unleash the Resnet34 and let it absorb all that it can, from the training data !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bmwlqwfs0BRPCS6ZjD2qA.jpeg" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f464f00d2c965f087d876e366be5a0/href">https://medium.com/media/c6f464f00d2c965f087d876e366be5a0/href</a></iframe><p>Check <a href="https://towardsdatascience.com/everything-you-need-to-know-about-saving-weights-in-pytorch-572651f3f8de"><strong>this blog</strong></a> for learning more about the ways in which you can either save just the learnt weights or the whole trained model (including the weights).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*MP4WaN06XeCT1nEhoVtfSg.png" /><figcaption>Loss Plots after training for 5 epochs</figcaption></figure><p>But wait ! There is a trick that I would like to share with you guys. We train the network for a few epochs and then we freeze all the layers but the last linear layers. You might wonder why is this step required.</p><p>Do you guys remember that we had discarded the last linear layers form the pretrained model and added a new one with the number of neurons equal to the number of classes that we have in our custom dataset ? When we did that, the weights of the last linear layers got randomly initialized which needs to be trained properly once all the convolutional layers are trained (able to extract distinct features form the input image).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/578614780b3c5b780204761d0032cb29/href">https://medium.com/media/578614780b3c5b780204761d0032cb29/href</a></iframe><p>Following are the loss plots after freezing the layer 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*djn34PC2hkkyevNujJNYbQ.png" /><figcaption>Loss Plots after freezing Layer 4.</figcaption></figure><p>This trick works well in practice. There are standard ways of training a network, but there is no hard and fast rules. So you may want to experiment with the training procedure. Do let me know if you guys have got nice results by following some other training procedure by sharing your methods in the comments section down below.</p><h4>STEP 7: It’s Testing Time !</h4><p>We have trained our Neural Network on the custom dataset of Mobile Gallery Images and it is now supposed to classify any given image to one of the 6 classes present in the dataset that it has been trained on.</p><p>Now all we need to do is read the test image, do the same preprocessing on it that we had done to the images while training the network and hope to see some nice predictions being returned my our network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17a60aff3f25cd9b7bacc4323b2c2378/href">https://medium.com/media/17a60aff3f25cd9b7bacc4323b2c2378/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*RD94BAtWqv2XNx6UewYZPw.png" /><figcaption>Test Image</figcaption></figure><p>And it seems to work just fine ! : D</p><p>Congratulations ! You just made a Mobile Gallery Image Classifier : D And this was just one idea of using an Image Classifier. You can use Image Classifiers to build a variety of creative apps. The only limit is your imagination.</p><p>I hope that you enjoyed reading this blog as much as I enjoyed writing it : )</p><p>Please feel free to reach out to me in case you have any doubts, questions or if you want to collaborate with me on some computer vision project.</p><p>Cheers, untill next time ! :D</p><h4><strong>I would strongly recommend you guys to fork this </strong><a href="https://www.kaggle.com/n0obcoder/mobile-gallery-image-classification-using-pytorch"><strong>public Kaggle kernel </strong></a><strong>and play with the code, to get the feel of it !</strong></h4><h4><strong>Or</strong></h4><h4><strong>Maybe download the G</strong><a href="https://github.com/n0obcoder/Mobile-Gallery-Image-Classification-in-PyTorch"><strong>itHub repository</strong></a><strong> containing the jupyter notebook file.</strong></h4><p>I am writing this blog because I have learnt a lot by reading other’s blogs and I feel that I should also write and share my learnings and knowledge, as much as I can. So please leave your feedback in the comments section down below. Also I am new to writing blogs, so any suggestions on how to improve my writing would be appreciated ! :D</p><p>Also I am an independent music artist who likes to play and record music in free-time. Maybe you can check out my artist page and show your support : )<br><a href="https://open.spotify.com/artist/7G2BgSnludIYl1gFyJKG6X?si=Bv5L4ZAVQrmIsl5SgGRAUw">8th Floor Harmony on Spotify!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba2d32ce2bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/classification-of-mobile-gallery-images-in-pytorch-8ba2d32ce2bf">Classification of Mobile Gallery Images  in PyTorch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fitting a Straight Line on 2D Data in PyTorch]]></title>
            <link>https://medium.datadriveninvestor.com/fitting-a-straight-line-on-2d-data-in-pytorch-78d0e3450876?source=rss-17fda0baf966------2</link>
            <guid isPermaLink="false">https://medium.com/p/78d0e3450876</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[n0obcoder]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 17:39:44 GMT</pubDate>
            <atom:updated>2022-07-23T07:43:23.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2CL8OcihVZVOCSyE" /><figcaption>Fitting a Straight Line on 2D Data ;)</figcaption></figure><p>This blog focuses on showcasing the flow of making and training a basic learning model in <strong>PyTorch</strong>.</p><p>And what can be more basic than fitting a straight line on 2D data?</p><p><a href="https://www.datadriveninvestor.com/2019/02/08/machine-learning-in-finance/">Machine Learning in Finance | Data Driven Investor</a></p><p><strong>Nothing !!!</strong></p><p>Seriously, nothing can be as simple as fitting a straight line on 2D data :p</p><p>Linear Regression in single variable a.k.a. Univariate Regression is one of the simplest yet one of the most fundamental concepts in Machine Learning.</p><p>In a Univariate Regression problem, we are given a number of data points in a 2D space for which we are asked to find a straight line in that 2D space such that the sum of perpendicular distances of all the data points from that line is the minimum. In other words, the straight line sits right at the center of the given data distribution.</p><p>We don’t know if the writer of this blog is a human being or a bot, but there is one thing which we just can’t deny; any straight line in a 2D space can be represented by just two real numbers, <strong>m </strong>the slope of the line and <strong>c</strong> the intercept of the line with the x-axis.</p><p>So the problem of finding a straight line which fits a given distribution of points in a 2D space gets reduced to finding the slope <strong>m </strong>and the intercept <strong>c </strong>of that line.</p><p>We are going to use PyTorch to solve this problem by building and training a very simple Deep Learning model.</p><p>It’s time to get our hands dirty…</p><p>We start off by importing the <a href="https://www.youtube.com/watch?v=5dhSdnDb3tk"><em>bare necessities</em></a> of coding using PyTorch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/847153a3665bc470c0bc157f3cad9bdf/href">https://medium.com/media/847153a3665bc470c0bc157f3cad9bdf/href</a></iframe><h4>Step 1: Generating Synthetic 2D Data</h4><p>In order to find a straight line that fits a given data, we first need to generate the data itself. We are going to generate the synthetic data in such a way that the data points roughly lie on a straight line. We are going to do this by using some predefined <strong>m</strong> (slope) and <strong>c</strong> (intercept).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/333011d33bd7cc2b4d61cc99eff527e6/href">https://medium.com/media/333011d33bd7cc2b4d61cc99eff527e6/href</a></iframe><p>Once the slope(m) and the intercept(c) have been randomly selected, we generate synthetic data points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8baf254d6a3e113f1862ebb8f2b0e6b0/href">https://medium.com/media/8baf254d6a3e113f1862ebb8f2b0e6b0/href</a></iframe><p>Let’s visualize the synthetic data points and the line defined by <strong>m_synthetic</strong> amd <strong>c_synthetic.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*IbrMcnWhtkjokEIL127Clw.jpeg" /><figcaption>Synthetic points generated by using a synthetic slope and a synthetic intercept.</figcaption></figure><p>Our task here is to find out the equation of a straight line which best fits all the data points!</p><p>In other words, we have to find the slope and the intercept of a line, which would give us the line that sits at the center of the distribution of the data points.</p><p>Since this is a Linear Regression Problem, we want to find the value of all the required parameters (slope m and intercept c in our case because the data lies in a 2D space).</p><p>Had the data been higher-dimensional, we would have to solve for more parameters.</p><h4>Step 2: Defining the Model Architecture</h4><p>We are going to use <strong>PyTorch</strong> to solve this Univariate Regression problem.<br>We need a very simple model which takes in a single scalar input and spits out some single scalar output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3369ab2ca46583d0b4fb5530fe3c2ba8/href">https://medium.com/media/3369ab2ca46583d0b4fb5530fe3c2ba8/href</a></iframe><p>We can print the <strong>model</strong> to see its architecture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b42141f35c0c55347aa65ed8d10eb4fb/href">https://medium.com/media/b42141f35c0c55347aa65ed8d10eb4fb/href</a></iframe><p>Once, we have created the <strong>model</strong>, let’s check out the parameters that we have in it.</p><p>There are going to be some learnable parameters in the model, which are randomly initialized at the beginning.</p><p>This is how the initial parameters look like at the initial stage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a60fc11deae3bb8ebdb5922973810a6a/href">https://medium.com/media/a60fc11deae3bb8ebdb5922973810a6a/href</a></iframe><p>Note that the parameter’s initialized values are not at all, near the <strong>m_synthetic</strong> and <strong>c_synthetic</strong> values, which have been actually used to synthesize the data points.</p><p>But as we train the model, these values would approach to the values of m_synthetic and c_synthetic!</p><p>We will see this at the end of this notebook.</p><h4>Step 3: Defining a Loss Function and an Optimizer</h4><p>There must be a metric which would let us know how well is our model fitting on the given data.</p><p>That is exactly what a <strong>Loss Function</strong> does!</p><p>And PyTorch calculates the derivatives of the loss with respect to all the learnable parameters during the <strong>Back-Propagation</strong>, which is later used by an <strong>Optimizer</strong> to update all the parameters of the model, improving the model after every epoch.</p><p>By the way, one <strong>epoch</strong> is when the entire dataset is passed both forward and backward through the Neural Network only once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/421b9e93d9b4cb7bd901e680ebb52429/href">https://medium.com/media/421b9e93d9b4cb7bd901e680ebb52429/href</a></iframe><p>PyTorch expects all its inputs to be <strong>torch.tensors</strong>, so we convert all the data to torch tensors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d03e1c492828324fb4c8feafefdb259/href">https://medium.com/media/2d03e1c492828324fb4c8feafefdb259/href</a></iframe><h4>Step 4: Training the Model and Plotting the Loss</h4><p>After having prepared the data, defined the model, the loss function and the optimizer, it’s finally time to train our model!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4fe4c3e46636dc269ff3af3dfa3b067/href">https://medium.com/media/d4fe4c3e46636dc269ff3af3dfa3b067/href</a></iframe><p>We must understand each and every line of code written in the previous code block.</p><p><strong>optimizer.zero_grad() </strong>is a very important line of code. So what&#39;s happening here is that, when the back-propagation is done, the gradients of all the model’s parameters are accumulated in the <strong>optimizer</strong>, rather than getting replaced. These gradients need to be cleared out. That’s exactly what <strong>optimizer.zero_grad() </strong>does.</p><p>Well, you must be wondering why PyTorch makes us do something which seems obvious to be done. Actually, accumulating the gradients comes in real handy when training an RNN or an LSTM because in these cases, each module will be backpropagated through several times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*WSKPNuBnikLrpBTkjvcfWw.jpeg" /><figcaption>Don’t woory if you didn’t get this meme : p</figcaption></figure><p>We can see the parameters (m_learnt and c_learnt) learnt by the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/845f11416d93366ceae9ee5689e97541/href">https://medium.com/media/845f11416d93366ceae9ee5689e97541/href</a></iframe><p>Next, we plot the losses</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96d68fc8a87b08cecaace722c77611c5/href">https://medium.com/media/96d68fc8a87b08cecaace722c77611c5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*FQjCqDECJv38sh6-XfWn3g.jpeg" /><figcaption>Decreasing loss during the model’s training</figcaption></figure><p>We see the loss coming down after every epoch. That’s always a good sight for a Deep Learning practitioner :D</p><h4>Step 5: Visualizing the Straight Line Learnt by the Model</h4><p>Let’s now plot the line defined by the slope and intercept learned by the model and see if it is a good approximation of the data distribution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28f1609bc1d51ddc4a76b39206459a60/href">https://medium.com/media/28f1609bc1d51ddc4a76b39206459a60/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*QPtnSdJ9pp3zRww1ZHDNwQ.jpeg" /><figcaption>Line learnt by the model is fitting well on the data</figcaption></figure><p>Looks like the model has indeed fit a straight line on the given data distribution !!! : D</p><h4>Visualizing the Slope and the Intercept during Training of Model</h4><p>Remember we had collected the learned slope and the learned intercept values of the model during the training process. We can now visualize them by making their plots.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f01dfe5af161f6c0ce3e7534eb82b7e5/href">https://medium.com/media/f01dfe5af161f6c0ce3e7534eb82b7e5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*3A41SapM-CqCnnirFe9ppg.jpeg" /><figcaption>Model’s parameters changing during the training</figcaption></figure><p>We see that during the training phase of the model, the parameters of the model change and they approach to the value for which the overall loss of the model is minimum.</p><p>This in fact, is the general idea behind any Deep Learning model. It tries to find the best suited parameters for the model, to perform a specific task, which is measured by using a suitable Loss Function for that specific task.</p><h4>End.</h4><p>I hope that you understood the basic ideas behind solving a Linear Regression problem using PyTorch.</p><p>This was a very simple example of solving a linear regression problem in 1 variable or a Univariate Regression problem. But we can even solve Multivariate Regression problems using a similar approach.</p><p>I hope that you enjoyed this tutorial! :D</p><h4>Check Out the Following Links</h4><p>Kaggle Kernel: <a href="https://www.kaggle.com/n0obcoder/fitting-a-straight-line-on-2d-data-in-pytorch">Fitting a Straight Line on 2D Data in PyTorch</a></p><p>Github Repository: <a href="https://github.com/n0obcoder/Fitting-a-Straight-Line-on-2D-Data-in-PyTorch">Fitting-a-Straight-Line-on-2D-Data-in-PyTorch</a></p><p>I am writing this blog because I have learned a lot by reading other’s blogs and I feel that I should also write and share my learnings and knowledge, as much as I can. So please leave your feedback in the comments section below! :D</p><p>Also I am an independent music artist who likes to play and record music in free-time. Maybe you can check out my artist page on Spotify and show your support : )<br><a href="https://open.spotify.com/artist/7G2BgSnludIYl1gFyJKG6X?si=Bv5L4ZAVQrmIsl5SgGRAUw">8th Floor Harmony on Spotify!</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78d0e3450876" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/fitting-a-straight-line-on-2d-data-in-pytorch-78d0e3450876">Fitting a Straight Line on 2D Data 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[Everything You Need To Know About Saving Weights In PyTorch]]></title>
            <link>https://medium.com/data-science/everything-you-need-to-know-about-saving-weights-in-pytorch-572651f3f8de?source=rss-17fda0baf966------2</link>
            <guid isPermaLink="false">https://medium.com/p/572651f3f8de</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[n0obcoder]]></dc:creator>
            <pubDate>Tue, 13 Aug 2019 18:31:05 GMT</pubDate>
            <atom:updated>2022-07-23T07:44:19.447Z</atom:updated>
            <content:encoded><![CDATA[<p>What do we Deep Learning practitioners do once we are done with training our models ?</p><p><strong>We chill !!!</strong></p><p><em>Hahhhaha</em> <em>Just Kidding…</em></p><p>We either save the learnt weights or the entire model so that we could further train the model or maybe use the trained model for inference !</p><p>Next thing that you guys might be interested in knowing is, when do we save just the learnt weights and when do we save the whole model.</p><p>In this blog, we will try to find the answers to these questions.</p><p>I will keep it very straightforward and simple while explaining you the ins and outs of the art of saving a model’s architecture and it’s weights in PyTorch.</p><p>We will also learn how to access the different modules, <em>nn.Modules</em> to be precise, in any given PyTorch model .</p><p>So feel free to fork this kaggle kernel and play with the <a href="https://www.kaggle.com/n0obcoder/things-to-know-about-saving-weights-in-pytorch"><strong>code</strong> </a>: )</p><p>Let’s get started !!!</p><p>We start off by importing the <a href="https://www.youtube.com/watch?v=5dhSdnDb3tk"><em>bare necessities</em></a> of coding using PyTorch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b06f4ea6dc8d765e988947139cd2a39/href">https://medium.com/media/2b06f4ea6dc8d765e988947139cd2a39/href</a></iframe><p>Next, we define a CNN based model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0054cff18e6ac2c15f28027973559a8a/href">https://medium.com/media/0054cff18e6ac2c15f28027973559a8a/href</a></iframe><p>Let’s initialize and print <em>model</em> and see what’s inside it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d64d32b3cb628ecdff45d4466e65f1f/href">https://medium.com/media/8d64d32b3cb628ecdff45d4466e65f1f/href</a></iframe><p>Printing the <em>model</em> shows you it’s architecture. But we are going to dive deeper, for we are the Deep Learning practitioners!</p><p>We need to make sure that we understand what exactly lies inside our model.</p><p>There is a way to access each and every learnable Parameter of a model along with their names. By the way, a <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Parameter"><em>torch.nn.Parameter</em></a> is a Tensor subclass , which when used with <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Module"><em>torch.nn.Module</em></a> gets automatically added to the list of its parameters and appears in e.g., in <em>parameters()</em> or <em>named_parameters()</em><strong><em> </em></strong>iterator. Adding a <em>torch.nn.Tensor</em> on the other hand doesn’t have such an effect. More on that later !</p><p>Back to printing all the parameters of the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ca6cc0677bf2f7d452dfe1dc438b84b/href">https://medium.com/media/3ca6cc0677bf2f7d452dfe1dc438b84b/href</a></iframe><p>Wooouhooouhooou ! So what did just happen here ?</p><p>Let’s get into the <em>named_parameters()</em> function.</p><p>model.named_parameters() itself is a generator. It returns the <em>name</em> and <em>param</em>, which are nothing but the name of the parameter and the parameter itself. Here, the returned param is <em>torch.nn.Parameter</em> class which is a kind of tensor. Since param is a type of tensor, it has <em>shape</em><strong> </strong>and <em>requires_grad</em><strong> </strong>attributes too. <em>param.shape</em> is simply the shape of the tensor and <em>param.requires_grad</em><strong> </strong>is a boolean which tells if the parameter is learnable or not. Since all the params in the model have <strong>requires_grad</strong> <strong>= True</strong>, it means that all the parameters are learnable and will update on training the model. Had it been set to <strong>False</strong> for a any specific <em>param</em>, that parameter’s weight would not update on training the model.</p><p>So, <em>requires_grad</em> is the flag that you might want to change when you want to <em>train/freeze</em> a specific set of layers of your model.</p><p>Now we will try to freeze all but the last layer of the model. If we go through all the names of all the parameters of the model, we can see that the name of the last layer is <em>‘fc’</em> which stands for ‘fully connected’.</p><p>So let’s freeze all the parameters except the ones with their names <em>‘fc.weight’</em> or <em>‘fc.bias’</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/691f3137240cee571a13b0ed027ec865/href">https://medium.com/media/691f3137240cee571a13b0ed027ec865/href</a></iframe><p>We can verify that the desired changes have been made successfully by printing out the <em>requires_grad</em> for all the parameters of the model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b5adcb83f98b727a92c73c5b8cd6271/href">https://medium.com/media/9b5adcb83f98b727a92c73c5b8cd6271/href</a></iframe><p>We can see that the desired changes have been made successfully !</p><p>So we have learnt how to change the <em>requires_grad</em> flag for any desired parameter of the model. And we have also learnt that doing so can come in very handy in situations where we want to <em>learn/freeze</em> the weights of some specific parameters/layers in a model.</p><p>We will now learn 2 of the widely known ways of saving a model’s weights/parameters.</p><ol><li>torch.save(model.state_dict(), ‘weights_path_name.pth’) <br> It saves only<strong> </strong>the <strong>weights</strong> of the model</li><li>torch.save(model, ‘model_path_name.pth’) <br>It saves the entire model (the <strong>architecture as well as the weights</strong>)</li></ol><h3>What Is state_dict() And Where To Use It ?</h3><p>We will first see how to write the syntax for <em>state_dict</em>. It’s pretty easy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a813ddbceec4fc3eff8b14368758ed97/href">https://medium.com/media/a813ddbceec4fc3eff8b14368758ed97/href</a></iframe><p>Its just a python’s ordered dictionary.</p><p>But, printing this, would result in chaos. So we wouldn’t print the <em>state_dict</em> for the entire model here, but I encourage you guys to go ahead and print it out on your screens !</p><p>I guess it’s a good time to divert a little from the topic.</p><p>See, printing <em>help(model)</em> tells us that model is an instance of <em>nn.Module</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b29606a9ac22789d94ad0882f527920a/href">https://medium.com/media/b29606a9ac22789d94ad0882f527920a/href</a></iframe><p>It could also be verified by using python’s isinstance function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28cb497a2fbda11008222f75dc418d97/href">https://medium.com/media/28cb497a2fbda11008222f75dc418d97/href</a></iframe><p>Is <em>model.fc</em> also an instance of <em>nn.Module</em> ?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fe917162a5a38b4cf8d26ca11e5662c/href">https://medium.com/media/1fe917162a5a38b4cf8d26ca11e5662c/href</a></iframe><p>Apparently yes !</p><p>But what exactly is <em>fc</em><strong>, </strong>and where does it come form ?</p><p>We can see what all <em>nn.Module</em> objects lie under the model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d90bd173e6c5f337cec2fcb7a9876c2/href">https://medium.com/media/0d90bd173e6c5f337cec2fcb7a9876c2/href</a></iframe><p>The <em>named_children()</em> applied on any <em>nn.Module</em> object returns all it’s immediate children (also <em>nn.Module</em> objects). Looking at the results of the above written piece of code, we know that <em>‘sequential’, ‘layer1’, ‘layer2’,</em> and <em>‘fc’</em> are all the children of model and all of these are <em>nn.Module</em> class objects. Now we all know where <em>‘fc’</em> is coming from.</p><p>And you know what ? <em>state_dict()</em> works on any <em>nn.Module</em> object and returns all it’s immediate children(of class <em>nn.Module</em>).</p><p>So let’s try the <em>state_dict()</em> function on the <em>‘fc’</em> layer of the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0392daec174810f755506a5b0cc4122c/href">https://medium.com/media/0392daec174810f755506a5b0cc4122c/href</a></iframe><p>Remember that <em>model.fc.state_dict()</em> or any <em>nnModule.state_dict()</em> is an <strong>ordered dictionary</strong>. So iterating over it gives us the keys of the dictionary which can be used to access the parameter tensor which, by the way, is not a <em>nn.Module</em> object, but a simple <em>torch.Tensor</em> with a <em>shape</em> and <em>requires_grad</em> attribute.</p><p>So it must be noted that when we save the <em>state_dict()</em> of a <em>nn.Module</em> object e.g. the model, the <em>torch.Tensor</em> objects are saved !</p><p>This is how we save the <em>state_dict</em> of the entire model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47c9a09fba37dbde4d642089e05a3c5e/href">https://medium.com/media/47c9a09fba37dbde4d642089e05a3c5e/href</a></iframe><p>This makes a <em>‘weights_only.pth’</em> file in the working directory and it holds, in an ordered dictionary, the <em>torch.Tensor</em> objects of all the layers of the model.</p><p>We will try to load the saved weights now. But before we do that, we need to define the model architecture first. It makes sense to define the model first and then to load the weights in it because the saved information is <strong>just</strong> the weights and <strong>not</strong> the model architecture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87c522f9d08690269eef40ad75403886/href">https://medium.com/media/87c522f9d08690269eef40ad75403886/href</a></iframe><p>Once the weights are loaded in the defined model, let’s check the <em>requires_grad</em> attribute of all the layers of model_new.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05a747cf8ad24ad5f9329a47b9482ffd/href">https://medium.com/media/05a747cf8ad24ad5f9329a47b9482ffd/href</a></iframe><p>Wait ! What ?</p><p>What happened to all the <em>requires_grad</em> flags that we had set for all the different layers ? It seems like all the <em>requires_grad</em> flags have been reset to <strong>True</strong>.</p><p>Actually, we never saved the <em>required_grad</em> flag of the parameters in the first place. Remember, a <em>state_dict</em><strong> </strong>is simply a python dictionary object that maps each layer to its parameter tensor. It does not save the <em>requires_grad</em> attribute of the parameters.</p><p>So we would need to again make the necessary changes to the <em>requires_grad</em> attribute of all the parameters before resume training of the model for more epochs</p><h3>How To Save The Entire Model And When To Do It ?</h3><p>Yes we have this second way of saving things, in which we can save the entire model too. By entire model, I mean the <strong>architecture</strong> of the model as well as it’s <strong>weights</strong>.</p><p>So we will resume from the point where we had frozen all but the last layer (the <em>‘fc’</em> layer) of the model and save the entire model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8eb06ecc2e957ab971b57ddab09b925/href">https://medium.com/media/b8eb06ecc2e957ab971b57ddab09b925/href</a></iframe><p>This makes a <em>‘entire_model.pth’</em> file in the working directory and it contains the model architecture <strong>as well as</strong> the saved weights.</p><p>We will try to load the saved model now. And this time, we do not need to define the model architecture as the information about the model architecture is already stored in the saved file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63be818266fd50015de780adc7968e17/href">https://medium.com/media/63be818266fd50015de780adc7968e17/href</a></iframe><p>Once the model is loaded, let’s check the <em>requires_grad</em> attribute of all the layers of model_new.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0a22484ed073418e483ac46b7c34f0d/href">https://medium.com/media/c0a22484ed073418e483ac46b7c34f0d/href</a></iframe><p>That is exactly what we wanted to see, isn’t it ? :D</p><p>So when we saved the entire model, we saved the <em>nn.Module</em> object and doing so saves the <em>requires_grad</em> flags of all it’s parameters too.</p><h4>I would strongly suggest you guys to fork this <a href="https://www.kaggle.com/n0obcoder/things-to-know-about-saving-weights-in-pytorch"><strong>public kaggle kernel </strong></a>and play with the code, to get the feel of it !</h4><h3><strong>Summary</strong></h3><p>We learnt a lot of things in this blog.</p><ol><li>Applying <strong><em>named_parameters()</em></strong> on an <em>nn.Module</em> object e.g. <em>model</em> or <br><em>model.layer2</em> or <em>model.fc</em> returns all the names and the respective parameters. These parameters are <em>nn.Parameter</em> (subclass of <em>torch.Tensor</em>) objects and therefore they have <em>shape</em> and <em>requires_grad</em> attributes.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a4b1f7ca69e4047f40f726d79353fdd/href">https://medium.com/media/7a4b1f7ca69e4047f40f726d79353fdd/href</a></iframe><p>2. The <strong><em>requires_grad</em></strong> attribute of a <em>nn.Parameter</em> object (learnable parameter object) decides whether to train or freeze a particular parameter. For example, if we want to freeze the <em>layer1</em> of the model, we would use the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6489116e1a35dabe15ef18eed67ccc6/href">https://medium.com/media/a6489116e1a35dabe15ef18eed67ccc6/href</a></iframe><p>3. Applying <strong><em>named_children()</em></strong> on any <em>nn.Module</em> object returns all it’s immediate children (also <em>nn.Module</em> objects).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88afcdc68d7d94b02dd1fa1f312d9a91/href">https://medium.com/media/88afcdc68d7d94b02dd1fa1f312d9a91/href</a></iframe><p>4. A <strong><em>state_dict()</em></strong> of any <em>nn.Module</em> object e.g. <em>model</em> or <em>model.layer2</em> or <em>model.fc</em> is simply a python <strong>ordered dictionary</strong> object that maps each parameter to its parameter tensor (<em>torch.Tensor</em> object). The <strong>keys</strong> of this ordered dictionary are the names of the parameters, which can be used to access the respective parameter tensors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f3aee709782b0dcf632435db16747ff/href">https://medium.com/media/6f3aee709782b0dcf632435db16747ff/href</a></iframe><p>5. Saving a <em>nn.Module</em> object’s <em>state_dict</em> only <strong>saves the</strong> <strong>weights</strong> of the various parameters of that object and <strong>not the model architecture</strong>. Neither does it involve the <strong>requires_grad</strong> attribute of the weights. So before loading the <em>state_dict</em>, one must define the model first.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e19837404cf182ce6cfac8220b003224/href">https://medium.com/media/e19837404cf182ce6cfac8220b003224/href</a></iframe><p>6. Entire model (<em>nn.Module</em> object) can also be saved which would include the <strong>model architecture as well as its weights</strong>. Since we are saving the <em>nn.Module</em> object, the <strong>requires_grad</strong> attribute is also <strong>saved</strong> this way. Also we don’t need to define the model architecture before loading the saved file since the saved file already has the model architecture saved in it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83d5b2ed9dea3d09a3a9d38eb3d02d98/href">https://medium.com/media/83d5b2ed9dea3d09a3a9d38eb3d02d98/href</a></iframe><p>7. Saving the <em>state_dict</em> can be used to only save the weights of the model. It doesn’t save the <em>required_grad</em> flag, whereas saving the entire model does save the model architecture, it’s weights and the <em>requires_grad</em> attributes of all its parameters.</p><p>8. Both <em>state_dict</em> as well as the entire model can be saved to make inferences.</p><p>I am writing this blog because I have learnt a lot by reading other’s blogs and I feel that I should also write and share my learnings and knowledge, as much as I can. So please leave your feedback in the comments section down below. Also I am new to writing blogs, so any suggestions on how to improve my writing would be appreciated ! :D</p><p>Also I am an independent music artist who likes to play and record music in free-time. Maybe you can check out my artist page on Spotify and show your support : )<br><a href="https://open.spotify.com/artist/7G2BgSnludIYl1gFyJKG6X?si=Bv5L4ZAVQrmIsl5SgGRAUw">8th Floor Harmony on Spotify!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=572651f3f8de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/everything-you-need-to-know-about-saving-weights-in-pytorch-572651f3f8de">Everything You Need To Know About Saving Weights In PyTorch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[word2vec (Skip-Gram model) Explained]]></title>
            <link>https://medium.datadriveninvestor.com/word2vec-skip-gram-model-explained-383fa6ddc4ae?source=rss-17fda0baf966------2</link>
            <guid isPermaLink="false">https://medium.com/p/383fa6ddc4ae</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[skip-gram]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[n0obcoder]]></dc:creator>
            <pubDate>Sun, 30 Jun 2019 18:43:16 GMT</pubDate>
            <atom:updated>2022-07-23T07:44:40.687Z</atom:updated>
            <content:encoded><![CDATA[<h3>Word2Vec (Skip-Gram model) Explained</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nqbuJjPXPWWek9jV" /><figcaption>Photo by <a href="https://unsplash.com/@sandym10?utm_source=medium&amp;utm_medium=referral">Sandy Millar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Word2Vec, as you might have guessed from the name itself, has something to do with words and vectors. But what exactly is it? Where do we use it? And most importantly, why do we even need it?</p><p>We will try to find answers to all these questions in this blog and then we will try to wrap our heads around the idea of Skip-Gram model, which is a fairly interesting yet a very simple concept to understand.</p><p><a href="https://www.datadriveninvestor.com/2019/03/03/editors-pick-5-machine-learning-books/">DDI Editor&#39;s Pick: 5 Machine Learning Books That Turn You from Novice to Expert | Data Driven Investor</a></p><p>So let’s get started !!!</p><p><strong>word2vec </strong>is a class of models that represents a word in a large text corpus as a vector in<strong> n-dimensional space</strong>(or n-dimensional feature space) bringing similar words closer to each other. One such model is the Skip-Gram model.</p><p><strong>Skip-gram model</strong> is one of the most important concepts in NLP (Natural Language Processing) and we must understand how exactly does it work, rather than just using an already implemented model or pre-trained embeddings (got no idea what embeddings mean ? Don’t worry we will get to that very soon !), which by the way is very easily available.</p><p>First, we need to understand that computers don’t understand words. All that a computer understands is numbers! Computers love numbers more than anything else. Well, maybe electricity comes first on the list. I think you guys got my point!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OUJT38pHXuQsxU9_" /><figcaption>Computers love numbers !</figcaption></figure><p>So we need to find a way to convert every given English word present in the dictionary, to number(s). There are two ways of doing that actually.</p><h3>One-Hot Encoding</h3><p>It is a way of representing categorical variables into vector forms(consisting of numbers, something that computers understand). The first thing to do when we are making One-Hot Encodings for a word present in our dictionary is to assign unique indices to all the words. This can be done by sorting the words in alphabetically ascending or descending order or maybe by arranging them in any random order. All we are interested in is mapping all the words to a unique index.</p><p>Once the word-to-index mapping is done, to make the One-Hot Encoding of a word, we make a vector of length equal to the total number of words present in our dictionary, and we put 0 everywhere but at the index of that particular word. We put 1 at that index. So our vector ends up having tons of zeros and only a single ‘1&#39;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*YWfZPB29CaALyfae" /><figcaption>These One-Hot Embeddings have ‘1’ only at the index mentioned on the left side</figcaption></figure><p>For example, imagine having a dictionary of 10,000 words.</p><pre>{‘a’, ‘aaron’ ..‘apple’...‘batman’...‘joker’...‘shinchan’... ‘zulu’}</pre><p>Its has ‘a’ at it’s 0th index, ‘aaron’ at 2nd index ‘zulu’ at 999th index.</p><p>One-Hot Encoding of ‘a’ will look like</p><pre>[1,0,0,0,0...0]</pre><p>One-Hot Encoding of ‘zulu’ will look like</p><pre>[0,0,0,0,0...1]</pre><p>I hope that you guys can come up with the One-Hot Encoding of any word, if you are given that word’s index in the word dictionary! 😄</p><h4>But there are a few problems with the One-Hot Encodings:</h4><ol><li>The length of the One-Hot Encoding can go up to 1 million(given a dictionary of 1 million words). This is a very <strong>sparse</strong> vector/encoding and is highly inefficient at storing data.</li><li>Such an encoding <strong>doesn’t preserve the semantic meaning</strong> of the word. Pick any distance metric, the<strong> distance</strong> between the One-Hot Encoding of any two words is <strong>always the same</strong>. Don’t you think it would be better to have encodings which could give us some idea about the semantic meaning of the words?</li></ol><p>This is where <strong>Continuous Vectors</strong> come into play !!!</p><h3>Continuous Vectors</h3><p>These are the vector representation of words which consist of real continuous numbers (not just 0 or 1). In this representation, there is no fixed rule for the length of such vectors. You can pick any length (any number of features) to represent words present in a given dictionary.</p><p>I am going to explain this to you by taking an example of words like <strong><em>‘Batman’</em>, <em>‘Joker’</em></strong>, <strong><em>‘Spiderman’</em></strong> and ‘<strong><em>Thanos’</em></strong>. Interesting selection of example words huh? I have made up 3-dimensional (<strong>3 features</strong>) continuous vectors of these words to explain to you, what the real numbers in the word vectors might represent.</p><pre>word2vec(‘Batman’) = [0.9, 0.8, 0.2]</pre><pre>word2vec(‘Joker’) = [0.8, 0.3, 0.1]</pre><pre>word2vec(‘Spiderman’) = [0.2, .9, 0.8]</pre><pre>word2vec(‘Thanos’) = [0.3, 0.1, 0.9]</pre><ol><li>It seems that the 1st feature represents the <strong>belongingness to the DC Universe</strong>. See that <em>‘Batman’</em> and <em>‘Joker’</em> have higher values for their 1st feature because they do belong to DC Universe.</li><li>Maybe the 2nd element in the word2vec representation here captures the <strong>hero/villian features</strong>. That’s why <em>‘Batman’ </em>and <em>‘Spiderman’</em> have higher values and, <em>‘Joker’</em> and <em>‘Thanos’</em> have smaller values.</li><li>One might say that the 3rd component of the word vectors represent the <strong>supernatural powers/abilities</strong>. We all know that <em>‘Batman’</em> and <em>‘Joker’</em> have no such superpowers and that’s why their vectors have small numbers at the 3rd position.</li></ol><p>I hope that you have now understood, how different dimensions in a <strong>continuous word vector</strong> might capture different <strong>semantic meaning/features</strong> of that word, something that One-Hot Encoding fails to capture!</p><h3>Where do the Embeddings come from?</h3><p>The word vectors/embeddings don’t come with the right numbers making up the vector. The embeddings capture semantic meaning only when they are trained on a huge text corpus, using some word2vec model. Before training, the word embeddings are randomly initialized and they don’t make any sense at all. It’s only when the model is trained, that the word embeddings have captured the semantic meaning of all the words.</p><p>The word embeddings can be thought of as a child’s understanding of the words. Initially, the word embeddings are randomly initialized and they don’t make any sense, just like the baby has no understanding of different words. It’s only after the model has started getting trained, the word vectors/embeddings start to capture the meaning of the words, just like the baby hears and learns different words.</p><p>The whole idea of Deep Learning has been inspired by a human brain. The more it sees, the more it understands and learns.</p><h3>Skip-Gram Model</h3><p>Skip-Gram model, like all the other word2vec models, uses a trick which is also used in a lot of other Machine Learning algorithms. Since we don’t have the labels associated with the words, learning word embeddings is not an example of supervised learning. This is semi-supervised learning because we don’t have the direct labels associated with the words but we use the neighboring words (of a context word in a sentence) as the labels.</p><h4>Generating Context-Target word</h4><p>Word2vec takes a large <a href="https://en.wikipedia.org/wiki/Text_corpus">corpus of text</a> as it’s input and produces a <a href="https://en.wikipedia.org/wiki/Vector_space">vector space</a> (<strong>feature space</strong>), typically of several hundred <a href="https://en.wikipedia.org/wiki/Dimensions">dimensions</a>, with each unique word in the <a href="https://en.wikipedia.org/wiki/Corpus_linguistics">corpus</a> being assigned a corresponding vector in the space. This is done by making context and target word pairs which further depends on the window size you take.</p><figure><img alt="Related image" src="https://cdn-images-1.medium.com/proxy/1*jX8qGZC3WOIm1LFvBNL5jA.png" /><figcaption>Keep Calm and read till the end!</figcaption></figure><p>Let’s understand this in more detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*G546QXnGFhwJ9bQe.png" /><figcaption>An overly used image which never fails to explain how exactly are the context-target word pairs are made to be used for the training of the Skip-Gram model.</figcaption></figure><p>The image above shows how context-target word pairs are made to be used for the training of Skip-Gram model. We use a <strong><em>window_size </em></strong>parameter (window_size is 2 in this case) which looks to the left and right of the context word for as many as window_size(=2) words.</p><p>Let me walk you through the process of making context-target word pairs.</p><ol><li>We have a sentence. We take the 1st word (<strong>‘<em>The’</em></strong>). This is our <strong><em>context word</em></strong>. We make pairs of this context word with the words on it’s right which are covered in the specified window(<strong><em>‘quick’ and ‘brown’</em></strong>). So this way we have 2 pairs. First pair being (<strong><em>‘The’, ‘quick’</em></strong>) and the second one being (<strong><em>‘The’, ‘brown’</em></strong>). We can’t pair the context word with the words on it’s left because there are no words on it’s left.</li><li>Now, we move to the 2nd word (<strong><em>context word</em></strong>) of the sentence (<strong><em>‘quick’</em></strong>) and pair it with words covered in the specified window (this time we have a word <strong><em>‘The’</em></strong> on it’s left too). So we end up making 3 pairs this time; (<strong><em>‘quick’, ‘The’</em></strong>), (<strong><em>‘quick’, ‘brown’</em></strong>), (<strong><em>‘quick’, ‘fox’</em></strong>)</li><li>And we keep on making context-target word pairs for all the possible <strong><em>context </em></strong>and <strong><em>target </em></strong>words. What we are essentially doing here is that we are capturing word pairs which can be found next to each other. We are capturing the <strong>context </strong>and we are going to use this context information to train the word embeddings<strong>. </strong>This is why I called this a <strong>semi-supervised learning algorithm</strong> earlier!</li></ol><p>Are you guys able to connect the dots now? : D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Eo5FlF-_o8a2WPtk.png" /><figcaption>When you start to understand the content of the blog that you have been reading for the last 10 mins</figcaption></figure><h4>Training</h4><p>So far we have our dictionary of 10,000 words ready and we also have the context-target word pairs.</p><p>We take the One-Hot Encoding of the context word and feed it into the shallow neural network. This input is multiplied with the weights of the hidden layers and the end, we get the output vector (also with 10,000 components).</p><p>Notice that the output layer has softmax applied to it which essentially converts the output vector of the neural network to a probability vector, with it’s each component representing the probability of the word at its index, being the target word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FD_ZSVKFywSg-CJM.png" /></figure><p>Then a loss function (Cross-Entropy Loss, because we treat this as a classification problem) is applied to compute the loss and back-propagation updates the weights (the word embeddings).</p><p>This is how word embeddings are trained !!!</p><h4>The Fake Task</h4><p>Once our context and target pairs are ready, we train a neural network with a very few hidden layers(maybe only a single hidden layer) to perform a certain task, but we are never going to use this neural network to perform this task that it was trained for. Instead, we are interested in the weights of the hidden layers that have been learned during the training process. These weights, are the word embeddings that we have been discussing from the beginning of this post!</p><p>This is called a ‘Fake Task’ because we are not interested in the prediction of the model, but the by-product(word vectors/embeddings) of the model.</p><h3>Pytorch and TensorFlow implementation of word2vec(Skip-Gram model)</h3><p>For the people, who want to get their hands dirty, here is a very simple implementation of word2vec (Skip-Gram-Model) in both,<strong> </strong><a href="https://github.com/n0obcoder/Skip-Gram-Model-PyTorch"><strong>PyTorch</strong> </a>and <a href="https://github.com/n0obcoder/Skip-Gram_Model-TensorFlow"><strong>TensorFlow</strong></a>.</p><p>In these implementations, I used a corpus from <strong>gensim</strong> library. I did some preprocessing on it, made a word dictionary, generated context-target word pairs and trained a single layer neural network.</p><p>Once the embeddings were trained, I used TSNE to reduce the dimensionality of the embeddings for a set of words, so that the embeddings could be visualized on a 2D plot. And this is what I got!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*h9qgem6GV0UuJysk" /><figcaption>Word Embeddings trained using Skip-Gram model</figcaption></figure><h3>Insights from the Trained Embeddings</h3><p>You can notice that words like <strong><em>‘sun’ </em></strong>and <strong><em>‘earth’ , </em></strong>with similar semantic meanings, have their 2D embeddings very close to each other.</p><p>Also the words like <strong><em>‘energy’</em></strong> and <strong><em>‘exploit’ , </em></strong>share some context which, my model was able to capture, and that’s why these two words have their 2D embeddings placed close to each other.</p><p>This is a decent result, considering the small size of the text corpus that the model was trained on.</p><h3>For those who Like to Watch</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwvsE8jm1GzE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwvsE8jm1GzE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwvsE8jm1GzE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ead71438f5d9f64e51933564a193d68/href">https://medium.com/media/9ead71438f5d9f64e51933564a193d68/href</a></iframe><p>I am writing this blog because I have learned a lot by reading other’s blogs and I feel that I should also write and share whatever I know as much as I can. So please leave your feedback in the comments section down below. Also, I am new to writing blogs, so any suggestions on how to improve my writing would be appreciated! :D</p><p>Also I am an independent music artist who likes to play and record music in free-time. Maybe you can check out my artist page on Spotify and show your support : )<br><a href="https://open.spotify.com/artist/7G2BgSnludIYl1gFyJKG6X?si=Bv5L4ZAVQrmIsl5SgGRAUw">8th Floor Harmony on Spotify!</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383fa6ddc4ae" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/word2vec-skip-gram-model-explained-383fa6ddc4ae">word2vec (Skip-Gram model) Explained</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[k-Means Clustering Explained (Part II: Python Implementation from Scratch !)]]></title>
            <link>https://medium.com/@animesh7pointer/k-means-clustering-explained-part-ii-python-implementation-from-scratch-867a571e535c?source=rss-17fda0baf966------2</link>
            <guid isPermaLink="false">https://medium.com/p/867a571e535c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[n0obcoder]]></dc:creator>
            <pubDate>Thu, 20 Jun 2019 20:42:41 GMT</pubDate>
            <atom:updated>2022-07-23T07:44:58.138Z</atom:updated>
            <content:encoded><![CDATA[<h3>k-Means Clustering Explained (Part II: Python Implementation from Scratch !)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k7PcIoQUGkr1b2Jb" /><figcaption>Photo by <a href="https://unsplash.com/@zoner?utm_source=medium&amp;utm_medium=referral">Maxim Dužij</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are not aware of the inside of k-Means Clustering Algorithm, I would strongly recommend you guys to check<a href="https://medium.com/@animesh7pointer/k-means-clustering-explained-part-i-theory-8983a9631588?postPublishedType=initial"> k-Means Clustering Explained (Part I: Theory)</a> out.</p><p>Once you guys have a decent understanding of this algorithm, we are good to dive into the implementation of this clustering algorithm using Python from scratch !</p><p>Like any other implementation tutorial, we start off with importing the libraries that we are going to use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da8b61016d51bb2960c5c22233fc9a98/href">https://medium.com/media/da8b61016d51bb2960c5c22233fc9a98/href</a></iframe><p>Next, we want a data generator function that could make fake data for us to cluster them. For the sake of simplicity, we are going to be working on 2-dimensional data. In general, 2D data is always simple to visualize. But there are a few people like Pogo and Deepi, who can even visualize 300-dimensional data 👽 Here is the <a href="https://medium.com/@animesh7pointer/k-means-clustering-explained-part-i-theory-8983a9631588">reference</a> if you guys din’t get the last line 😛</p><p>So we define a data generator function which would generate data points falling in the same cluster. We want the function to take in the <strong>center </strong>(2-dimensional coordinates) of this cluster and the <strong>number of data points</strong> to be created and return us the data points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/445598fc3d81976b2dcd49a1a883716f/href">https://medium.com/media/445598fc3d81976b2dcd49a1a883716f/href</a></iframe><p>Next, we make an empty<strong> np array</strong> and fill it with data points falling in different clusters by calling the gen_data() with varying it’s parameters (cluster centers and number of data points).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41ff4ad199976b5c5487aa921b3f9a45/href">https://medium.com/media/41ff4ad199976b5c5487aa921b3f9a45/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*jIBgs1UBs4bUBG9p" /><figcaption>Data points generated by calling get_gen( ) 3 times.</figcaption></figure><p>Now, we need to pick the value of <strong><em>k</em></strong> and initialize the k cluster centers vectors randomly. The cluster centers are bound to exist between the extremes of all the data points that we have. So we first find out the extremes of the data points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb9b46f5998c550ac99288709ed22100/href">https://medium.com/media/fb9b46f5998c550ac99288709ed22100/href</a></iframe><p>Next, we define a function which would take in the <strong><em>k</em></strong> cluster center points and plot them together. This function would be very helpful when we call them after every iteration of the algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b4b27a9efe989b30d0beaaff34c1b74/href">https://medium.com/media/4b4b27a9efe989b30d0beaaff34c1b74/href</a></iframe><p>Let’s, plot the randomly initialized cluster centers on top of all the data points that we have created using the fen_data() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1b702aba808dcc2b882f8c5ebac9b6f/href">https://medium.com/media/c1b702aba808dcc2b882f8c5ebac9b6f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*llxLhYNb2mAu03BN" /><figcaption>Initialization of k cluster centers(Red dots) randomly, where k = 3</figcaption></figure><p>We need a way to know which data points fall under which cluster . We can get this information by creating a list which would contain the cluster information of all the data points encoded in color names.</p><p>Initially we color all the data points ‘Gray’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2d8b56dd5b3e6947ec2712b942cf71b/href">https://medium.com/media/d2d8b56dd5b3e6947ec2712b942cf71b/href</a></iframe><p>We need another helper function which would map a data point to one of the existing k cluster centers. A data point is assigned to a cluster whose center is nearest to that data point. Isn’t this so simple !</p><p>All we need to do is compute Euclidean distances between a data point and all the k cluster centers, for all the data points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/351685d2a6d72de7677d5bc228f0aad6/href">https://medium.com/media/351685d2a6d72de7677d5bc228f0aad6/href</a></iframe><p>Once, all the data points are assigned a cluster, we need to recompute new cluster centers. And also we need to compare how much a cluster center has shifted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ec37f45ec89d128fa0b3c8e779b8a27/href">https://medium.com/media/9ec37f45ec89d128fa0b3c8e779b8a27/href</a></iframe><p>We set the maximum number of iterations the algorithm would run for.</p><p>Also we need a way to stop the algorithm before running maximum number of iterations in case when all the cluster centers have converged(when they stop shifting much). We can do this by creating a list of length equal to the number of clusters k and fill it with False. At the end of every iteration, for every cluster center, we check if the shift is less than a certain threshold, we change the stop list to True for that particular cluster. And when all the elements of the stop list are True, we stop the algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fff17cde4a0876b8c8db36115803fea4/href">https://medium.com/media/fff17cde4a0876b8c8db36115803fea4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*W9jX4w3hj4rpZAH6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*6PXBtGqRa_ZeLuc7" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ySIreQhc5U93ndL8" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*oNFONSclnzS2RHNV" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*GcjXJCGPbwREW5Mc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*T7DfPOel22RZjqj5" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*IT9rSolVA1HyBZtn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*hmW5t_95keXkl46C" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*4y-JjH7d0qCT7byG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*fuQPsFl3g6AQJoXn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*TCCmtMhw8moNaxof" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Sm3Lsa7fE-wAIY3G" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*SZenW_hZcJNteWs0" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*H8hJlvG28nnCQ5DP" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*KcAlqUnAKhUcisjJ" /><figcaption>See how the cluster centers (Red dots) move !</figcaption></figure><p>If you guys have <strong>any</strong> doubts regarding the theory or the code, please let me know in the comments section down below. I will try to respond and clarify your doubts as soon as possible :D</p><p>I hope that this blog was helpful to you.</p><p>You guys can find the whole code<strong> </strong><a href="https://github.com/n0obcoder/ClusteringAlgos/tree/master/kMeans"><strong><em>here</em></strong></a><em> </em>on my github page.</p><p>I am writing this blog because I have learnt a lot by reading other’s blogs and I feel that I should also write and share whatever I know, as much as I can. So please leave your feedback in the comments section down below. Also I am new to writing blogs, so any suggestions on how to improve my writing would be appreciated ! :D</p><p>Also I am an independent music artist who likes to play and record music in free-time. Maybe you can check out my artist page on Spotify and show your support : )<br><a href="https://open.spotify.com/artist/7G2BgSnludIYl1gFyJKG6X?si=Bv5L4ZAVQrmIsl5SgGRAUw">8th Floor Harmony on Spotify!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=867a571e535c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[k-Means Clustering Explained (Part I: Theory)]]></title>
            <link>https://medium.com/@animesh7pointer/k-means-clustering-explained-part-i-theory-8983a9631588?source=rss-17fda0baf966------2</link>
            <guid isPermaLink="false">https://medium.com/p/8983a9631588</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <dc:creator><![CDATA[n0obcoder]]></dc:creator>
            <pubDate>Sat, 15 Jun 2019 10:25:49 GMT</pubDate>
            <atom:updated>2022-07-23T07:41:11.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*68LI-FMbuy4opj2f" /><figcaption>Photo by <a href="https://unsplash.com/@henryatto?utm_source=medium&amp;utm_medium=referral">Henry Lorenzatto</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Clustering ?</h3><p>Pogo visits his friend’s place. His friend, Deepi, is an anthophile (a person who loves flowers). Deepi has a big pile of flowers in his backyard, all of them belonging to the same species, but of different colors!</p><p>Deepi asks Pogo if he can create <em>Clusters</em> out of the pile of flowers lying in his background. Pogo looks at the pile of flowers. He sees that all of the flowers look almost the same. They have very similar characteristics in all but one aspect, their color!</p><p>So Pogo simply puts all the flowers, having the same color, in a separate basket and goes on to enjoy some chilled beer with his buddy Deepi.</p><h3>So what exactly happened here ?</h3><p>Pogo basically performed the task of grouping a set of objects (flowers in his case) in such a way that the objects in the same group (called a <strong>Cluster</strong>) share some <strong>common features</strong> (color being the common feature in his case) with each other than to those in the other groups.</p><p>I hope that you now have got a decent understanding of what Clustering means.</p><p>Little more formally, Clustering is an <strong>unsupervised Machine Learning algorithm</strong> that involves grouping of data points. In theory, data points falling in the same cluster should have similar characteristics/features, while data points falling in different clusters should have highly dissimilar properties/features.</p><p>In Data Science, we use clustering analysis to get some valuable insights from our data by seeing what groups the data points fall into when we apply a clustering algorithm. Clustering reveals the underlying pattern or the structure of the data points, which otherwise would go unnoticed.</p><p>There are various clustering algorithms out there. But I am going to talk about the first ever clustering algorithm that I had come across, and it’s a very simple one. Its called the <strong>k-Means Clustering.</strong></p><h3>k-Means Clustering</h3><p>It is one of the simplest and easy to implement unsupervised learning algorithms that solves the problem of clustering.</p><h4>Steps involved in k-Means Clustering Algorithm</h4><ol><li>We start with a value of k, the number of clusters/classes/groups that we want to create in the given dataset and we initialize the k cluster centers in the n-dimensional feature space. It’s good to take a look at the data and try to come up with the number of distinct clusters, k. Note that all the k cluster centers are n-dimensional vectors, in the n-dimensional feature space.</li><li>Each data point is classified to one of the k cluster centers, by computing it’s distance with all the k cluster centers, and then classifying the point to the cluster whose center is closest to it.</li><li>Based on these classified points, we recompute the group center by taking the mean of all the n-dimensional vectors in the group.</li><li>We repeat these steps until the cluster centers don’t change much (untill the cluster centers converge).</li></ol><h4>Advantages</h4><ol><li>k-Means is really fast. Computing the distances between the data points and the cluster centers is all that we are doing here. It has a linear complexity <em>O(n)</em></li><li>It’s very easy to understand and implement from scratch using just Numpy.</li></ol><h4>Disadvantages</h4><ol><li>We have to select the number of clusters <em>k</em> ,that we want to be created in the dataset. This is not a very simple task and ideally we would want the clustering algorithm to figure that out for us.</li><li>k-Means starts off by initializing the k cluster centers randomly. It therefore, has chances to yield different cluster outputs every time we run the algorithm. Other clustering algorithms are more consistent.</li><li>Since this algorithm involves taking means of all the n-dimensional data points falling in a group to calculate the new cluster center, it is sensitive to outliers.<br> <br>This problem can be solved by using the k-Medians clustering algorithm, where we take medians and not means of all the n-dimensional data points falling in a group to calculate the new cluster center. This method is not sensitive to outliers as we are using medians here. But this method is slower for larger datasets as sorting is also required on each iteration when computing the n-dimensional median vector.</li><li>This learning algorithm is not invariant to non-linear transformations<strong> </strong>i.e.<strong> </strong>with different representations of data we get different results (data represented in form of cartesian co-ordinates and polar co-ordinates will give different results).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*81hF6UVtymJ9upj0" /><figcaption>Get Your Hands Dirty in Part II</figcaption></figure><p>If you guys want to get your hands dirty, you should definitely check out <a href="https://medium.com/@animesh7pointer/k-means-clustering-explained-part-ii-python-implementation-from-scratch-867a571e535c?postPublishedType=initial">k-Means Clustering Explained (Part II: Python Implementation)</a></p><p>I am writing this blog because I have learnt a lot by reading other’s blogs and I feel that I should also write and share whatever I know as much as I can. So please leave your feedback down below in the comments section. Also I am new to writing blogs, so any suggestions on how to improve my writing would be appreciated ! :D</p><p>Also I am an independent music artist who likes to play and record music in free-time. Maybe you can check out my artist page on Spotify and show your support : )<br><a href="https://open.spotify.com/artist/7G2BgSnludIYl1gFyJKG6X?si=Bv5L4ZAVQrmIsl5SgGRAUw">8th Floor Harmony on Spotify!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8983a9631588" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>