<?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 Jacob Crabb on Medium]]></title>
        <description><![CDATA[Stories by Jacob Crabb on Medium]]></description>
        <link>https://medium.com/@alludedwinter?source=rss-58811da7f0c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AA3VgzS4qCf7SNcB2wtDgw.png</url>
            <title>Stories by Jacob Crabb on Medium</title>
            <link>https://medium.com/@alludedwinter?source=rss-58811da7f0c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:43:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alludedwinter/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[Come on, Lint a little: cleaning up your code with Linters]]></title>
            <link>https://medium.com/data-science/come-on-lint-a-little-cleaning-up-your-code-with-linters-5d16b1bf19bd?source=rss-58811da7f0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d16b1bf19bd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jacob Crabb]]></dc:creator>
            <pubDate>Wed, 30 Oct 2019 22:36:23 GMT</pubDate>
            <atom:updated>2023-02-06T20:28:03.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>Come On, Lint A Little: Cleaning Up Your Code With Linters</h3><p>You know what they say, “It’s what’s on the inside that counts.” While this may be true, you still have to find a way to express what’s inside so that people can understand it. You might have the most functional piece of code you’ve ever written. It might be elegant, thorough, and foolproof. But it still looks like this:</p><pre>def buy_me_dinner():<br>    &quot;lala&quot;<br>    print(&quot;yummy dinner&quot;)<br>def attack(): <br>    &quot;oh&quot;<br>    print(&quot;I love you&quot; to)</pre><pre>from fileinput import input<br>  <br>     suspects = input()[9:].split(&#39;,&#39;)<br> weapons = input()[8:].split(&#39;,&#39;)<br>        rooms = input()[6:].split(&#39;,&#39;)</pre><pre>clues = input()   <br> for line in input():  <br>     clue = line.split(&#39; &#39;)<br>      if clue[1] != &#39;the&#39;:  <br>          suspects.remove(&quot; &quot;.join(clue[1:]))  <br>        <br>        <br>    else:  <br>        thing = &quot; &quot;.join(clue[2:])   <br>           if thing in weapons:<br>               weapons.remove(thing)  <br>            <br>            <br>        else:  <br>            rooms.remove(thing)  <br>     print(suspects[0])  <br>       print(&quot;in the &quot; + rooms[0])  <br>     print(&quot;with the &quot; + weapons[0])</pre><p>This is where a linter will come in handy. A linter is a tool that analyzes code to flag style or programming errors. The linter I’m using today is <a href="https://pypi.org/project/pycodestyle/">pycodestyle</a>, and it’s based on Python’s Pep-8 style guide. Linter’s will give you a list of the errors found so that you can fix them one by one, and hopefully learn how to write code that betters adheres to your chosen style guide in the future. There are other linters like <a href="https://github.com/psf/black">Black</a>, which reformat your code automatically, but you don’t learn anything that way, so when starting out with linters it’s better to use something verbose.</p><p>Let’s see what happens when we lint the above code with pycodestyle. Once you have it installed, simply go to your terminal and type</p><pre>pycodestyle &lt;name of file to lint&gt;</pre><p>And you’ll get back something like this:</p><pre>messy.py:4:1: E302 expected 2 blank lines, found 0<br>messy.py:4:14: W291 trailing whitespace<br>messy.py:13:1: E303 too many blank lines (6)<br>messy.py:13:1: E402 module level import not at top of file<br>messy.py:14:1: W293 blank line contains whitespace<br>messy.py:15:6: E111 indentation is not a multiple of four<br>messy.py:15:6: E113 unexpected indentation<br>messy.py:16:2: E901 IndentationError: unindent does not match any outer indentation level</pre><p>So the 1st character in line 4 is having an issue with the number of blank lines, then the 14th character has trailing whitespace after, and so on. What does the code look like after we’ve taken its recommendations? Funnily enough, sometimes fixing one error can reveal another error. But eventually we end up with something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*s8cLkflIYXW6iCWjWkkpEg.png" /></figure><p>Just by looking at it you can tell something about the way Pep-8 says to format code. There should be 2 blank spaces after importing libraries, 2 blank spaces after declaring a function, and a new line at the end of a file. These linters aren’t perfect though, and sometimes you will find style errors that they just don’t pick up on. Also, pycodestyle doesn’t pick up on functionality errors. But I can check this code with <a href="https://mypy.readthedocs.io/en/latest/">mypy</a> for certain types of errors. mypy is used in the same way.</p><pre>mypy &lt;name of file to check&gt;</pre><p>And it will check for errors. For the above code, it returned</p><pre>messy.py:12: error: invalid syntax</pre><p>Which is telling me about the syntax error in line 11 inside of the print statement. Using simple tools like these can make a huge difference in the way your code looks, and reduce frustration when debugging. I’ve heard of managers who won’t even look at code that hasn’t been linted, so it’s a good habit to get into, and aside from that it’s a great way to learn how your code should look, and what areas you make mistakes in most often.</p><p>Happy coding adventures!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d16b1bf19bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/come-on-lint-a-little-cleaning-up-your-code-with-linters-5d16b1bf19bd">Come on, Lint a little: cleaning up your code with Linters</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[Save before entering the dungeon! An introduction to Git]]></title>
            <link>https://medium.com/data-science/save-before-entering-the-dungeon-an-introduction-to-git-8ec5f9fdda7?source=rss-58811da7f0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ec5f9fdda7</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Jacob Crabb]]></dc:creator>
            <pubDate>Wed, 23 Oct 2019 22:01:07 GMT</pubDate>
            <atom:updated>2023-02-06T20:28:33.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>Save Before Entering The Dungeon! An Introduction To Git</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*phyURx2pCUQs7PpsJ4WKFw.jpeg" /></figure><p>So there you are bold adventurer, standing at the entrance to the deep, the dark, the unknown reaches beneath the surface. You have made all the preparations. You’ve filled your bag with useful potions and tools and tonics. You’ve sharpened your blades and bolstered your armor. You’ve steeled your nerves and stepped through the entrance to the most infamous dungeon in the land. You are ready.</p><p>… But what if you’re not? Even the boldest of heroes need a backup plan. You should save your game just in case things turn out poorly, or deadly.</p><p>And also for you, humble programmer, standing at the beginning of a project, the beginning of a great, unknown continuum of potential futures. You should save your game too, with Git!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*Yf48dlC5RhXYPV3gLeaLdg.png" /></figure><p>Git is a distributed version-control system for tracking changes in source code during software development. It is designed for coordinating work among programmers, but it can be used to track changes in any set of files.</p><p>So how does it work? Once you have it installed on your machine (go <a href="https://git-scm.com/">here</a> to acquire if you don’t have it already) the first step is to create a Git repository. When you build a project on your local machine, you will probably be putting it in some local working directory. a Git repository is just a directory that has been Git enabled.</p><p>There are two ways to start a Git repository. the first is to convert an existing directory into a Git repository, this is done with:</p><pre>$ git init</pre><p>Which will add a .git file to the directory and allow you to start tracking changes made to your files. The second method is used to clone existing Git repositories:</p><pre>$ git clone</pre><p>Cloning repositories from <a href="https://github.com/">GitHub</a> (a site used to share projects and code) is incredibly common and highly encouraged! Creating an empty project repository on GitHub, then cloning it to your local machine is very normal.</p><p>So now lets actually start tracking some changes! In fact, making the repository is a tracked change in itself. Right now your repository looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2oLYkx225zUtSuf___DrGg.png" /></figure><p>Not so impressive right? But let&#39;s do a little work on your project. Say you put a few hours into your project, but you’re not sure how to proceed farther. Now is a perfect time to save your work with a git commit. Committing your work is as simple as telling git which files you want to add to the commit:</p><pre>$ git add &lt;files you want to include in the commit&gt;</pre><p>Add any files that you’ve made changes too, or if you’re not sure which files have been changed, use:</p><pre>$ git status</pre><p>Files that have been modified will come up in red. Once you’ve decided which files to add to the commit, use:</p><pre>$ git commit -m &quot;Left a commit message because it&#39;s best practice&quot;</pre><p>It’s important to leave messages describing the changes you’ve made so your future self can find them, in case something goes wrong. Now should you ever have to come back to this “Save” it will be easier to find. We can now imagine your repository looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3hOvvvW5iB9FMtTpWwciw.png" /></figure><p>At any point when you’ve committed changes to your repository, if you cloned your repository from GitHub, you can push your changes back up to the remote GitHub repository with:</p><pre>$ git push</pre><p>Ok, nice! But let&#39;s say you’ve been working on your project for a while, and you realize that somebody else, definitely not you, made a terrible mistake that compromised the project. You know this mistake was made while they were updating “Rom Drive Data”, so you want to go back to that commit and fix it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MU3cMtUImTubvDeDd1EUhg.png" /></figure><p>This can be done by using:</p><pre>$ git log</pre><p>To examine your previous commits. This will bring up something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzXFAecTvnigq5_tFyzDnA.png" /><figcaption>Feel free to email me. I don’t bite often :)</figcaption></figure><p>There’s a lot of information here. These are previous commits starting with the most recent at the top. You can see each commit’s unique id, who made the commit, when it was made, and it’s commit message. In order to go back to a previous commit, copy the commit’s unique id, hit “q” to escape the Git log, then use:</p><pre>$ git checkout &lt;unique id&gt;</pre><p>You’ll get a message like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6HoIdB5IbC6mnOWz_eirA.png" /></figure><p>Ah! You’re a headless zombie! Not really. What it’s saying is that you aren’t on a branch anymore. Flow in Git is set up in branches, and in a new repository there’s only one branch, called “master.” It looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sn8Ib0dZ7-Bc7GMmnG7hhQ.png" /></figure><p>In the detached head state, you can try other things, add other commits, and freely experiment to your heart&#39;s content. But if you want any of these changes to be saved, you will have to make a new branch. This can be done quite easily with:</p><pre>$ git checkout -b &lt;new-branch-name&gt;</pre><p>which makes a new branch (the “-b” part), then moves over to it (the “checkout” part). If you issue this command while in a detached head state, it will automatically make the branch out of your current state.</p><p>It’s like our bold adventurer going through the dungeon and coming to a crossroads. He saves his game before going down the left path, where he finds gold and loot, but maybe he also wants to know what happens if he goes down the right path instead. So we make a branch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydhFvhpYa3__tHOCU6hu0g.png" /></figure><p>As mentioned before, navigate between the branches with:</p><pre>$ git checkout &lt;branch you want to go to&gt;</pre><p>There’s so much more that can be done with Git! A great place to start learning is the <a href="https://git-scm.com/doc">Git documentation</a>. May all of your version-controls be merry and bright! Happy Wednesday :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec5f9fdda7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/save-before-entering-the-dungeon-an-introduction-to-git-8ec5f9fdda7">Save before entering the dungeon! An introduction to Git</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[Sound Tasty? A Data Science Project Walkthrough]]></title>
            <link>https://medium.com/analytics-vidhya/sound-tasty-a-project-walkthrough-5be396b15bdb?source=rss-58811da7f0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be396b15bdb</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[words]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[word-vectors]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jacob Crabb]]></dc:creator>
            <pubDate>Wed, 16 Oct 2019 23:09:23 GMT</pubDate>
            <atom:updated>2023-02-06T19:46:55.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VphIS_3oeeXZQHxJL3EuEg.png" /></figure><p>Today I’m going to write about a fun project I made. Unfortunately, my taste in foods is somewhat limited. I tend to eat only what I know, which is a problem because there’s so much incredible food out there if you’re willing to try it! Let’s hop in.</p><p>I started off by identifying recipe data I wanted from Allrecipes.com</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kOSyqFZl_bVnMgascf2dg.png" /></figure><p>After searching for a bit I could find no API to work with, so instead, I studied the site layout and put together a Selenium web driver to use as a web-scraper. I set up my code to go through the site&#39;s main category url’s and copy the title and ingredients from around the first 100 recipes. Here is the web scraping code:</p><pre># # browser = Chrome()</pre><pre>for url in urls:<br>#     print(url)<br>#     browser.get(url)</pre><pre>#     for _ in range(6):<br>#         browser.execute_script(&quot;window.scrollTo(0,             document.body.scrollHeight);&quot;)<br>#         time.sleep(3 + random.random()*10)</pre><pre>#     link_list = browser.find_elements_by_xpath(&#39;//*[contains(<a href="http://twitter.com/class">@class</a>,&quot;fixed-recipe-card__info&quot;)]/a&#39;)</pre><pre>#     recipe_page_list = [link.get_attribute(&#39;href&#39;) for link in link_list]</pre><pre>#     len(recipe_page_list)</pre><pre>#     with open(&#39;recipes_list.json&#39;, &#39;a&#39;) as f:</pre><pre>#         for recipe in recipe_page_list:</pre><pre>#             browser.get(recipe)</pre><pre>#             recipe_dict = {}<br>            <br>#             try:<br>#                 recipe_dict[&#39;title&#39;] = browser.find_element_by_xpath(&#39;//*[<a href="http://twitter.com/id">@id</a>=&quot;recipe-main-content&quot;]&#39;).text<br>#             except:<br>#                 recipe_dict[&#39;title&#39;] = browser.find_element_by_xpath(&#39;//*[contains(<a href="http://twitter.com/class">@class</a>, &quot;intro article-info&quot;)]/h1&#39;).text<br>            <br>#             try:<br>#                 lala_list = browser.find_elements_by_xpath(&#39;//*[contains(<a href="http://twitter.com/id">@id</a>,&quot;lst_ingred&quot;)]&#39;)<br>#                 item_list = []<br>#                 for element in lala_list:</pre><pre>#                     item_list += element.find_elements_by_css_selector(&#39;span&#39;)</pre><pre>#                 ingredients = [item.text for item in item_list[:-1]]<br>#                 recipe_dict[&#39;ingredients&#39;] = ingredients<br>            <br>#             except:<br>#                 lala_list = browser.find_elements_by_xpath(&#39;//*[contains(<a href="http://twitter.com/class">@class</a>, &quot;ingredients-item-name&quot;)]&#39;)</pre><pre>#                 ingredients = [item.text for item in lala_list]<br>#                 recipe_dict[&#39;ingredients&#39;] = ingredients</pre><pre>#             json.dump(recipe_dict, f)<br>#             f.write(&#39;\n&#39;)<br>#             time.sleep(3 + random.random()*10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*PINnqQLDVuz4sDcZw-inOA.png" /></figure><p>I had to attempt to get my data 6 times, updating for older recipes in different formats, as well as timeouts and data storage issues. The web-scraper also got bogged down by activity trackers attached to Allrecipes.com. My solution to this was to install an adblocker on the instance of Selenium.</p><p>Great! Now that I had my data, I planned to breakdown the ingredient words so I could use Gensim’s word2vec to compare ingredient word embeddings. So comes cleaning!</p><p>I loaded the data from the JSON file where it was stored and put it in a Pandas data frame for EDA. The first task was to deal with missing values, fortunately, there weren’t that many. Then I removed punctuation. Next, I had to deal with how to find meaningful words in the ingredients and how to deal with stop words and measurements. This is what my data looked like.</p><pre>[&#39;2 pounds unpeeled large shrimp&#39;,<br> &#39;2 tablespoons olive oil&#39;,<br> &#39;1 teaspoon minced garlic&#39;,<br> &#39;1/4 teaspoon salt&#39;,<br> &#39;1/8 teaspoon freshly ground black pepper&#39;,<br> &#39;1 cup cocktail sauce&#39;,<br> &#39;1 lemon, cut into wedges&#39;]</pre><p>My goal for this project was just to map out flavors and recommend new foods that have similar flavors to what you like, so measurements were dropped. As for descriptions like “unpeeled large” or instructions like “cut into wedges”, I made judgment calls on what I thought was valuable information and removed the rest. In order to prepare for word2vec, I split all of the ingredients into lists of the remaining ingredient words. This left me with ingredient lists like this:</p><pre>[&#39;shrimp&#39;,<br> &#39;olive&#39;,<br> &#39;oil&#39;,<br> &#39;garlic&#39;,<br> &#39;salt&#39;,<br> &#39;black&#39;,<br> &#39;pepper&#39;,<br> &#39;cocktail&#39;,<br> &#39;sauce&#39;,<br> &#39;lemon&#39;]</pre><p>The problem now is that ‘olive’ and ‘oil’ are considered as two different ingredients when clearly they should be only one. So I used Gensim’s phrase detection to look for words that are frequently together and rejoin them as ingredients. While not 100% accurate, it did bring us to a better place and having a “lemon shrimp” vector doesn’t change the “lemon” vector or the “shrimp” vector, so I considered it acceptable.</p><pre>[&#39;sauce&#39;,<br> &#39;cocktail&#39;,<br> &#39;salt black garlic&#39;,<br> &#39;olive oil&#39;,<br> &#39;pepper&#39;,<br> &#39;lemon shrimp&#39;]</pre><p>After all of the cleaning, I finally had a data frame that was ready for Gensim’s word2vec</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*GAud1eTa8jOKrgneFD3fLQ.png" /></figure><p>Next was to use word2vec’s similarity comparison to find words that are similar to the user’s ingredients inputs, then built a function to return recipes that have those similar ingredients. I added an adjustable button to find recipes with either very similar, not so similar, or very different ingredients from the user input called “how adventurous.”</p><pre>model.wv.most_similar(positive=[&quot;cheddar cheese&quot;])</pre><pre>[(&#39;mushrooms&#39;, 0.9990376234054565),<br> (&#39;beef&#39;, 0.9988831281661987),<br> (&#39;monterey jack&#39;, 0.9986639022827148),<br> (&#39;green chile&#39;, 0.9985662698745728),<br> (&#39;sauce&#39;, 0.9985474348068237),<br> (&#39;green onions&#39;, 0.9985294342041016),<br> (&#39;cheese&#39;, 0.9985264539718628),<br> (&#39;seasoning&#39;, 0.9983548521995544),<br> (&#39;tomato sauce&#39;, 0.9983314275741577),<br> (&#39;cayenne pepper&#39;, 0.9981967210769653)]</pre><p>To finish it all off I pickled the data and the word2vec model and built a Flask app to run the project on an Amazon Ec2 instance.</p><p>I had a lot of fun making Sound Tasty and I’d love to hear feedback or ideas for improvement!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be396b15bdb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/sound-tasty-a-project-walkthrough-5be396b15bdb">Sound Tasty? A Data Science Project Walkthrough</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[Classifying Hate Speech: an overview]]></title>
            <link>https://medium.com/data-science/classifying-hate-speech-an-overview-d307356b9eba?source=rss-58811da7f0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d307356b9eba</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jacob Crabb]]></dc:creator>
            <pubDate>Tue, 28 May 2019 15:49:18 GMT</pubDate>
            <atom:updated>2019-05-28T18:00:55.504Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief look at label classification and hate speech</h4><p>By <a href="https://medium.com/u/58811da7f0c1">Jacob Crabb</a>, <a href="https://medium.com/u/e86e1bcb017">Sherry Yang</a>, and <a href="https://medium.com/u/1c39b72311e2">Anna Zubova</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*qGZPi298h3OtjdfE.jpg" /></figure><h3>What is hate speech?</h3><p>The challenge of wrangling hate speech is an ancient one, but the scale, personalization, and velocity of today’s hate speech a uniquely modern dilemma. While there is no exact definition of hate speech, in general, it is speech that is intended not just to insult or mock, but to harass and cause lasting pain by attacking something uniquely dear to the target. Hate speech has been especially prevalent in online forums, chatrooms, and social media.</p><p><a href="https://hatebase.org/">Hatebase.org</a>, a Canadian company that created a multilingual dictionary of words used in hate speech, has the following criteria for identifying hate speech (<a href="https://hatebase.org/faqs">source</a>):</p><ul><li>It is addressed to a specific group of people (ethnicity, nationality, religion, sexuality, disability or class);</li><li>There is a malicious intent;</li></ul><p>There is one main problem with hate speech that makes it hard to classify: subjectivity. With the <a href="https://en.wikipedia.org/wiki/United_States_free_speech_exceptions">exceptions from the First Amendment</a>, hate speech has no legal definition and is not punished by law. For this reason, what is and isn’t hate speech is open to interpretation. A lot depends on the domain and the context, according to Aylin Caliskan, a computer science researcher at George Washington University (<a href="https://www.wired.com/story/break-hate-speech-algorithm-try-love/">source</a>) A seemingly neutral sentence can be offensive for one person and not bother another.</p><p>But since humans can’t always agree on what can be classified as hate speech, it is especially complicated to create a universal machine learning algorithm that would identify it. Besides, the datasets used to train models tend to “reflect the majority view of the people who collected or labeled the data”, according to Tommi Gröndahl from the Aalto University, Finland (<a href="https://www.wired.com/story/break-hate-speech-algorithm-try-love/">source</a>).</p><p>One more complication is that it is hard to distinguish hate speech from just an offensive language, even for a human. This becomes a problem especially when labeling is done by random users based on their own subjective judgment, like in <a href="https://github.com/t-davidson/hate-speech-and-offensive-language/tree/master/data">this dataset</a>, where users were suggested to label tweets as “hate speech”, “offensive language” or “neither”. So when designing a model, it is important to follow criteria that will help to distinguish between hate speech and offensive language.</p><p>It is worth pointing out that Hatebase’s database can be very useful in creating hate speech detection algorithms. It is a multilingual vocabulary where the words attain labels from “mildly” to “extremely offensive” depending on the probability of it to be used in hate speech.</p><p>While there are different opinions on whether hate speech should be restricted, some companies like Facebook, Twitter, Riot Games, and others decided to control and restrict it, using machine learning for its detection.</p><h3>Model Sensitivity</h3><p>One more problem with detecting hate speech is the sensitivity of the machine learning algorithms to text anomalies.</p><p>A model is “the output of the algorithm that trained with data” (<a href="https://www.toptal.com/machine-learning/ensemble-methods-machine-learning">source</a>). Machine learning algorithms, or models, can classify text for us but are sensitive to small changes, like removing the spaces between words that are hateful. This change can drastically reduce the negative score a sentence receives (<a href="https://www.wired.com/story/break-hate-speech-algorithm-try-love/">Source</a>). Learning models can be fooled into labeling their inputs incorrectly. A crucial challenge for machine learning algorithms is understanding the context.</p><p>The insidious nature of hate speech is that it can morph into many different shapes depending on the context. Discriminatory ideas can be hidden in many benign words if the community comes to a consensus on word choice. For example names of children’s toys and hashtags can be used as monikers for hateful ideas. Static definitions that attribute meaning to one word in boolean logic don’t have the flexibility to adapt to changing nicknames for hate. “What A.I. doesn’t pick up at this point is the context, and that’s what makes language hateful,” says Brittan Heller, an affiliate with the Berkman Klein Center for Internet and Society at Harvard University (<a href="https://psmag.com/ideas/neo-nazi-hate-speech-foiling-algorithms">Source</a>).</p><p>Every company that allows users to publish on their own face the challenge that the speech becomes associated with their brand. <em>Wired</em>’s April issue describes how relentless growth at Facebook has created a major question “whether the company’s business model is even compatible with its stated mission [to bring the world closer together].” (<a href="https://www.wired.com/story/facebook-mark-zuckerberg-15-months-of-fresh-hell/">Source</a>) We may not be able to bring people together and make the world a better place by simply giving people more tools to share.</p><p>In the next section, we will look at a case study of how another company, Riot Games faced the challenge of moderating hate speech.</p><h3>A Case Study: League of Legends by Riot games</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*zaDTS6cOkXRFnFWt.png" /></figure><p>For those who don’t know, League of Legends is a competitive game where two teams of five players each attempt to destroy the opposing team’s base.</p><p>On release in 2009, Riot games were, of course, looking to create a fun environment where friendly competition could thrive. This was the original goal.</p><p>League of Legends uses built-in text, and as the game’s popularity and user base grew, the competition intensified. The players begin to use the chat to gloat about their in-game performance or tear down the enemy team’s futile attempts to stop inevitable defeat. This was still within the company’s goals. Soon, however, it devolved until it was commonplace to see things such as: “your whole life is trash”, “kill yourself IRL”, or numerous other declarations of obscene things the victors would do to the losers. This became so commonplace that the players gave it a name: Toxicity. Players became desensitized to the point were even positive, upstanding players would act toxic without thought. Riot Games saw that of their in-house player classifications (negative, neutral, and positive), 87% of the Toxicity came from neutral or positive players. The disease was spreading. (<a href="https://www.gamesindustry.biz/articles/2015-07-08-homophobia-sexism-racism-reduced-to-2-percent-of-league-of-legends-matches">Source</a>)</p><p>In 2011 Riot Games released an attempt at a solution called “The Tribunal” (<a href="https://leagueoflegends.fandom.com/wiki/The_Tribunal">Source</a>). The Tribunal was designed to work with another in-game feature called “Reporting” (<a href="https://support.riotgames.com/hc/en-us/articles/201752884-Reporting-a-Player">Source</a>). At the end of a game, if you felt another player had been toxic, reporting was a way of sending those concerns to Riot Games for review. Riot Games would then turn the report over to The Tribunal. The Tribunal was a jury based judgment system comprised of volunteers. Concerned players could sign up for The Tribunal, then view game reports and vote on a case by case basis whether someone had indeed acted toxic or not. If your vote aligned with the majority, you would be granted a small amount of in-game currency and the offending toxic player would be given a small punishment, which would increase for repeat offenders. Riot Games also enacted small bonuses to players who were non-toxic. These combined efforts saw improvements in the player base, and Riot found that just one punishment from The Tribunal was enough to curb toxic behavior in most players.</p><p>This system had two main problems:</p><ol><li>It was slow and inefficient. Manual reviews require those chat logs to be pulled out to The Tribunal website, then having to wait for responses from enough players, and then decide on a penalty from there.</li></ol><p>2. It was at times wildly inaccurate (especially before they removed the reward per “successful” penalty, which lead to a super innate bias in the system). (<a href="https://nexus.leagueoflegends.com/en-us/2018/08/ask-riot-will-tribunal-return/">Source</a>)</p><p>Riot closed down the Tribunal in 2014. It had worked for a while, but toxicity was still a problem.</p><p><strong>A Machine Learning Solution:</strong></p><p>After that though, Riot Games took their approximately 100 million Tribunal reports (<a href="https://www.gamesindustry.biz/articles/2015-07-08-homophobia-sexism-racism-reduced-to-2-percent-of-league-of-legends-matches">Source</a>) and used it as training data to create a machine-learning system that detected questionable behaviors and offered a customized response to them (based on how players voted in the training data’s Tribunal cases.)</p><p>While The Tribunal had been slow or inefficient, sometimes taking days or a week or two to dish out judgment, (long after a player had forgotten about their toxic behavior) this new system could analyze and dispense judgment in 15 minutes. Players were seeing nearly immediate consequences to their actions (<a href="https://nexus.leagueoflegends.com/en-us/2018/08/ask-riot-will-tribunal-return/">Source</a>).</p><p>“As a result of these governance systems changing online cultural norms, incidences of homophobia, sexism and racism in League of Legends have fallen to a combined 2 percent of all games,” … “Verbal abuse has dropped by more than 40 percent, and 91.6 percent of negative players change their act and never commit another offense after just one reported penalty. (<a href="https://www.gamesindustry.biz/articles/2015-07-08-homophobia-sexism-racism-reduced-to-2-percent-of-league-of-legends-matches">Source</a>)</p><h3>Machine Learning methodology</h3><p>Machine learning approaches have made a breakthrough in detecting hate speech on web platforms. In this section, we will talk about some techniques that are traditionally used for this task as well as some new approaches.</p><p><strong>Preprocessing Data</strong></p><p>Natural language processing (NLP) is the process of converting human words into numbers and vectors the machine can understand. A way of working between the world of the human and the world of the machine. Naturally, this requires quite a lot of data cleaning. Typically, cleaning means removing stop words, stemming, tokenization, and the implementation of Term Frequency-Inverse Document Frequency (TFIDF) which weights words of more importance heavier than words like “the” which get penalized for adding less meaning. (<a href="https://medium.com/@ODSC/essential-nlp-tools-code-and-tips-39b7b2b7d7ba">Source</a>) Lemmatization is a more computationally expensive method used to stem, or take the root, words. (<a href="https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html">Source</a>)</p><p><strong>Model Implementation</strong></p><p>Once the data is clean we use several methods for classification. Common methods of classifying text include<strong> </strong>”sentiment analysis, topic labeling, language detection, and intent detection.” (<a href="https://monkeylearn.com/text-classification/">Source</a>) More advanced tools include Naive Bayes, bagging, boosting, and random forests. Each method can have a recall, precision, accuracy, and F1 score attached to how well it classifies. Then we want to test these methods over and over. As awesomely accurate as our artificial intelligence can be with trained data sets, they can be equally rogue with test data. We need to make sure our model is not overfit to our training data in a way that makes it excellent at classifying test data but poor at accurately classifying future data. Below are three further ways to deal with challenges in classify text.</p><p><strong>Multilabel Classification</strong></p><p>The baseline multilabel classification approach, called the <em>binary relevance</em> method, amounts to independently training one binary classifier for each label (<a href="https://en.wikipedia.org/wiki/Multi-label_classification">Source</a>). This approach treats each label independently from the rest. For example, if you were trying to classify ‘I hate that kind of food, let’s not have it for lunch.’ For the labels: lunch talk, love talk, hate talk. Your classifier would go through the data three times, once for each label.</p><p>For the data and labels below, (after preprocessing) the binary relevance method will make individual predictions for each label. (We will be using a Naive Bayes classifier, which is explained quite well <a href="https://medium.com/syncedreview/applying-multinomial-naive-bayes-to-nlp-problems-a-practical-explanation-4f5271768ebf">here</a>)</p><pre>data = pd.read_csv(&#39;lunchHateLove.csv&#39;)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*bLGKxfXZwjlDInLB36cYmg.png" /></figure><pre># using binary relevance<br>from skmultilearn.problem_transform import BinaryRelevance<br>from sklearn.naive_bayes import GaussianNB</pre><pre># initialize binary relevance multi-label classifier<br># with a gaussian naive bayes base classifier<br>classifier = BinaryRelevance(GaussianNB())</pre><pre># train<br>classifier.fit(x_train, y_train)</pre><pre># predict<br>predictions = classifier.predict(x_test)</pre><pre>#print the keywords derived from our text<br>#along with the labels we assigned, and then the final predictions<br>print(data.comment_text[1], &#39;\n&#39;,<br>      data.comment_text[3], &#39;\n&#39;,<br>      y_test, &#39;\n&#39;,<br>      predictions, &#39;\n&#39;)</pre><pre><br>hate love kind food okay lunch <br>food hate love get lunch <br>    lunch_talk  love_talk  hate_talk<br>1        1          0          1<br>3        1          1          1 <br>  (0, 0)	1<br>  (1, 0)	1<br>  (1, 1)	1<br>  (0, 2)	1<br>  (1, 2)	1</pre><p>So in this simple example, binary relevance predicted that the spot in the first row in the first column (0,0) was true for the label “lunch_talk”, which is the correct label based on our original inputs. In fact, in this very simple example, binary relevance predicts our labels perfectly.</p><p>Here’s a<a href="https://github.com/AlludedCrabb/Toy_Binary_relevance_Example/blob/master/Toy_Example_Binary_Relavance.ipynb"> link</a> to this example on Github if you’d like to see the steps in more detail. Or better yet, check out this <a href="https://towardsdatascience.com/journey-to-the-center-of-multi-label-classification-384c40229bff">blog</a> on the subject, which has more detail, and a link to the Github page I used as a starting point.</p><p><strong>Transfer Learning and Weak Supervision</strong></p><p>One bottleneck in machine learning models is a lack of labeled data to train our algorithms for identifying hate speech. Two solutions are transfer learning and weak supervision.</p><p>Transfer learning implies reusing already existing models for new tasks, which is extremely helpful not only in situations where lack of labeled data is an issue, but also when there is a potential need for future relabeling. The idea that a model can perform better if it does not learn from scratch but rather from another model designed to solve similar tasks is not new, but it wasn’t used much in NLP until Fastai’s <a href="http://nlp.fast.ai/classification/2018/05/15/introducting-ulmfit.html">ULMFiT</a> came along (<a href="https://towardsdatascience.com/a-technique-for-building-nlp-classifiers-efficiently-with-transfer-learning-and-weak-supervision-a8e2f21ca9c8">source</a>).</p><p>ULMFiT is a method that uses a pre-trained model on millions of Wikipedia pages that can be tuned in for a specific task. This tuned-in model is later used to create a classifier. This approach is impressively efficient: <em>“with only 100 labeled examples (and giving it access to about 50,000 unlabeled examples), </em>[it was possible]<em> to achieve the same performance as training a model from scratch with 10,000 labeled examples”</em> (<a href="http://nlp.fast.ai/classification/2018/05/15/introducting-ulmfit.html">source</a>). Another advantage is that this method can be used for languages other than English since the data used for the initial training was from Wikipedia pages available in many languages. Some other transfer learning language models for NLP are: Transformer, Google’s BERT, Transformer-XL, OpenAI’s GPT-2, ELMo, Flair, StanfordNLP (<a href="https://www.analyticsvidhya.com/blog/2019/03/pretrained-models-get-started-nlp/">source</a>).</p><p>Another paradigm that can be applied in case there is lack of labeled data, is weak supervision, where we use hand-written heuristic rules (“label functions”) to create “weak labels” that can be applied instead of labeling data by hand. Within this paradigm, a generative model, based on these weak labels is established first, and then it is used to train a discriminatory model (<a href="https://hazyresearch.github.io/snorkel/blog/weak_supervision.html">source)</a>.</p><p>An example of using these two approaches is presented in <a href="https://towardsdatascience.com/a-technique-for-building-nlp-classifiers-efficiently-with-transfer-learning-and-weak-supervision-a8e2f21ca9c8">this article</a>. Abraham Starosta, Master’s Student in AI from Stanford University, shows how he used a combination of weak supervising and transfer learning to identify anti-semitic tweets.</p><p>He started with an unlabeled set of data of about 25000 tweets and used Snorkel (a tool for weak supervision labeling) to create a training set through writing simple label functions. Those functions were used to train a “weak” label model in order to classify this large dataset.</p><p>To apply transfer learning to this problem, he fine-tuned the ULMFiT’s language model by training it on generalized tweets. He then trained this new model on the training set created with weak supervision labeling. The results were quite impressive: the author was able to reach 95% precision and 39% recall (probability threshold of 0.63), while without using weak supervision technique, it would be 10% recall for a 90% precision. The model also performed better than logistic regression from sklearn, XGBoost, and Feed Forward Neural Networks (source).</p><p><strong>Voting Based Classifications</strong></p><p>Voting based methods are ensemble learning used for classification that helps balance out individual classifier weaknesses. Ensemble methods combine individual classifier algorithms such as: bagging (or bootstrap aggregating), decision trees, and boosting. If we think about a linear regression or one line predicting our y values given x, we can see that the linear model would not be good at identifying non-linear clusters. That’s where ensemble methods come in. An “appropriate combination of an ensemble of such linear classifiers can learn any non-linear boundary.” (<a href="http://www.scholarpedia.org/article/Ensemble_learning">Source</a>) Classifiers which each have unique decision boundaries can be used together. The accuracy of the voting classifier is “generally higher than the individual classifiers.” (<a href="https://towardsdatascience.com/ensemble-learning-in-machine-learning-getting-started-4ed85eb38e00">Source</a>)</p><p>We can combine classifiers through majority voting also known as naive voting, weighted voting, and maximum voting. In majority voting, “the classification system follows a divide-and-conquer approach by dividing the data space into smaller and easier-to-learn partitions, where each classifier learns only one of the simpler partitions.” (<a href="http://www.scholarpedia.org/article/Ensemble_learning">Source</a>) In weighted voting, we can count models that are more useful multiple times. (<a href="https://www.aclweb.org/anthology/Y07-1050">Source</a>) We can use these methods for text in foreign languages to get an effective classification. (<a href="http://bit.ly/2wiZTpZ">Source</a>) On a usability note, voting based methods are good for optimizing classification but are not easily interpretable.</p><p>Awareness of how powerful machine learning can be should come with an understanding of how to address its limitations. The artificial intelligence used to remove hate speech from our social spaces often lie in black boxes. However, with some exploration of natural language processing and text classification, we can begin to unpack what we can and cannot expect of our A.I. We don’t need to be part of a tech giant to implement classifiers for good.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d307356b9eba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/classifying-hate-speech-an-overview-d307356b9eba">Classifying Hate Speech: an overview</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[Ever washed a panda?]]></title>
            <link>https://medium.com/data-science/ever-washed-a-panda-c94d23c47667?source=rss-58811da7f0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94d23c47667</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jacob Crabb]]></dc:creator>
            <pubDate>Wed, 15 May 2019 16:53:10 GMT</pubDate>
            <atom:updated>2023-02-06T20:29:00.912Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ever Washed A Panda?</h3><h4>a brief introduction to DataFrame cleaning in pandas</h4><p>Often in data science, we get excited by the goals of a project. “I’m going to predict fuel efficiency with a regression model and get my results within 5 percent accuracy!” And we’re tempted to run with the idea right then and there. Starting with a great goal in mind can be a great motivator, but beware the dangers of skipping over one of the most important parts of any project: the data cleaning. It may not be flashy, you may not be saving the world, but in the words of one wiser than I:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1paf0tasfGaPNo39Av9IOQ.jpeg" /><figcaption>A wise old tree teaches life lessons</figcaption></figure><p>Really getting to know a dataset before rushing into predictions is the best way to form a healthy, lasting relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*yPbsxZ-o0WrWdPbQ8rFrqw.jpeg" /><figcaption>At the panda wash! woah woah woah at the…</figcaption></figure><p>Trust me, data rewards us for slowing down to consider things from all angles. Let’s ask some basic questions: When we look at our data what do we see? Should we be seeing that? What is each column’s intended meaning? Are the values meant to be taken literally or are they categorical? How do the values in the column relate to the values in other columns? I know these might seem like ridiculously simple questions, but starting small can help you catch things you might otherwise miss if you were in a hurry. You might be surprised how simple questions can lead to more complicated ones.</p><p>All right, it’s time put on our raincoats, grab a sponge and a squeegee, and get a little dirty.</p><p>For the purposes of this exercise, we’ll say I’m trying to predict game scores based on the available data. I’ll be using a game reviews dataset from kaggle which can be found here: <a href="https://www.kaggle.com/egrinstein/20-years-of-games/downloads/20-years-of-games.zip/2">https://www.kaggle.com/egrinstein/20-years-of-games/downloads/20-years-of-games.zip/2</a></p><ol><li>When we look at our data, what do we see? Should we be seeing that?</li></ol><p>Let’s start by importing pandas and reading the csv file into a dataframe:</p><pre>import pandas as pd<br>df = pd.read_csv(&#39;ign.csv&#39;)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPMONjQVXOC-9CG0ECOXgQ.png" /><figcaption>a first look at our dataframe</figcaption></figure><p>Right from the start, I can see a couple of issues. First off, it looks like this csv file has it’s own index column. Keeping both would be redundant, so let’s get rid of ours by specifically calling the csv index column.</p><pre>df = pd.read_csv(&#39;ign.csv&#39;,index_col=&#39;Unnamed: 0&#39;)</pre><p>2. What is each column’s intended meaning? Are the values meant to be taken literally or are they categorical?</p><p>We have two possible columns which include scores: score_phrase, which looks like text, and score, which appears numeric. In context, both of these columns seem to be representing categorical data. Let’s take a look at their data types and values:</p><pre>df.score_phrase.value_counts()</pre><pre>Great          4773<br>Good           4741<br>Okay           2945<br>Mediocre       1959<br>Amazing        1804<br>Bad            1269<br>Awful           664<br>Painful         340<br>Unbearable       72<br>Masterpiece      55<br>Disaster          3<br>Name: score_phrase, dtype: int64</pre><pre>df.score.describe()</pre><pre>count    18625.000000<br>mean         6.950459<br>std          1.711736<br>min          0.500000<br>25%          6.000000<br>50%          7.300000<br>75%          8.200000<br>max         10.000000<br>Name: score, dtype: float64</pre><p>So it looks like score_phrase has 11 different text values, which can easily be converted to 11 number rankings. score appears to be a number ranking system, going from 0 to 10. Now it’s time to make a decision. Do I use score? score_phrase? or a mixture of the two? Let’s get some more information before making a decision.</p><p>It seems strange to include both a score and score_phrase column in the same dataset. I would hypothesize that score_phrase might be based on the scores from the score column, let’s find out. Below I’ll look up rows in the dataframe for Disaster, to see what the values in the score column are. I’ll do the same for all the unique values of score_phrase.</p><pre>score_dict = {&#39;Disaster&#39;: [],<br>              &#39;Unbearable&#39;: [],<br>              &#39;Painful&#39;: [],<br>              &#39;Awful&#39;: [],<br>              &#39;Bad&#39;: [],<br>              &#39;Mediocre&#39;: [],<br>              &#39;Okay&#39;: [],<br>              &#39;Good&#39;: [],<br>              &#39;Great&#39;: [],<br>              &#39;Amazing&#39;: [],<br>              &#39;Masterpiece&#39;: []}</pre><pre>for name in score_dict.keys():<br>    score_dict[name] = df.loc[df.score_phrase == name].score.values<br>    print(name,<br>          score_col_dict[name].min(),<br>          score_col_dict[name].max())</pre><pre>Disaster 0.5 0.8<br>Unbearable 1.0 1.9<br>Painful 2.0 2.9<br>Awful 3.0 3.9<br>Bad 4.0 4.9<br>Mediocre 5.0 5.9<br>Okay 6.0 6.9<br>Good 7.0 7.9<br>Great 8.0 8.9<br>Amazing 9.0 9.9<br>Masterpiece 10.0 10.0</pre><p>To be sure let’s look at our results in a box plot with 0 representing Disaster and 10 representing Masterpiece:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r00hPrOlLxTjjrQ--9pjjQ.png" /></figure><p>It looks like the values in the score column directly affect the score_phrase values, so we can do away with the score_phrase column altogether.</p><p>Now let’s take another look at our dataframe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irnOxZGY_wHqv94K6D5g_Q.png" /></figure><p>It appears that the editors_choice column is also a binary yes or no column. Let’s turn it into zeroes and ones to make it easier to work with.</p><pre>df.editors_choice = df.editors_choice.astype(&#39;category&#39;)<br>df.editors_choice = df.editors_choice.cat.codes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpwAZAGTQcNs9w2Edo3QjA.png" /><figcaption>Change the editors_choice column</figcaption></figure><p>Now that we’ve done the more obvious things, it’s time to make more thoughtful decisions. What is useful information for making our predictions? The title? While titles are definitely important, I don’t think they affect the ratings, only the discovery of the games. The URL? that’s just a tool for people using the data set to learn more about each. What about the platform? Does the platform you release your game on effect your rating? I would say yes. Let’s trim it down a little bit more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJeDh_LY5wGh5m8x0lfLvw.png" /></figure><p>What about those different columns for year, month, and day? Would it be better to put those into a single datetime column? How should we treat the different values of the platform column? What about the genre? These are all great questions going forward, and it’s important to ask and answer not just these, but even more questions about your dataset. Once you’ve finally cleaned everything up and fully understand the data, then and only then should you proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*JqXi3dwuSE0l6h89ogQx-A.gif" /><figcaption>Don’t be hasty</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94d23c47667" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ever-washed-a-panda-c94d23c47667">Ever washed a panda?</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[Foiled again! A brief discussion on folium]]></title>
            <link>https://medium.com/data-science/foiled-again-a-brief-discussion-on-folium-2258db4c9d7f?source=rss-58811da7f0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2258db4c9d7f</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Jacob Crabb]]></dc:creator>
            <pubDate>Wed, 01 May 2019 00:19:03 GMT</pubDate>
            <atom:updated>2023-02-06T20:29:29.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Foiled Again! A Brief Discussion On Folium</h3><p>When you’re thinking about visualizations, there’s lots and lots of good choices out there: Bar charts for when you’re bar-hoppin&#39;, scatter plots for when you’re scatter-brained, histograms for those days when you just wanna throw a histy-fit, and of course, pie charts for dessert. Today though, I’m gonna say a few words about a helpful library called Folium, which is particularly fun to use because it throws all the information into the real world around you with maps.</p><p>For instance, say I have a list of latitudes and longitudes for all the pizza places near me, but I’d like to get a more concrete visual of what those numbers actually mean. I can run those lists into Folium to easily plot each of the points on a map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXWNhMHDBf_oXyyjJFtSZA.png" /></figure><p>Nice! Now I’ve got a clear idea of where to find pizza shops near me. But let’s say I don’t just want to know what their location is, maybe I also want to know some information about each one. Through computer magic this is easily doable! Folium gives us the ability to place popup information at every point, so you can store relevant information right there, waiting to be clicked!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDKA6W14n5mFglr_UbTUJw.png" /></figure><p>Do I feel like having five-star pizza today? Probably. Do I feel like paying top dollar for five-star pizza today? Probably not, so it’s good to have this feature to let me know ahead of time.</p><p>For a lot of you, this is a very familiar image. You can go onto google maps and see images just like this in the time it takes to snap your fingers (or question all you’re life choices if you’re quick about it :P). So now I’ll show you something you won’t see on google. Let’s say we don’t want to know where the nearest pizza places are anymore, let’s say we want to know the density of Starbucks in one part of town as opposed to the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hsbLGOAaljC5YQMiexXedA.png" /></figure><p>As you can see the ‘hot’ spot for Starbucks is downtown, which makes sense since foot traffic is very high. As you get farther away though, foot traffic as transportation becomes less common and buildings are farther apart, so the density of Starbucks decreases. Folium heatmaps are useful when you’ve got too many points to view individually, this lets you see the relationship between your points without bogging down the image with countless markers. Pretty sweet!</p><p>So far we’ve been using the default map background, but no more! Folium has lots of customizability. Maybe you’ve gotten tired of seeing roads and cities, maybe less information is more for your particular graphic, maybe you’re recreating the classic board game designed by Larry Harris: Axis and Allies, but on a grander scale. And say you want it in black and white, cause why not? Your wish is Folium’s command!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XTFDg6eb8o99OJQGXPhMQ.png" /></figure><p>Or maybe you’ve drunk all the coffee you can drink, stuffed yourself with more pizza than humanly possible, and you’ve decided to leave the city in search of solitude atop a dormant volcano. More power to you! Folium has a terrain option so you can look at things through a more geographic lense. Looks like you’ve got a bit of a journey ahead. Be sure to wear shoes with ankle support!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wz3AdXEyvqv40S7xIphLSA.png" /></figure><p>While our friend sets off in search of mountain air, blisters, and inner peace, I’m noticing that the markers on our maps are starting to look a bit bland. You might guess that Folium provides customizable markers, and if you guessed that, you’d be right! Let’s take a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ms3kXnMX0IJjSYocKxbwHw.png" /></figure><p>Lots of different colors and icons are available, and legions more can be found online from places like Font Awesome!</p><p><a href="https://fontawesome.com/?from=io">Font Awesome 5</a></p><p>Folium has more than just markers. Maybe you want to see the general area around each point. For showing a radius a great choice would be the circle option, that way you can get a feel for what places might share a delivery range or something of that nature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OSMKJJo8o9mIRwIGRMYvA.png" /></figure><p>As you can see Folium has lots of really great things going for it. Lots of available customizations: different map styles and markers, different icons and colors, and it’s pretty easy to use too. I like Folium a lot because it helps to visually break down location information in a way that’s clear and easy to understand. Imagine trying to make sense of the same information using scatter plots or bar charts, you could do it, but this is better in my opinion. Hopefully, this gave you some ideas about how you could use Folium in your own projects. Well, I’m just about out of time, and completely out of puns, so that’s all for now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2258db4c9d7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/foiled-again-a-brief-discussion-on-folium-2258db4c9d7f">Foiled again! A brief discussion on folium</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[Visualizations: a Regressive Gene]]></title>
            <link>https://medium.com/@alludedwinter/visualizations-a-regressive-gene-235a4334276f?source=rss-58811da7f0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/235a4334276f</guid>
            <category><![CDATA[visualisation]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jacob Crabb]]></dc:creator>
            <pubDate>Fri, 19 Apr 2019 16:29:13 GMT</pubDate>
            <atom:updated>2023-02-06T20:29:56.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>Visualizations: A Regressive Gene</h3><p>When working on your varied projects, it’s important to get information across quickly and clearly. While you may know exactly what to look for in the sea of numbers related to your project, the next person to come along may not. Nobody likes trudging back and forth across the page in a futile quest for one key piece of knowledge. Fortunately, we have weapons in this war on fact-finding frustration. Plots and graphs! Good visualizations can really break up the… well, the this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVsgyAj_xotA0KrYVomccg.png" /></figure><p>My project partner @Taeho Jeon and I recently did a project on regression. This will more or less be a tour of our visualizations throughout the project. Our goal was to use King County housing sales data to build a model for predicting home sale prices. To start, we explored the data with pandas, pouring through rows and columns like what you see above. Welcome to monotony. So we decided to shake things up by looking at our data from another angle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPI0WuIwV0vzbpK7Zut1WQ.png" /></figure><p>That helps us get some perspective on the areas we’re dealing with. A latitude and longitude scatter plot really helped to show us the individual home sales. (the redder the color, the higher the mean sale price in thousands).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*w55nFjW7difG-7ajg3o1Sw.png" /></figure><p>How refreshing! We can see where home sales are concentrated and where they’re sparse, as well as get some idea of what kind of houses tend to be in each area. After a few other considerations, we dove into our first simple regression model. We set the style to ‘bmh’ to give the background some gridlines and color. Then we made our regression line yellow to give it some contrast. A very basic plot, but it’s clean and expresses our regression pretty well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*VlkpaoSvKpNrOl0iaMUV_A.png" /></figure><p>From this plot, we can see there’s some heteroskedasticity in our data. Our regression model definitely still needs some work. What comes next? We chose data cleaning: removing outliers and fixing bad or missing values as best we could. While we were cleaning house, we found yet another problem: our target variable was quite skewed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*2bc5wfKml2xeetFf_xAEbg.png" /></figure><p>Regression assumes a normal distribution, so leaving this kind of skew in our model would cause all kinds of problems. So we decided to use a natural logarithm to bring it into a more normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*fGtv3WxaJTbwSEY_8U3DBA.png" /></figure><p>That’s better, so long as we remember to use the exponential function should we need to undo our changes. Now that we’ve got the data cleaned up a bit, we can look at our regression plot again. As you can see, things look pretty different after we’ve cleaned the data up. Our points fit tighter together, and most of the heteroskedasticity has been taken care of as well. Progress, sweet progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*pmK4PZXcrPIEBcWkMiyKrQ.png" /></figure><p>Of course when it comes to regression, simple is not enough. From here we have to dive into multiple linear regression. What predictors are useful? Does each have a logical connection to the target? How long has it been since I’ve slept? all good questions. But we started by checking for multicollinearity. Bring on the scatter matrix!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*7vSr5juWwArSOQNamS5W1w.png" /></figure><p>Remind you of anything? Columns and rows full of useful information, and if you can focus on all of that at once, we applaud you. A slightly easier plot that can tell you almost all of the same data is this lovely heatmap below. What’s hot? What’s not? You decide!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*VGA6yg7c8jCV63k3PCGVdA.png" /></figure><p>Ok, so we’ve learned quite a bit from the plots above, but what about when we’ve got lots of categorical information to show? During the evaluating of our model, we decided to parse through each zip code and compare model performance to each. This would be a lot of information to read through, but with the right visualization, anything can be easy to understand. What zip code are we looking at? How does the error rate compare to other zip codes? It’s all explained visually. Bars are good for more than chocolate you know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECCzzH11Mx9gpP1qK2qO2Q.png" /></figure><p>Or if you’re not a fan of the bars, there’s one more bonus visualization to show. Here we have all of the same information and a little more. Red is high error and blue is low. Take a look from our familiar bird’s eye view. How far is one zip code from another? Where does our model perform best? Where does it perform the worst? It’s easy to see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZ1vN79ojoa11q-d_5aSmg.png" /></figure><p>Choosing the right visualization can make all the difference between trudging through the data and instant understanding. We had a ton of fun (and a few frustrations) with this project, but the right plots and graphs definitely made it better. If only making the perfect model was as easy as creating some interesting and fun plots, then… something would happen, not sure what. Hopefully, this gave you some ideas for visualizations of your own. Go out. Be brave, but most importantly, plot your heart out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=235a4334276f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science: A Nautical Introduction]]></title>
            <link>https://medium.com/@alludedwinter/data-science-a-nautical-introduction-c34dbc1aae2b?source=rss-58811da7f0c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c34dbc1aae2b</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jacob Crabb]]></dc:creator>
            <pubDate>Sun, 14 Apr 2019 22:10:01 GMT</pubDate>
            <atom:updated>2019-04-14T22:10:01.406Z</atom:updated>
            <content:encoded><![CDATA[<p>I am the pirate captain of a ship constantly in storms, going up one wave and down another, hands fused to the wheel, searching for calmer waters. This fundamental lack of status quo, this continual distress of spirit, this ever stormy sea causes me to reach for those few things in life that I have control over. Control starts with understanding. Understanding information is one of the most primal and natural forms of control. How many of us as kids learned a fantastic secret, something that was understood by the individual, then lorded that knowledge over everyone else? “I know something, but I’m not gonna tell! I know the secret to winning at Mario Kart 64, so eat my dust!” Sadly, my term as Mario Kart champion did not last…. The idea of control changes and evolves as we age. Many are the VCR’s, CD players, and cellphones I took apart in a quest for something I could deconstruct and understand (few of those unfortunate devices were ever reconstructed). This drive continued into studying and improving video game performance, committing to various extreme exercise plans, diets, writing stories, drawing, saving every penny, and any other variables that were wholly within my authority. Like those old VCR’s, few of these ever produced a reassembled result. I found myself working as a pizza delivery driver, the same job I’d taken five years prior as a 19-year-old looking for any way to earn a paycheck. What a pair that had made; a man who deeply wanted to understand the cause of things, and a job where even your income was entirely based on the winds of chance. I made a good living overall. I owned my own car, my own computer, my own house, but I was still subject to something that was by definition out of my control. So I left. I set off to write the next best-selling novel: to take charge of my sea, to find my own path. 9 months of drafts, edits, and rewrites later, I presented my ultimate creation. The world didn’t move. Once again I was subject to things I could not control. The ship lurched. This captain let go of the wheel. “Let the sails hang open, the sea can take us where she pleases” I spouted before going below deck. The seas raged. The hull shook. I contented myself with fixing what leaks I could and contemplating the way of things. It was in this state of minding my own business, on a certain lazy Monday in September, that I got an email from a company called Thinkful. They were doing a data science webinar. I immediately dismissed it. They had once ignored my application to enroll, plus, I valued my Saturday far more than a 2 hour Q and A. Tuesday went by, I remained resolute. Wednesday came. My curiosity overpowered my will. I RSVP’d. The webinar turned out to be informative and interesting. Still, I resisted. Two days later I got an email from the Flatiron School offering a data science scholarship. You might call that good advertising (and it was), but I’d been aware of the Flatiron School for a while, had even looked into some of their programs. The timing seemed too convenient, so I took it as a sign. Five months of continual study led to attendance at a formal data science school. Now that I’m fully entrenched in the study of data science, I find two things to be true: No 1: Data Science has challenged me in different and more punishing ways than I’ve ever known. The breadth of notions statistical, syntactical, dimensional, and mathematical can only be learned by boring a hole through one’s old ideas of understanding. This process is difficult and frustrating. No 2: the deeper I get, the more control it gives me, not just over the data and the machine, but in the organization of thought and mind. The computer requires complete and total clarity, even the smallest ignored detail can bring disaster to your end goals. This effect doesn’t stop when you put down the laptop. In everyday life, where once I would act on intuition and whim, I find myself stopping, framing the problem, considering steps, and deciding on a course of action before I even move a muscle. It’s always strange to look back and see how much you’ve changed over the years, but stranger still to see that change come about in a matter of months or weeks. Strange yes, but I think I like what I’m becoming. So though it’s hard, though it hurts, sometimes excruciatingly so, I will continue. In this stormy sea of mine, I have been given the greatest gift: a compass. The wind still howls. The waves still crash. The ship still shudders. But through the chaos, I’m finding true north. I’m steering toward an invisible path on the edge of the horizon. So it’s time to adjust my cap, take a swig O rum, strike up a shanty (perhaps not), and dare the sea to do her worst! The Captain is on deck! I guess all of this is a long-winded way of saying: Though I don’t see them yet, I may have finally found my calmer waters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c34dbc1aae2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>