<?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 Rishav Sharma on Medium]]></title>
        <description><![CDATA[Stories by Rishav Sharma on Medium]]></description>
        <link>https://medium.com/@rvs?source=rss-9743e6420231------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Rishav Sharma on Medium</title>
            <link>https://medium.com/@rvs?source=rss-9743e6420231------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:49:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rvs/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[How to build a Database of all the songs you have ever heard using Python?]]></title>
            <link>https://rvs.medium.com/how-to-build-a-database-of-all-the-songs-you-have-ever-heard-using-python-b34dfd4f5f3d?source=rss-9743e6420231------2</link>
            <guid isPermaLink="false">https://medium.com/p/b34dfd4f5f3d</guid>
            <category><![CDATA[music]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rishav Sharma]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 06:32:19 GMT</pubDate>
            <atom:updated>2022-01-16T07:10:24.021Z</atom:updated>
            <content:encoded><![CDATA[<p>A guide and a step towards extreme OCD for organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*-20JFaETY8Z7ydDabL2c8A.gif" /><figcaption>Wordcloud animation of all the words associated with the music I heard.</figcaption></figure><p>How cool would it be if you could own a database of all the songs you have ever heard?<br>You could listen to songs that you no longer remember and <strong>reminisce the memories</strong> associated with them. It was a simple idea, but the question is where does one start?</p><p><strong>Episodes:</strong></p><ol><li><strong>The data challenge and solution.</strong></li><li><strong>Isolating music — Automated + Manual</strong></li><li><strong>Manual checks and building the final database.</strong></li><li><strong>Word cloud animation.</strong></li><li><strong>How can you make my own database?</strong></li></ol><h4>1. The data challenge and solution</h4><p>The majority of us listen to songs on multiple platforms, but my go-to platform for the past couple of years has been <strong>YouTube music</strong>. So, that became the starting point. Before attempting to build a music database, I first needed the data of everything I have ever watched on YouTube.<br>The idea?<br>Get the history data from YouTube, figure out which videos are music, and voila!<br>But things didn’t turn out as straightforward.</p><p><strong>First thought</strong>: Can the YouTube API provide me the data of my watched history? I explored for a bit but could not find anything concrete. Closed!</p><p><strong>Second thought</strong>: Do I need to scrape the data myself from the history page? Ugh! I don’t want to do this. Let’s keep thinking.</p><p>The third thought came as a savior. Google allows users to download ALL of their data with their project — <a href="https://takeout.google.com/settings/takeout">Google Takeout</a>. A user can visit Google Takeout and download the required YouTube history data. Steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFKgfmJNgAOUduYGFQsCdQ.png" /><figcaption>Optionally, you can export just the history by choosing history from All YouTube data included.</figcaption></figure><p>i) Open the site and click on Deselect all. Check the YouTube and YouTube Music option as shown in the screenshot.</p><p>ii) Click on Next step.</p><p>iii) Keep everything checked to default and click Export.<br><em>Note</em>: You can choose the file format for your history. Options include HTML and JSON. For this task, JSON is more suitable.</p><p>Now, you have your entire YouTube history. Sorry, Incognito mode users :P</p><p>You can navigate to the ‘<strong>watch-history.json</strong>’(or .html) file in your downloaded Takeout folder. That is all we need, and now we can start building the database.</p><h4>2. <strong>Isolating music — Automated + Manual</strong></h4><p>Now begins the challenge. Not only do you have to fetch all details of a video from YouTube but you also need to use those details to somehow classify a video as music or not music. Machine Learning? Do we need you?</p><p>Not really…</p><p><strong><em>What features does YouTube provide for every video</em></strong>?</p><p>→ Title, Tags, and Description, right? So, I thought. But there is something more. YouTube has a <a href="https://gist.github.com/dgp/1b24bf2961521bd75d6c">Category ID</a> attribute that classifies a video into a category. The Category ID for music is <strong>10</strong>.</p><p>→ So, does this mean that all one needs to do is filter the videos by Category ID, and their database is ready? Sadly no :( <br>Like any Machine Learning task, this classification by YouTube is not 100% accurate.</p><p>So, how accurate is it exactly? <strong>How can we test the accuracy of music videos being classified correctly by the Category ID? </strong>I did it as follows:-</p><p>→ I found a public playlist of the <a href="https://www.youtube.com/watch?v=JGwWNGJdvx8&amp;list=PLhsz9CILh357zA1yMT-K5T9ZTNEU6Fl6n">most viewed songs on YouTube</a> with the idea that I can check the category ID of all the videos present in this playlist and get an estimate of how accurate the inbuilt classification is.</p><p>→ I wrote <a href="https://github.com/rvs-23/SongsDatabase/blob/main/0.%20music_vid_identify/how_to_identify_a_music_video.py">a script</a> that inputs any playlist ID and figures out the category ID of all the videos present in that playlist. When I executed the script with the above music playlist, I found that around <strong>90.3% </strong>of the videos had a category 10. So, in a rough sense, 90.3% of the music videos were identified by category ID 10. The result is not bad, but can we improve it further?</p><p>One strategy that we could use is as follows:</p><ul><li>Figure out the <strong>category ID</strong> of all the videos from the most played music playlist and store the Top-2 category ID’s (accounts for <em>97.1%</em> of music videos).</li><li>Create a list of <strong>Tags </strong>associated with all the videos in the playlist, and store the 750 most commonly used Tags with music videos in that playlist.</li><li>Create a string of <strong>Video descriptions</strong> and store the 250 most commonly used words that frequently appear in music video descriptions.</li></ul><p>Using a combination of the above, we are more likely to filter the videos accurately when compared with using Category ID=10 alone. <a href="https://github.com/rvs-23/SongsDatabase/blob/main/0.%20music_vid_identify/how_to_identify_a_music_video.py">Here</a> is the Python script that applies our strategy and stores the results of the Top Category, Top tags, Top Description words in a <a href="https://github.com/rvs-23/SongsDatabase/tree/main/0.%20music_vid_identify/music_identify_data">pickle file</a>.</p><pre>r&#39;&#39;&#39;</pre><pre>Once we have obtained a list of videos along with all the necessary details from <br>our history, how do we identify if a particular video is a MUSIC video?</pre><pre>Idea: we could use a combination of CategoryID, Video Tags and Description words.<br>Problem: How do we know which values to pick?</pre><pre>Solution:<br>    This script experiments with a playlist of ONLY MUSIC videos to figure out<br>    the most common CategoryID, Video Tags and Description assigned for music videos.</pre><pre>Playlist used: <a href="https://www.youtube.com/watch?v=JGwWNGJdvx8&amp;list=PLhsz9CILh357zA1yMT-K5T9ZTNEU6Fl6n">https://www.youtube.com/watch?v=JGwWNGJdvx8&amp;list=PLhsz9CILh357zA1yMT-K5T9ZTNEU6Fl6n</a></pre><pre>This playlist contains around 5000 most played music videos on YouTube. We<br>    could use information from these videos to create a system that can best<br>    identify a music video.</pre><pre>&#39;&#39;&#39;</pre><pre>import os<br>import string<br>from collections import Counter<br>import pandas as pd<br>import pickle<br>from nltk.corpus import stopwords<br>from googleapiclient.discovery import build</pre><pre># If you have never downloaded list of stopwords before, uncomment the following lines:<br># import nltk<br># nltk.download(&#39;stopwords&#39;)</pre><pre># Opening the API key.<br>base_path = os.path.dirname(__file__)<br>with open(os.path.join(base_path, &#39;../_private_data/api_key.txt&#39;), &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:<br>    api_key = f.read()<br>    <br># Creating a YouTube resource<br>yt = build(&#39;youtube&#39;, &#39;v3&#39;, developerKey=api_key)</pre><pre>####################################################</pre><pre># Variable to keep track of pages from the playlist.<br>nextPageToken = None</pre><pre># List to store the video details from the playlist<br>all_video_details = []</pre><pre>playlist_id = &#39;PLhsz9CILh357zA1yMT-K5T9ZTNEU6Fl6n&#39;<br># What&#39;s the idea, here?<br># We loop through each page of the playlist, fetch the video ID of all present<br># videos, fetch the details of those videos and append them to a list. Repeat<br># the process, until the playlist pages are exhausted.<br>while True:<br>    # YouTube resource to fetch playlist video IDs.<br>    pl_req = yt.playlistItems().list(<br>        part=&#39;contentDetails&#39;,<br>        playlistId=playlist_id,<br>        maxResults=50,<br>        pageToken=nextPageToken<br>        )<br>    pl_response = pl_req.execute()</pre><pre># Fetching the video ID&#39;s of 50 (maximum allowed) videos.<br>    video_ids = []<br>    for item in pl_response[&#39;items&#39;]:<br>        video_ids.append(item[&#39;contentDetails&#39;].get(&#39;videoId&#39;))</pre><pre># YouTube resource to fetch details of the obtained 50 videos.<br>    # snippet contains Title, Tags, Description and CategoryID.<br>    vid_req = yt.videos().list(<br>        part=&#39;snippet&#39;,<br>        id=&#39;,&#39;.join(video_ids)<br>        )<br>    vid_response = vid_req.execute()</pre><pre># Adding the necessary information to a dictionary and appending<br>    # to a list for all the playlist videos.<br>    for details, yt_id in zip(vid_response[&quot;items&quot;], video_ids):<br>        snippet = details[&quot;snippet&quot;]<br>        # Fetching the necessary details from the snippet key<br>        every_video_detail = dict(<br>            VideoID=yt_id,<br>            Title=snippet.get(&quot;title&quot;),<br>            CategoryID=snippet.get(&quot;categoryId&quot;),<br>            PublishDate=snippet.get(&quot;publishedAt&quot;),<br>            ChannelTitle=snippet.get(&quot;channelTitle&quot;),<br>            Description=snippet.get(&quot;description&quot;),<br>            Tags=snippet.get(&quot;tags&quot;),<br>        )<br>        all_video_details.append(every_video_detail)</pre><pre># Returns None if we have exhausted all pages. Break if it returns None.<br>    # not None returns True.<br>    nextPageToken = pl_response.get(&#39;nextPageToken&#39;)<br>    if not nextPageToken:<br>        break</pre><pre>df = pd.DataFrame(all_video_details)</pre><pre>######################################</pre><pre># 1. Filtering most used CategoryID<br># Filtering the top 2 CategoryIDs which YT identifies as music.<br>top_categories = df[&#39;CategoryID&#39;].value_counts()[:2]<br>print(f&quot;Fetched top-2 categories that account for {round(sum(top_categories)/len(df)*100, 2)} % music videos...&quot;)</pre><pre># 2. Filtering most used Tags<br># The tags column contains a list of tags associated with each video.<br># Creating a single list of all the tags associated with the videos.<br>all_tags = [<br>    tag.lower() for tags in df[&#39;Tags&#39;].tolist() if tags is not None for tag in tags<br>    ]<br># Fetching the top 1000 most common tags in music videos.<br>top_tags = Counter(all_tags).most_common(750)<br>print(f&quot;Fetched {len(top_tags)} most common tags...&quot;)</pre><pre># 3. Filtering most used Description words<br>desc_words = &#39;&#39;.join(df[&#39;Description&#39;].str.lower()).split()<br># From these words, we need to remove the stop words.<br>stopwords_en = stopwords.words(&#39;english&#39;)<br>desc_words_filtered = [word for word in desc_words if word not in stopwords_en]<br># Fetching the 250 most common words in description<br>desc_most_common = Counter(desc_words_filtered).most_common(250)<br>desc_most_common = [word for word in desc_most_common if word[0] not in string.punctuation]<br>print(f&quot;Fetched {len(desc_most_common)} most common words...&quot;)</pre><pre>print(&quot;Dumping categories, tags and most common words into pickle...&quot;)<br>with open(os.path.join(base_path, &#39;music_identify_data/top_categories.pkl&#39;), &#39;wb&#39;) as cats:<br>    pickle.dump(top_categories, cats)</pre><pre>with open(os.path.join(base_path, &#39;music_identify_data/top_tags.pkl&#39;), &#39;wb&#39;) as tags:<br>    pickle.dump(top_tags, tags)</pre><pre>with open(os.path.join(base_path, &#39;music_identify_data/top_desc_words.pkl&#39;), &#39;wb&#39;) as desc:<br>    pickle.dump(desc_most_common, desc)</pre><pre>print(&quot;Complete...&quot;)</pre><p>We now have a strategy for our identification. Therefore, we can start building the database. We need to perform three separate tasks for extracting useful data and proper identification, which is present in these <a href="https://github.com/rvs-23/SongsDatabase/tree/main/1.%20modules">scripts</a>:</p><ul><li><strong>module_extract_urls</strong> → Script to extract all the watched video URLs from the HTML/JSON history file (<em>watch-history.json</em>).</li><li><strong>module_fetch_video_details</strong> → Script to fetch the details such as Title, Description, Tags, Duration of these watched videos using the Python YouTube API.</li><li><strong>module_identify_music_video</strong> → Script that uses our strategy to filter the videos. To implement, we create three flag columns called <em>TagsCheck</em>, <em>DescriptionCheck</em>, and <em>CategoryIDCheck. </em>They have values 1 if the video Tags, Category, and Description match the top categories, top tags, and top description words respectively, 0 otherwise. <br>We exclude videos that fail all 3 checks. We also exclude videos with duration 60s or lesser (YouTube shorts).</li></ul><h4><strong>3. Manual checks, and building the final database.</strong></h4><p>This <a href="https://github.com/rvs-23/SongsDatabase/blob/main/2.%20song_database/create_song_db_1.py">script</a> uses the above three modules in sequence to build an initial Database of all the videos that could be music. Let’s call this <strong>IDBM</strong>. At this point, I came to terms with the fact that automation can only take this so far. At one point, you need to manually check if certain videos are music or not. But, we can at least make that task as simple as possible. Therefore, we have the final <a href="https://github.com/rvs-23/SongsDatabase/blob/main/2.%20song_database/create_song_db_2.py">script</a> in place that does the following tasks:</p><p>— It breaks IDBM(Initial Database music) into three parts: definitely music(Y), definitely not music(N) and maybe music(Maybe).</p><p>— <strong>If the video category is 10 <em>or</em> if all three checks are 1, we classify the video as definitely music.</strong> The idea being that not all music videos have category 10, but those videos that have a category 10 are definitely music.</p><p>— If all three checks result in 0, we classify the video as definitely not music.</p><p>— For all other cases, we classify the video into the “maybe” category which will require manual checking. For these videos, we create a column called <strong>Is_Music_Manual</strong> with all values set to <strong>No</strong> initially. Now, all we need to do is create a copy of this, open, and for a music video, toggle the column’s value from a No to a <strong>Yes</strong>.</p><p>— We finally merge our definitely music data with the manually checked music data.</p><p>— Our database is ready :)</p><h4>4. <strong>Word cloud animation.</strong></h4><p>We have all heard that:</p><blockquote>A picture is worth thousand words.</blockquote><p>Here’s a rendition that I always use:</p><blockquote>An animation is worth a thousand pictures.</blockquote><p>The best way to see the most popular artist in your database is by building a word cloud. The following animation was created by merging 11 word clouds. The word clouds were created by using the words from the Title, Tags and Description. The words were used in increasing order of their frequency i.e. the first word cloud was created using the words which have the bottom 10% frequency, second using the bottom 20% and so on…<br>The final word cloud where the frame rests after 2 loops is the one that uses all the words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*YrFXPvUnx6kEwmUblTJVBg.gif" /></figure><h4>5. <strong>How can you make your own database?</strong></h4><ol><li>Learn how to connect with the YouTube API. <a href="https://www.youtube.com/watch?v=th5_9woFJmk">This</a> is a fantastic video on the topic. Set up the API key.</li><li>Clone <a href="https://github.com/rvs-23/SongsDatabase">this</a> repository.</li><li>Download your YouTube history data as mentioned above.</li><li>Create a folder named “<strong>_private_data</strong>” within the repository and add your history file (watch-history.json) to this.</li><li>Add the API key into a text file named api_key.txt. Store it in the folder _private_data.</li><li>In the folder named “<strong>2. song_database”, </strong>create a folder called songs_heard.</li><li>Run the <a href="https://github.com/rvs-23/SongsDatabase/blob/main/2.%20song_database/create_song_db_1.py">create_song_db_1 script</a> from the repository. This should detect the history file, and create a csv file of the filtered videos into the folder <strong>songs_heard</strong>. The filtered videos are the ones that have passed at least one column check and are at least 61s long.<br>Note: The script by default expects a .json file. You can change the parameter is_json to False in the script if you want to use an HTML file.</li><li>Next, run the <a href="https://github.com/rvs-23/SongsDatabase/blob/main/2.%20song_database/create_song_db_2.py">script create_song_db_2</a> from the repository. This will create two files. One will contain all the definitely music videos.</li><li>The other will be an excel sheet named: “ManuallyCheckMusic.xlsx”</li><li>Make a copy of this sheet in the same directory. Rename it to ManuallyCHECKEDMusic.xlsx. Toggle the N to Y for the Is_Music_Manual column, by identifying music videos yourself. It is not as challenging as it sounds. I had to identify around 1200 videos (6 months data) and it hardly took 15 minutes.<br>Optionally, if you’re okay with not maximizing accuracy, you can just save the definitely music file that the script creates.</li><li>If you have checked manually and created the required excel file, run create_song_db_2.py once again. This should merge the definitely music and manually checked files to create a FinalMusicDatabase.csv file in the same directory as the script.</li><li>Completed :D</li></ol><p><a href="https://github.com/rvs-23/SongsDatabase">Code repository.</a></p><p><strong><em>Note</em></strong><em>:</em></p><ul><li><em>There is no right or wrong way to do this fun little thing, neither was this an exhaustive or a fool proof approach. This is the best I could figure out. You could have better ideas or a more efficient filtering system. If so, please share it.</em></li><li><em>YouTube by default stores only 3 years worth of data in the history. You can change it to lifetime in your Google activity page.</em></li><li><em>A playlist is a tiny substrata of everything that you may have every heard. If you already have playlists of ALL the music you have ever heard, things can be even simpler because there is a direct way of storing the results of videos from a playlist using the YouTube API. I didn’t have, so took this long route.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b34dfd4f5f3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do Accuracy and Precision scores impact your entrance exam rank?]]></title>
            <link>https://rvs.medium.com/how-do-accuracy-and-precision-scores-impact-your-entrance-exam-rank-2410f653b0fe?source=rss-9743e6420231------2</link>
            <guid isPermaLink="false">https://medium.com/p/2410f653b0fe</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rishav Sharma]]></dc:creator>
            <pubDate>Tue, 22 Jun 2021 09:46:02 GMT</pubDate>
            <atom:updated>2022-01-16T17:12:17.906Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article attempts to explain the three infamous albeit important words in Statistics and Machine Learning — Accuracy, Precision, and Recall… from an entrance exam perspective.</h4><p>At some point in our lives, we have certainly experienced the horror of taking an entrance examination. The exam usually consists of multiple-choice-type questions. The standard is — you score positive marks if you are correct, negative if incorrect, 0 if you skip the question. The cumulative sum of the three gives you your total score.</p><p>Is that all there is to it? Does the total breakdown of scores contain something more? Let’s understand.</p><p><strong>Episodes:</strong></p><ol><li><strong>The intuition - Removing the hood of {Accuracy, Precision}.</strong></li><li><strong>Optimization strategy.</strong></li><li><strong>Formalizing intuition and introducing Recall.</strong></li><li><strong>Visualizing Accuracy and Precision.</strong></li></ol><h3>1. Intuition</h3><p>Consider the scorecard of a student called <strong>A</strong>, from his latest entrance examination consisting of <strong>50 questions</strong>:</p><p><em>a) Each correct answer awards +4 marks.</em></p><p><em>b) Each incorrect answer awards -1 marks.</em></p><p><em>c) Not attempting a question awards 0 marks.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*__qV4K_-6fboMXQsC3iTfg.png" /><figcaption>Attempts of Student A (Chart by author)</figcaption></figure><p>As shown in the figure, Student A could attempt only <strong>30 questions </strong>(we have all been here :P) and out of the 30 attempted, 26 were correct and the rest incorrect. Therefore, the <strong>total score of student A</strong>= (26 correct*4) + (4 incorrect*-1) = <strong>100</strong></p><p>Let’s ask some questions about the score: <strong><em>what is the percentage of questions Student A correctly attempted?</em></strong></p><p>Total questions = 50, Correct = 26</p><p>Therefore, percentage of correct answers = 26/50 = <strong>0.52 = 52%</strong></p><p>That’s it. This is <strong>accuracy</strong> which is <strong>52%</strong> for Student A for this example.</p><p>In a very vanilla way, we can say that accuracy is:</p><p>“<strong>what percentage of questions could the student correctly answer?</strong>”</p><p>Okay. That wasn’t tough? So what’s causing all the fuss?</p><p>To understand this, let’s now introduce another student, call him B, with the score breakdown as shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*hXI43-FWewUGHYAxbIOZgQ.png" /><figcaption>Attempts of Student B.</figcaption></figure><p>The <strong>total score of Student B</strong> = (28 correct * 4) + (12 incorrect * -1) = <strong>100</strong></p><p>Wait! Now what? <strong>Both the students have scored the same marks.</strong></p><p>The question now becomes: <strong><em>Who do we award a higher rank?</em></strong></p><p>Sigh! We need a solid strategy to make an intelligent choice. Because such exams are usually very competitive and a minor difference of 1 rank could easily be a deciding factor to get into a student’s dream college. One way to do it could be to <em>utilize the fact that the exam had a negative scoring system for incorrect answers.</em></p><p><strong>How?</strong></p><p>Whoever scored fewer negative marks i.e. whoever made fewer errors in the exam, could be awarded a better rank. Using this strategy for Students A and B, we observe that:</p><ol><li>Student B made 12 errors</li><li>Student A made 4 errors</li></ol><p>Therefore, according to this strategy, <strong>student A should be awarded a better rank.</strong> Voila! This is <strong>Precision.</strong> Student A was more precise than Student B.</p><p>If we compare the data of both the students, we see that the precision of students A and B can be calculated intuitively as follows:</p><p>Precision-A = 26 correct / (26 correct + 4 incorrect) = <strong>0.867</strong></p><p>Precision-B = 28 correct / (28 correct + 12 incorrect) = <strong>0.7</strong></p><blockquote><em>Congratulating Student A!</em></blockquote><h3>2. Optimization</h3><p>The first logical strategy is to score as much as possible but for a specific score, if you want to ensure the maximum likelihood of getting the BEST rank, the strategy should be: to <strong>maximize precision</strong>.</p><p>This means that one should avoid guessing answers randomly for the simple reason that there are two layers of punishment involved just for doing that:</p><p><em>Punishment 1</em>: The score goes down by 1 mark for every incorrect answer.</p><p><em>Punishment 2</em>: Precision reduces.</p><p>The significance of punishment 2 is very high especially if the same score is shared by multiple people. Is that all we can optimize? Check the last part :P</p><h3>3. A little math now…? To formalize!</h3><p>Now that we have got a clear intuition — let’s say hello to some words which most of us must have heard before, probably in a different context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*D-wH6PqYPxi2OKUYQG0lzg.png" /><figcaption>Image by author</figcaption></figure><p>From a student’s perspective, there are two possibilities with the question he/she attempts- Either the answer is correct, or the answer is incorrect. We can represent the possibilities in a matrix form shown alongside.</p><p>But this shows only half of the possibilities. The figure only shows OUR PREDICTION of the answer. A complete picture would also include the ACTUAL ANSWERS shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9x6mNpVyyVCN5QxclSgrQw.png" /><figcaption>Confusion matrix of attempts. Image by author</figcaption></figure><p>Let’s formally define the crazy terms written inside the squares.</p><ol><li><strong>True positives:</strong> When we correctly identify the positive class.</li><li><strong>True Negatives:</strong> When we correctly identify the negative class.</li><li><strong>False positives:</strong> When we incorrectly identify the positive class.</li><li><strong>False negatives:</strong> When we incorrectly identify the negative class.</li></ol><p>Technical nonsense! Let’s try to stick to the example that we have been following:</p><ol><li><em>A </em><strong><em>True positive</em></strong><em> in this context would simply be choosing the correct answer from the given options.</em></li><li><em>A </em><strong><em>True negative</em></strong><em> in the same context would be eliminating a question with all incorrect options.</em></li><li><em>A </em><strong><em>False positive </em></strong><em>would be choosing an incorrect answer.</em></li><li><em>Finally, the trickiest case: a </em><strong><em>False Negative </em></strong><em>would be skipping a question. (assuming a correct answer always exists)</em></li></ol><p>We now formalize the intuition behind accuracy and precision using the above points. If we remember from the previous episode, accuracy is: <em>“</em><strong><em>what is the percentage of questions Student A correctly attempted?</em></strong><em>”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*n-c8EN12I4F0Me1YAsDuZA.png" /><figcaption>Image by author</figcaption></figure><p>Therefore, accuracy of Student A = (True Positives + True Negatives) / Total questions = 26+0 / 26+20+4 = 0.52</p><p>Similarly,<strong> precision of Student A = True Positives / (TP + FP) = 26 / 26 + 4 = <em>0.867</em></strong></p><p>We can compute the same results for student B as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*byj3RJs5sHBMWkNz2HDVIw.png" /><figcaption>Confusion matrix of attempts of student B. Image by author</figcaption></figure><p>Accuracy of Student-B = (TP + TN) / Total questions = (28+0)/28+10+12 = 0.56</p><p>Similarly,<strong> precision of Student B = True Positives / (TP + FP) = 28 / 28 + 12= <em>0.7</em></strong></p><p>The Precision of Student B(0.7) is, therefore, worse than Student A(0.867). Hence, we have numerically established that Student-A should be awarded a better rank.</p><p>There is one last metric which we are yet to understand — Recall. Recall<strong> measures how well you can find the actual correct answers (ignoring the incorrect ones).</strong> Careful, on the surface, Recall looks very close to Precision, but they are entirely different metrics.</p><p>Mathematically,</p><p><strong>Recall of Student A = True Positives / (TP + FN) = 26 / 26 + 20 = 0.565</strong></p><p>This means that Student A could identify <strong>56.5%</strong> correct answers from all the answers whereas Precision identified that out of all the answers Student A attempted, <strong>86.7%</strong> were correct.</p><p>Wait! Argh! I feel you. It needs a lot of focus and mental energy to keep track of all the metrics. So, let’s combine all the metrics to have a look at a glance:</p><ol><li><strong><em>Out of all the answers, how many correct and incorrect answers could you identify? — Accuracy.</em></strong></li><li><strong><em>Out of all the correct answers which you could identify, how many were actually correct? — Precision.</em></strong></li><li><strong><em>Out of all the answers, how many correct (disregarding incorrect ones) answers could you identify? — Recall.</em></strong></li></ol><p><em>Note: One might now think that the </em><strong><em>Optimization strategy</em></strong><em> should include maximizing Recall and not Precision. But remember, recall is affected by you </em><strong><em>not attempting an answer</em></strong><em> which has 0 contribution to your score whereas precision is </em><strong><em>affected by an incorrect answer</em></strong><em> which has a -1 contribution to your score.</em></p><h3>4. Visualizing Accuracy and Precision.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*FWupw5Z4f6NFt_lO7g4TUQ.png" /></figure><p>The figure alongside shows that for a certain score, as the number of True Positives increase, the Precision goes down.</p><p>Strange?</p><p>Think for a second…</p><p>Remember, precision is affected more when the number of incorrect answers increase. Therefore, for the same score of 100, when the number of correct answers increase from 25 to 30, naturally the number of incorrect answers must increase as well. This is what reduces precision.</p><blockquote>A picture is worth a thousand words.</blockquote><blockquote>-Henrik Ibsen</blockquote><p>Here is my rendition of this famous quote:</p><blockquote>An animation is worth a thousand pictures.</blockquote><p>To be technically <strong>precise</strong>, an animation would be worth however many frames one has used :P</p><p>The point being, <em>It’s much easier to digest a picture than hardcore formulas and it’s much easier to digest an animation than an informationally dense image.</em></p><p>Here is a small <strong>animation</strong> depicting Accuracy and Precision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*mB-jtn3F-SlkFCSDr7dgOA.gif" /><figcaption>The well-known dart visualization of Accuracy and Precision, animated!</figcaption></figure><p>The code to figure out the combinations of the number of questions attempted equating to a specific score and the code for the animation can be found on my GitHub <a href="https://github.com/rvs-23/Accuracy_Precision_EExam">here</a>.</p><p><strong><em>Reference to the Optimization episode:</em></strong><em> There is one more level of optimization we can perform. That can be achieved by creating a single metric using both Precision and Accuracy. This idea will be covered in the next part. So, stay tuned.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2410f653b0fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can I make Python replicate my signature?]]></title>
            <link>https://faun.pub/can-i-make-python-replicate-my-signature-65241e719eb1?source=rss-9743e6420231------2</link>
            <guid isPermaLink="false">https://medium.com/p/65241e719eb1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[handwriting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Rishav Sharma]]></dc:creator>
            <pubDate>Mon, 24 May 2021 05:56:44 GMT</pubDate>
            <atom:updated>2021-06-22T07:11:25.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>Credit to <a href="https://medium.com/u/a4bc34279e8">Srijit Mukherjee</a> for inspiring me to do this. I read his <a href="https://medium.com/srijit-mukherjee/how-to-make-r-learn-your-handwriting-8917ff6d02f1">article</a> and was fascinated by the creative idea. The following is my attempt to reproduce the same.</h4><h4>The idea: Using Math and Python to mimic my handwriting as close as possible.</h4><p><strong>I have divided the approach into the following Episodes:</strong></p><ol><li><strong>{Ideas, Challenges, Failures}</strong></li><li><strong>The approach towards a satisfactory solution.</strong></li><li><strong>The code and the animation.</strong></li></ol><h4>1. {Ideas, Challenges, Failures}</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnbuhM_P43x2FSMceMbfOw.jpeg" /><figcaption>Relax! This is with a pen and paper. Actual animation isn’t this good :P</figcaption></figure><p><strong><em>a) The coordinates challenge</em></strong></p><p>Think about this. I give you <em>n</em> points in 2-D space and ask you how many curves best fit the points? This is the very question whose answer I failed to appreciate when I began working on this.</p><p><strong>The answer is n!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LS8BydtNSZOTMPIXnRLRyQ.png" /><figcaption>When n=3, few of the possible curves.</figcaption></figure><blockquote>All models are wrong some are useful.<br> — George Box</blockquote><p>Here is my rendition of the quote:</p><blockquote>All laziness is bad, some may be fruitful.</blockquote><p>I was too lazy to collect the data points for my signature and started to think of ways to automate the task. Maybe the computer’s vision can help?</p><p>The first approach I tried was to get the coordinates through pixels of the image of my signature. The idea was the signature would be written on a white piece of paper. The picture would then be dilated (using open cv) and the coordinates of the pixels that lie below a certain threshold of color could now be extracted.</p><p>I used the following piece of code to extract the coordinates:</p><pre>image = cv2.imread(&#39;dilated_sign_.jpg&#39;)<br>gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br>threshold = 45<br># Find coordinates of all pixels below threshold<br>coords = np.column_stack(np.where(gray &lt; threshold))<br>print(coords.shape)</pre><p>I got around 30000 coordinates. On plotting them, I got this:</p><pre>fig, ax = plt.subplots()<br>ax.grid(False)<br>fig.set_size_inches(6,9)<br>ax.plot(coords[:,0], coords[:,1], &#39;.&#39;, color=&#39;royalblue&#39;)<br>ax.yaxis.set_visible(False)<br>fig.savefig(&#39;pixel_sign.jpg&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*6IXUc0ozijOPAWAIzLimnA.jpeg" /><figcaption>30000 pixel coordinates</figcaption></figure><p>It looks close. Now all I had to do is find a way to fit a smooth curve through these coordinates. Right?</p><p>If only it were that easy :P. Real Analysis came along and shit all over my excitement. See, if we were to plot the coordinates, there is only one way to do it but <strong>to draw a curve passing through those points, we also need the order(timestamps) in which those points appeared</strong>. That’s where <a href="https://en.wikipedia.org/wiki/Sequence">sequences</a> come. The understanding is that order matters. This is the very point that I mentioned at the very start of this part. On connecting the coordinates which were not sequenced, this is what I got.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*dfRLD6Ov7nXxn9JR5Kl9dQ.jpeg" /><figcaption>A plot of failure.</figcaption></figure><p><strong>If only my bank accepted this divine looking signature :P</strong></p><p>Failing to see what I wanted to, I kept aside the idea of automatically getting the sequence of coordinates and instead submitted to the joy of manual labor by collecting the ordered coordinates of the signature from <a href="https://www.mobilefish.com/services/record_mouse_coordinates/record_mouse_coordinates.php">here</a>.</p><p><strong><em>b) The curve challenge:</em></strong></p><p>Once you have obtained the coordinates(manually), getting a smooth curve would be easy, I thought. In the article mentioned above, <a href="https://en.wikipedia.org/wiki/Generalized_additive_model#:~:text=In%20statistics%2C%20a%20generalized%20additive,inference%20about%20these%20smooth%20functions.">Generalized additive models</a> were used to fit a smooth curve through the points. I tried to use the model in Python from <a href="https://pygam.readthedocs.io/en/latest/">here</a>; it did not work as expected.</p><p>Now, it was time to think of other ways to fit a smooth curve.</p><p><strong>We are all obsessed with curves after all :P</strong></p><p><em>Attempt: Computer graphics</em></p><p>I started wondering how curves are drawn so smoothly in computer software. After researching, I came across the theory of Spline curves which use some kind-of an Interpolation technique to get coordinates in the vicinity of the input data. When joined, the coordinates yield a smooth curve. Ah! Interpolation, the final semester subject came to the rescue.</p><p>There are many types of Spline curves one can choose to use. The two types I decided to play around with are: <a href="https://pomax.github.io/bezierinfo/">Bézier </a>curves and <a href="http://web.mit.edu/hyperbook/Patrikalakis-Maekawa-Cho/node17.html">B-Splines</a>. B-splines are <a href="https://en.wikipedia.org/wiki/Piecewise">piecewise</a>, <a href="https://en.wikipedia.org/wiki/Spline_(mathematics)">polynomial interpolation curves</a>, where the “signature curve” could be built by performing polynomial interpolation over a set of points, using a sliding window of a certain number of points.</p><p>Technically, one can use any of them. I found this excellent repository which contains <a href="https://github.com/kawache/Python-B-spline-examples">B-Spline Interpolation examples</a>. Now, it was time to get the hands dirty and code the result.</p><p>Here is the how the final animation looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*Dd6bo7iA2K4sKINnxNE3Pg.gif" /><figcaption>Signing off! (30 fps)</figcaption></figure><p>The better you can capture the coordinates, the closer this animation gets to your actual handwriting.</p><p><a href="https://commons.wikimedia.org/wiki/File:Elon_Musk_Signature.svg">Signature of Elon Musk</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*WaBzIZSIEjO7rPrK61_tkQ.gif" /><figcaption>Is it too dark?</figcaption></figure><p>The code can be found on my GitHub <a href="https://github.com/rvs-23/HandwritingMimic/blob/master/Code/Signature_code%20(Scipy).py">here</a>!</p><figure><a href="https://faun.to/i9Pt9"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_MOgMTr_f1N4qHN_R7KVA.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65241e719eb1" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/can-i-make-python-replicate-my-signature-65241e719eb1">Can I make Python replicate my signature?</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>