<?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 Robert Miller on Medium]]></title>
        <description><![CDATA[Stories by Robert Miller on Medium]]></description>
        <link>https://medium.com/@rob3hr?source=rss-b50c493cd5d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cJa5yja8aP5OYVxQUb49gw.jpeg</url>
            <title>Stories by Robert Miller on Medium</title>
            <link>https://medium.com/@rob3hr?source=rss-b50c493cd5d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:47:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rob3hr/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[Iteratively Deleting Items in Dynamo DB using Python]]></title>
            <link>https://medium.com/@rob3hr/iteratively-deleting-items-in-dynamo-db-using-python-28082130f9f3?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/28082130f9f3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Fri, 08 Mar 2019 18:19:09 GMT</pubDate>
            <atom:updated>2019-03-08T18:19:09.228Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever inserted objects into dynamo db that you didn’t want to? I have done this many times and couldn’t find an easy way to delete these items.</p><p>First thing you will want to do it make sure you have boto3 installed. This is a strong library for connections to AWS.</p><pre>from boto3.dynamodb.conditions import Key, Attr</pre><pre>import boto3</pre><p>Now its time to set your resource and your table. For this case you will set up a dynamodb resource for boto3. You will then specify the table you want to delete items from.</p><pre>from boto3.dynamodb.conditions import Key, Attr</pre><pre>import boto3</pre><pre>dynamodb = boto3.resource(&#39;dynamodb&#39;, region_name=&#39;us-east-2&#39;)</pre><pre>table = dynamodb.Table(&#39;practice_mapping&#39;)</pre><p>I have my table set. I want to scan over my table, and i will scan over the Primary Key for the table. My primary key is called <em>job_id. </em>For this test case i want to delete all items with the primary key <em>testjob</em></p><pre>from boto3.dynamodb.conditions import Key, Attr</pre><pre>import boto3</pre><pre>dynamodb = boto3.resource(&#39;dynamodb&#39;, region_name=&#39;us-east-2&#39;)</pre><pre>table = dynamodb.Table(&#39;practice_mapping&#39;)</pre><pre>scan = table.query(</pre><pre>KeyConditionExpression=Key(&#39;job_id&#39;).eq(&#39;testjob&#39;)</pre><pre>)</pre><p>Now its time to iterate over the table and delete the entries for this table. In this test my secondary key is <em>image_path</em>.</p><pre>from boto3.dynamodb.conditions import Key, Attr</pre><pre>import boto3</pre><pre>dynamodb = boto3.resource(&#39;dynamodb&#39;, region_name=&#39;us-east-2&#39;)</pre><pre>table = dynamodb.Table(&#39;practice_mapping&#39;)</pre><pre>scan = table.query(</pre><pre>KeyConditionExpression=Key(&#39;job_id&#39;).eq(&#39;testjob&#39;)</pre><pre>)</pre><pre>with table.batch_writer() as batch:</pre><pre>    for item in scan[&#39;Items&#39;]:</pre><pre>        batch.delete_item(Key={&#39;job_id&#39;:item[&#39;job_id&#39;], &#39;image_path&#39;: item[&#39;image_path&#39;]})</pre><p>We have officially iterated over the primary key and deleted the results. Check to make sure all entries have been deleted, if not run again. Sometimes the connection will time out before all entries are deleted.</p><p>Good luck deleting entries with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28082130f9f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[D.C. Crime]]></title>
            <link>https://medium.com/@rob3hr/d-c-crime-9cdf6444a6b0?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cdf6444a6b0</guid>
            <category><![CDATA[prison-reform]]></category>
            <category><![CDATA[crime]]></category>
            <category><![CDATA[criminal-justice]]></category>
            <category><![CDATA[dc]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Fri, 26 May 2017 12:10:43 GMT</pubDate>
            <atom:updated>2017-05-26T12:10:43.849Z</atom:updated>
            <content:encoded><![CDATA[<p>My capstone for My Data Science Bootcamp is to analyze how space, time, and number of building permits can help predict violent crimes in the D.C. wards. In this analysis I got data from DC.gov’s website under crime map and I got building permit data from opendata.DC.gov.</p><p>In D.C in 2016 there were approximately 35,000 crimes, and those were only the ones documented by DC.gov’s website. Out of those there were about 6,000 violent crimes. I find this a disturbing statistic that can put fear into many residents.</p><p>I approached this problem from a few different directions. One of which being that I know that time and space are both strong predictors of how many violent crimes will happen in a given week. For example summer has an influx of crimes, so if we are trying to predict violent crimes during summer, looking at the past few weeks might be a good indicator of the week we are trying to predict.</p><p>For this I made an ARIMA model that will go through all of my Data frames (one for each ward) and use time series to predict.</p><p>I also thought that building permits might be able to show us some insights into violent crimes. My thought process here was that I figured analyzing building permits could show some aspects of gentrification and from papers I’ve read, the beginning of gentrification has an influx of crime in most areas.</p><p>When doing this analysis I did a PanelOLS regression and a Linear Mixed Affects Model so I could keep space and time constant and just look at the effect of building permits on violent crimes. My models turned out to be not predictive and the correlation between building permits and violent crimes was around 20%.</p><p>The ARIMA model that I created had a MSE (mean squared error) of 6, which is pretty good considering the range of violent crimes if from 1–50.</p><p>For future steps I plan on looking more into spatial modeling for this problem. I also want to try a Bayesian regression to see if I can get better results. Lastly I want to find more gentrification indicator data and see how that affects violent crimes to see if we can target locations that the police should deploy more units</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cdf6444a6b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Quit my Job for Data]]></title>
            <link>https://medium.com/@rob3hr/why-i-quit-my-job-for-data-c7bfe181efed?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7bfe181efed</guid>
            <category><![CDATA[general-assembly]]></category>
            <category><![CDATA[job-search]]></category>
            <category><![CDATA[quitting-a-job]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Wed, 17 May 2017 12:56:19 GMT</pubDate>
            <atom:updated>2017-05-17T12:56:19.392Z</atom:updated>
            <content:encoded><![CDATA[<p>I came out of George Mason with a degree in Mathematics. I was on the rode to success, the world was my oyster. Or so I thought. I started applying to all sorts of jobs, mostly analyst positions, teaching jobs, and contracting positions.</p><p>I finally got a job as a government account representative with my own clientele! Wait, what does that even mean?</p><p>I thought my position would be working on government contracts and analyzing data. Boy was I in for a surprise. I turned out to be making cold calls for 9 hours a day getting paid a meager salary that was embellished at my interviews by “potential bonuses”.</p><p>Not only was I cold calling government employees all day, I was getting 10k less than I was expecting a year. I thought I could suck it up for a year, get “professional work experience” so I could easily get another position. The days wore on, never ending phone calls, rote memorization of a pitch to be said every call. I thought making a competition with my co-workers to see who could get more leads could spice up the monotony. Once I won the competition there was no satisfaction, I was in a dead end job, losing everything I had just learned in college.</p><p>I started looking for other positions, but getting home at 7 was tiring, so I would be productive for maybe an hour every night. This dragged on for months before I learned about General Assembly. There was a program for data science where you learn Python and SQL and how to use those languages to make models and predictions! It sounded like a way back into working with data, relearning some of my math skills. I was weary though, I have never known how to code. It is also a 3 month immersive program, meaning full time, 5 days a week, with labs and projects that take up your weekends. I thought to myself “3 months, it costs a lot, no income, but it can help you get out of this dead end job into something you want to do. Lets do it”.</p><p>Here I am now, almost 3 months after, about to graduate the program, regretting nothing. Had I not had such a terrible first job I wouldn’t have ended up at General Assembly. I plan on using what I learned here and expanding my knowledge with a deeper dive into a data science position.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7bfe181efed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Twitter’s API]]></title>
            <link>https://medium.com/data-science/how-to-use-twitters-api-c3e25c2ad8fe?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3e25c2ad8fe</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[twitter]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Mon, 08 May 2017 13:29:36 GMT</pubDate>
            <atom:updated>2017-05-09T16:47:13.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*G5wQOQ8CygD7eg3sXGcMMg.png" /></figure><p>Why use an API? API stands for Application Programming Interfaces (APIs) and they allow you to access resources only available on the server. Lets learn how to use twitters API.</p><p>Firstly you will need a twitter account with your phone number attached for verification purposes. You will then need to go to <a href="https://apps.twitter.com/">apps.twitter.com</a> and create app so we can reference the coresponding keys Twitter generates for this app. These are the keys that we will use with our application to communicate with the Twitter API.</p><p>Now going into the code, we will need to install python-twitter API library</p><pre>!pip install python-twitter</pre><p>Make sure you understand Twitters rules for using their API, if you do not follow their rules they can block you from accessing data. Here is a link to some of their rate limits <a href="https://dev.twitter.com/rest/public/rate-limiting">https://dev.twitter.com/rest/public/rate-limiting</a></p><p>Now that we have our app, we have keys associated with the app.</p><h4>Key Setup</h4><ul><li><strong>consumer_key</strong> — Find this in your app page under the “Keys and Access Tokens”</li><li><strong>consumer_secret</strong> — Right under <strong>consumer_key</strong> in the “Keys and Access Tokens” tab</li><li><strong>access_token_key</strong> — You will need to click the “generate tokens” button to get this</li><li><strong>access_token_secret</strong> — Also available after “generate tokens” is pressed</li></ul><p>We will plug those specific keys into our function below</p><pre>import twitter, re, datetime, pandas as pd</pre><pre>class twitterminer():</pre><pre>request_limit   =   20    <br>    api             =   False<br>    data            =   []<br>    <br>    twitter_keys = {<br>        &#39;consumer_key&#39;:       , #add your consumer key<br>        &#39;consumer_secret&#39;:     , #add your consumer secret key<br>        &#39;access_token_key&#39;:    , #add your access token key<br>        &#39;access_token_secret&#39;:  #add your access token secret key<br>    }<br>    <br>    def __init__(self,  request_limit = 20):<br>        <br>        self.request_limit = request_limit<br>        <br>        # This sets the twitter API object for use internall within the class<br>        self.set_api()<br>        <br>    def set_api(self):<br>        <br>        self.api = twitter.Api(<br>            consumer_key         =   self.twitter_keys[&#39;consumer_key&#39;],<br>            consumer_secret      =   self.twitter_keys[&#39;consumer_secret&#39;],<br>            access_token_key     =   self.twitter_keys[&#39;access_token_key&#39;],<br>            access_token_secret  =   self.twitter_keys[&#39;access_token_secret&#39;]<br>        )</pre><pre>def mine_user_tweets(self, user=&quot; set default user to get data from&quot;, mine_retweets=False):</pre><pre>statuses   =   self.api.GetUserTimeline(screen_name=user, count=self.request_limit)<br>        data       =   []<br>        <br>        for item in statuses:</pre><pre>mined = {<br>                &#39;tweet_id&#39;: item.id,<br>                &#39;handle&#39;: item.user.name,<br>                &#39;retweet_count&#39;: item.retweet_count,<br>                &#39;text&#39;: item.text,<br>                &#39;mined_at&#39;: datetime.datetime.now(),<br>                &#39;created_at&#39;: item.created_at,<br>            }<br>            <br>            data.append(mined)<br>            <br>        return data</pre><p>We then need to instantiate our class to be able to use our functions above.</p><pre>mine = twitterminer()</pre><p>Lets use the API to get some tweets from Donald Trumps twitter</p><pre># insert handle we like<br>trump_tweets = miner.mine_user_tweets(&quot;realDonaldTrump&quot;)<br>trump_df = pd.DataFrame(trump_tweets)</pre><p>We have now successfully pulled tweets from Donald Trumps twitter onto our local machine to analyze. Good luck gathering your data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3e25c2ad8fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-use-twitters-api-c3e25c2ad8fe">How to use Twitter’s API</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[Git index lock error]]></title>
            <link>https://medium.com/@rob3hr/git-index-lock-error-f2035246f899?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2035246f899</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Mon, 01 May 2017 13:13:07 GMT</pubDate>
            <atom:updated>2017-05-01T13:13:07.742Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever had an error with git? Well a common error I have encountered is having a “.git/index.lock’: File exists”. This error will make it so you cannot pull or push from your repository, leaving you stranded. I have found a solution.</p><ol><li>Navigate to the top level directory for your repo</li><li>cd .git</li><li>rm -f index.lock</li><li>cd ..</li><li>cd add .</li><li>cd commit -m “your message”</li><li>cd push</li></ol><p>This will get rid of the lock and reopen the flow of git and allow you to pull from your github repos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2035246f899" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering: Why to Use it]]></title>
            <link>https://medium.com/data-science/clustering-why-to-use-it-16d8e2fbafe?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/16d8e2fbafe</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Mon, 24 Apr 2017 13:40:06 GMT</pubDate>
            <atom:updated>2017-04-24T13:40:06.894Z</atom:updated>
            <content:encoded><![CDATA[<p>As an new data science student who came from a no coding background, I like to explain complex topics in a simplified way. As if talking to myself before my program started. Well I hope you are all ready for some clustering.</p><p>Lets start with what is clustering? It is something that you have done, many times in fact. Its the act of looking for similarities and putting those similar points into a group (or cluster). Lets all think back to the last time we went out to eat. The first thing you want to find out is what type of food you want, Mexican, Chinese, Italian, ect. You are making clusters of multiple restaurants with those attributes.</p><p>Now to a more Data Science example, I am going to look at different attributes of seeds and see if clustering those attributes can help predict whether a seed is of a certain species or not.</p><p>Jumping right into the code, we need to import libraries in order to execute the following lines. I am also going to read in my dataset at the bottom</p><pre>%matplotlib inline <br><br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>from</strong> <strong>sklearn</strong> <strong>import</strong> cluster<br><strong>from</strong> <strong>sklearn</strong> <strong>import</strong> metrics<br><strong>from</strong> <strong>sklearn.metrics</strong> <strong>import</strong> pairwise_distances<br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br><strong>import</strong> <strong>matplotlib</strong><br>matplotlib.style.use(&#39;ggplot&#39;) <br><br><strong>import</strong> <strong>seaborn</strong> <strong>as</strong> <strong>sns</strong></pre><pre>seeds = pd.read_csv(&quot;../assets/datasets/seeds.csv&quot;)</pre><p>Just looking at the first few rows of my Dataframe, this is what it looks like. The code to look at this using pandas is seeds.head(), that will show the first 5 rows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*b__0KegWUwtWTqLJNmpUVg.png" /></figure><pre>seeds.species.nunique()</pre><p>I then looked at the amount of unique values in my species column, which is are Target value column (the thing we are trying to predict). It turns out there are three species in our dataset</p><pre><em># Plot the Data to see the distributions/relationships</em><br>cols = seeds.columns[:-1]<br>sns.pairplot(seeds, x_vars=cols, y_vars= cols, hue=&#39;species&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSD1P1oz4iRaz740Jry7mQ.png" /></figure><p>This is a scatter plot of how our different variables relate to each other, and the color (or hue which I set above) is each different species. So you can start to see that in general the seeds tend to cluster with their own species for the majority of our variables (predictors).</p><p>Since we have a Target value we could stop our clustering here, but many times that we will use clustering is when we don’t have a Target value. So I will drop our Target and see if our clustering will pick up on the differences and do a good job of predicting which seeds should be clustered together.</p><pre>X = seeds.drop(&quot;species&quot;, axis = 1)</pre><pre><strong>from</strong> <strong>sklearn.metrics</strong> <strong>import</strong> pairwise_distances<br><strong>from</strong> <strong>sklearn</strong> <strong>import</strong> cluster, datasets, preprocessing, metrics<br>X_scaled = preprocessing.normalize(X,axis=0)</pre><p>I dropped the Target value, I also imported a few more libraries from sklearn so I can normalize my data. Normalizing data is the process of organizing the attributes and relations of the database to scale all numeric variables in the range [0,1]. We do this so that columns like permiter with values of 15 don’t show more importance than columns like compactness which are below 1</p><pre><strong>from</strong> <strong>sklearn.cluster</strong> <strong>import</strong> KMeans<br><br>k = 3<br>kmeans = cluster.KMeans(n_clusters=k)<br>kmeans.fit(X_scaled)</pre><p>I am using kmeans clustering for this problem. It sets random centroids (center points for each group) and those centroids will continually shift until they are centered in a cluster of points to make the mean distance of all points as small as possible.</p><pre>inertia = kmeans.inertia_<br><strong>print</strong> &#39;Silhouette Score:&#39;, metrics.silhouette_score(X_scaled, labels, metric=&#39;euclidean&#39;)</pre><p>What I am doing above is looking at two different metrics to analyze how well our clustering method did. Inertia is the sum of squared error for each cluster. Therefore the smaller the inertia the denser the cluster(closer together all the points are)</p><p>The Silhouette Score is from -1 to 1 and show how close or far away the clusters are from each other and how dense the clusters are. The closer your silhouette score is to 1 the more distinct your clusters are. If your score is 1 think of your clusters as perfect little balls that are far away from each other with no miss classification.</p><p>Clustering can be used on many problems, whether you have a Target value or not, it is helpful to seek insights and see relationships.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16d8e2fbafe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/clustering-why-to-use-it-16d8e2fbafe">Clustering: Why to Use it</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[Natural Language Processing with Python]]></title>
            <link>https://medium.com/data-science/natural-language-processing-with-python-b3aad16f578f?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3aad16f578f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Mon, 17 Apr 2017 13:35:36 GMT</pubDate>
            <atom:updated>2017-04-17T13:39:14.871Z</atom:updated>
            <content:encoded><![CDATA[<p>There are many ways to use Natural Language Processing, also known as NLP. In this blog we will talk about count vectorizers and how this can be useful when making models.</p><p>Lets start with what is NLP. It is a way to make words into numerical values so we can analyze and make predictive models based on that data.</p><p>I like to show by example, so today we will read in dataset from sklearn with different emails based on categories. We will only read in four of the categories and practice using nlp on them. We will make a model to determine whether an email will fall into a certain category or not.</p><p>Firstly, we need to read in some of our dictionaries</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br>%matplotlib inline<br><em><br># Getting that SKLearn Dataset</em> <br><strong>from</strong> <strong>sklearn.datasets</strong> <strong>import</strong> fetch_20newsgroups</pre><p>This give us a few libraries to use and imports the data set from sklearn with our email information.</p><pre>categories = [<br>    &#39;alt.atheism&#39;,<br>    &#39;talk.religion.misc&#39;,<br>    &#39;comp.graphics&#39;,<br>    &#39;sci.space&#39;,<br>]<br><em># Setting out training data</em><br>data_train = fetch_20newsgroups(subset=&#39;train&#39;,categories=categories,<br>                                shuffle=True, random_state=42,<br>                                remove=(&#39;headers&#39;, &#39;footers&#39;, &#39;quotes&#39;))<br><em># Setting our testing data</em><br>data_test = fetch_20newsgroups(subset=&#39;test&#39;, categories=categories,<br>                               shuffle=True, random_state=42,<br>                               remove=(&#39;headers&#39;, &#39;footers&#39;, &#39;quotes&#39;))</pre><p>In this code block we are determining the 4 categories we want. Then making our training set and our testing set. We set categories equal to our above four categories, and removed the headers, footers, and quotes.</p><pre>data_train.keys() #tells us what keys are in our dataset</pre><pre>len(data_train[&#39;data&#39;]) #looks at the length of the data_train<br>len(data_train[&#39;target&#39;])#looks at the length of the data_test</pre><p>We are making sure that our Data and Target columns are of equal length, otherwise we will have errors when modeling.</p><pre><strong>from</strong> <strong>sklearn.feature_extraction.text</strong> <strong>import</strong> CountVectorizer<br><em><br># Setting the vectorizer just like we would set a model</em> <br>cvec = CountVectorizer(stop_words=&#39;english&#39;)</pre><pre><em># Fitting the vectorizer on our training data</em> cvec.fit(data_train[&#39;data&#39;])</pre><p>We set cvec equal to CountVectorizer so we can easily call it in the future. Additionally I added in stop_words = ‘english’. What this does is take our common english words such as , ‘the’, ‘a’, ‘and’, etc. This is useful so we don’t base our model on these words that don’t actually have predictive meaning. Then it needs to be fit on the data_train[‘data’].</p><pre>X_train = pd.DataFrame(cvec.transform(data_train[&#39;data&#39;]).todense(),<br>                       columns=cvec.get_feature_names())</pre><p>This step is transforming the training data. The .todense() will make this into a matrix (and easily convertible to a pandas DataFrame). Making the columns = cvec.get_feature_names() will make each column equal to a different word that we are analyzing.</p><pre><em># Which words appear the most.</em><br>word_counts = X_train.sum(axis=0)<br>word_counts.sort_values(ascending = False).head(20)</pre><p>I then made a word counter that will look through our transformed X_train and count the words up, and making sort_values(ascending = False) will start from the highest count words and go to the lowest.</p><pre>names = data_train[&#39;target_names&#39;]</pre><p>names is now equal to the 4 categories we initially read into our DataFrame.</p><pre>X_test = pd.DataFrame(cvec.transform(data_test[&#39;data&#39;]).todense(),<br>                      columns=cvec.get_feature_names())</pre><p>We then need to transform our X_test like we did above with our X_train.</p><pre>y_test = data_test[&#39;target&#39;]</pre><p>and set our y_test to be able to test how accurate our model is</p><pre><strong>from</strong> <strong>sklearn.linear_model</strong> <strong>import</strong> LogisticRegression<br>lr = LogisticRegression()<br>lr.fit(X_train, y_train) <br>lr.score(X_test, y_test)</pre><p>Our final step was to fit our model on the X_train and y_train and then to test our model on the X_test and y_test. lr.score(X_test, y_test) lets us know how well our model performed. In this case is was about 75% accurate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3aad16f578f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/natural-language-processing-with-python-b3aad16f578f">Natural Language Processing with Python</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[How to Web Scrape with python, simplified]]></title>
            <link>https://medium.com/@rob3hr/how-to-web-scrape-with-python-simplified-670d59fbf510?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/670d59fbf510</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Wed, 12 Apr 2017 12:30:54 GMT</pubDate>
            <atom:updated>2017-04-12T12:30:54.185Z</atom:updated>
            <content:encoded><![CDATA[<p>As a data science student, I am learning as I go. I particularly like to write about topics as I learn them so I can show difficulties I faced and hopefully help others avoid the same pitfalls.</p><p>So, what is webscrapping? It is going to websites and taking data from that page so you can then analyze that data.</p><p>If you think that this is too difficult, don’t be deterred. I never though I would be able to achieve creating a webscrapper.</p><p>Let start on an example. I want to look at Open table (a website that takes lunch and dinner reservations) to determine the restaurant names, the prices, and the locations.</p><pre><strong>from</strong> <strong>bs4</strong> <strong>import</strong> BeautifulSoup<br><strong>import</strong> <strong>urllib</strong></pre><p>As with most task, importing libraries are a necessary step. I have imported BeautifulSoup, which s a Python library for pulling data out of HTML and XML files. I also import urllib, which helps us to work with urls</p><pre><em># set the url we want to visit</em><br>url = &quot;http://www.opentable.com/washington-dc-restaurant-listings&quot;<br><br><em># visit that url, and grab the html of said page</em><br>html = urllib.urlopen(url).read()<br><em># we need to convert this into a soup object</em><br>soup = BeautifulSoup(html, &#39;html.parser&#39;, from_encoding=&quot;utf-8&quot;)</pre><p>This sets are url that we want to look and and grabs that page. Now using html(which we set in the above code) we can go through that url an extract data. Beautiful soup will help us parse through the html.</p><p>Now here comes the more difficult part. We need to go to the page and inspect it. Google chrome and Firefox both have good inspect functions. In either browser right click and press inspect. If that doesn’t work then open up the developer tools and inspect will be in there.</p><p>Since we are looking for the restaurant names, I will show below what using the inspect looks like when looking at the restaurant names</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jw221T4DWaD8Y8fElKu1iQ.png" /></figure><p>So I have opened my inspect tool, and scrolled over the restaurant name. If you can see in the box in the bottom of the picture there is a line highlighted. This says &lt;span class=”rest-row-name-text”&gt;&lt;/span&gt;</p><p>For this line, the name =’span’ and the attributes, called attrs (for coding) ={‘class’ : ‘rest-row-name-text’}. So lets make a for loop that will go through the page and return all of the restaurant names.</p><pre><strong>for</strong> entry <strong>in</strong> soup.find_all(&#39;span&#39;, {&#39;class&#39;: &#39;rest-row-name-text&#39;}):<br>    <strong>print</strong> entry.renderContents()</pre><p>In this loop we are saying for some entry in soup find all occurrences where there is a span tag and the attribute is class : rest-row-name-text. Then we print the entries which gives us all the names.</p><p>Similarly we will do this for location</p><pre><strong>for</strong> entry <strong>in</strong> soup.find_all(&#39;span&#39;, {&#39;class&#39;: &#39;rest-row-meta--location rest-row-meta-text&#39;}):<br>    <strong>print</strong> entry.renderContents()</pre><p>and price.</p><pre><strong>for</strong> entry <strong>in</strong> soup.find_all(&#39;div&#39;, {&#39;class&#39;: &#39;rest-row-pricing&#39;}):<br>    price = entry.find(&#39;i&#39;).renderContents()<br>    <strong>print</strong> price.count(&#39;$&#39;)</pre><p>Price is a little different as you can see. In the print statement we find(‘i’) before we renderContents. If you inspect the page, there are a potential for four dollar signs, but if it is less that four dollar signs, then there with be, for example, &lt;i&gt; $$$&lt;i&gt;$. So the however many dollar signs are within the i’s is the price. Then printing the count will give us a numerical amount for easy analysis later.</p><p>Now I want to make one loop that will scrap all of this data at the same time and put it into a Dataframe.</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br>dc_eats = pd.DataFrame(columns=[&quot;name&quot;,&quot;location&quot;,&quot;price&quot;])</pre><p>I am importing pandas as pd and creating a Dataframe with three columns.</p><pre><strong>for</strong> entry <strong>in</strong> html.find_all(&#39;div&#39;, {&#39;class&#39;:&#39;result content-section-list-row cf with-times&#39;}):<br>    <br>    name = entry.find(&#39;span&#39;, {&#39;class&#39;: &#39;rest-row-name-text&#39;}).text<br>    <br>    location = entry.find(&#39;span&#39;, {&#39;class&#39;: &#39;rest-row-meta--location rest-row-meta-text&#39;}).renderContents()<br>   <br>    price = entry.find(&#39;div&#39;, {&#39;class&#39;: &#39;rest-row-pricing&#39;}).find(&#39;i&#39;).renderContents().count(&#39;$&#39;)<br>    <br>    dc_eats.loc[len(dc_eats)]=[name, location, price]</pre><p>This takes all three of the loops we made and stick them into one loop. It then adds all of those values to our Dataframe.</p><p>That is how I did basic web scraping.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=670d59fbf510" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K nearest neighbors, it’s purpose and how to use it]]></title>
            <link>https://medium.com/data-science/k-nearest-neighbors-its-purpose-and-how-to-use-it-36fa927acc64?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/36fa927acc64</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Mon, 03 Apr 2017 13:54:36 GMT</pubDate>
            <atom:updated>2017-04-04T17:34:24.181Z</atom:updated>
            <content:encoded><![CDATA[<p>For those of you who don’t know what k nearest neighbors is, it is a predictive model. Whats its purpose, why use it? Those are the questions we will delve into in this post.</p><p>In order for this model to work the data must have a notion of distance. In laymens terms, we need to be able to graph our data.</p><p>This model will is non-linear and can be used on classes. What I mean by classes is it can help determine if a data point will be part of one class or another. A good example is determining if someone will be a republican or democrat based on their income and age. This model will prove useful because in essence it looks at the neighboring data points to determine what this new data point will fall into.</p><p>Now that we know why this is useful, lets give an example with how to do this in python.</p><p>This example will be using pedal width, pedal length, sepal length, and sepal width to try to determine the classification of flower</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br>url = &#39;http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data&#39;<br>col_names = [&#39;sepal_length&#39;, &#39;sepal_width&#39;, &#39;petal_length&#39;, &#39;petal_width&#39;, &#39;species&#39;]<br>iris = pd.read_csv(url, header=None, names=col_names)</pre><p>Firstly, I imported pandas (a python library) and then read in my dataset and set column names. This puts my data into a nice dataframe that can easily be analyzed.</p><pre><strong>from</strong> <strong>matplotlib.colors</strong> <strong>import</strong> ListedColormap<br>cmap_bold = ListedColormap([&#39;#FF0000&#39;, &#39;#00FF00&#39;, &#39;#0000FF&#39;]</pre><p>The chunk of code above imports color graphing ability .</p><pre>iris[&quot;Species_number&quot;] = iris.species.map({&#39;Iris-setosa&#39;:0,&#39;Iris-versicolor&#39;:1,&#39;Iris-virginica&#39;:2 })</pre><p>I then made a new column mapping each species to a different bin, the bins being 0,1, or 2.</p><pre>iris.plot(kind = &#39;scatter&#39;, x = &quot;petal_length&quot;, y = &quot;petal_width&quot;, c =&quot;Species_number&quot; ,colormap= cmap_bold )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*_S-NpRtAdAbz-NKUpDKumw.png" /></figure><p>This shows pedal width and petal length to determine the species. The species each being a different color.</p><pre>feature_cols = [&#39;sepal_length&#39;, &#39;sepal_width&#39;, &#39;petal_length&#39;, &#39;petal_width&#39;] <br>X = iris[feature_cols]<br>y = iris.Species_number</pre><p>This Makes our X the sepal length, sepal width, petal length, petal width. Our Y is the species column with three bins. We are trying to use X features to determine Y</p><pre><strong>from</strong> <strong>sklearn.model_selection</strong> <strong>import</strong> train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y)</pre><p>For any good model you will want to do a train test split to avoid over fitting your model. What this does is takes your data and splits in to a training set, and then a testing set to test how well your model is. K nearest neighbors (also knows as KNN) is a lazy model, this means is that it does not use the training data points to do any <em>generalization. So </em>we are not going to train a model. Then why train test split you might ask? Because we still need that testing set to test on the 70% to see if our X variables are good predictors.</p><pre><strong>from</strong> <strong>sklearn.neighbors</strong> <strong>import</strong> KNeighborsClassifier<br><strong>from</strong> <strong>sklearn</strong> <strong>import</strong> metrics<br><em># make an instance of a KNeighborsClassifier object</em><br>knn = KNeighborsClassifier(n_neighbors=1)<br>knn.fit(X_train, y_train)</pre><p>We then import from sklearn.neighbors to be able to use our KNN model. Using KNeighborsClassifier and then the argument inside determines how many nearest neighbors you want your datapoint to look at. There is no rule of thumb for how many neighbors you should look at. The best way to find out how many neighbors to look at is to test a range of neighbors and determine what has the best accuracy.</p><pre>y_pred_class = knn.predict(X_test)<strong><br>print</strong> metrics.accuracy_score(y_test, y_pred_class)</pre><p>This will let you see the accuracy score, and since we only had 1 nearest neighbor to check, our score ended up being a 1 (also know as 100%), which has potential to be overfit.</p><pre><strong>def</strong> length(X, y):<br>    empty_list = []<br>    <strong>for</strong> n <strong>in</strong> range(1,100):<br>        X_train, X_test, y_train, y_test = train_test_split(X, y)<br>        knn = KNeighborsClassifier(n_neighbors=(n))<br>        knn.fit(X_train, y_train)<br>        y_pred_class = knn.predict(X_test)<br>        empty_list.append(metrics.accuracy_score(y_test, y_pred_class))<br>    <strong>return</strong> empty_list</pre><p>This function will test 1–100 nearest neighbors and return the accuracy for each. This will help you look for the best number of neighbors to look at for your model</p><p>Once you determine the Best neighbor you can use your model on other data points to put them into a class.</p><p>Thats how you use KNN, I hope this helped those of you interested in predicting what classes data points will fall into</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36fa927acc64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/k-nearest-neighbors-its-purpose-and-how-to-use-it-36fa927acc64">K nearest neighbors, it’s purpose and how to use it</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[Multi-Linear Regression in Python]]></title>
            <link>https://medium.com/@rob3hr/lost-when-it-comes-to-multi-linear-regression-988785c3fa55?source=rss-b50c493cd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/988785c3fa55</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Robert Miller]]></dc:creator>
            <pubDate>Sat, 25 Mar 2017 14:29:52 GMT</pubDate>
            <atom:updated>2017-04-13T18:45:01.709Z</atom:updated>
            <content:encoded><![CDATA[<p>Lets start with what it is, and whats the use. Multi-Linear Regression, or as I will refer to it in the rest of the post MLR, is a predictive model that compares 1 dependent variable with 2 or more independent variables.</p><p>Confused? well let me give you an example.</p><p>Let’s say I want to see “how much sleep a sample of 100 people get”. This will be my dependent variable. I then will look for independent variables that I think will affect this for our MLR. So I will choose as my independent variables as “How long it takes to commute to work”, “Day of the week”, “Time work starts”. These are three variables I think will affect how much sleep this sample gets, so I will use my MLR to test the effect of these variables on the dependent variable.</p><p>Still lost? Lets add in some code on how to make a MLR so you can see the process and understand what is going on better.</p><p>Firstly we will want to import our libraries. Note: some of these libraries I will not use in my example.</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br><strong>import</strong> <strong>seaborn</strong> <strong>as</strong> <strong>sns</strong><br><strong>from</strong> <strong>scipy</strong> <strong>import</strong> stats, integrate<br><strong>import</strong> <strong>statsmodels.api</strong> <strong>as</strong> <strong>sm</strong><br>%matplotlib inline</pre><pre>data = pd.read_csv(&quot;../3.03-linear-regression-part-i-lab/data/sacramento_housing_data.csv&quot;)<br>data = data[data.latitude &gt; 0]<br>data.drop_duplicates(inplace = True)<br>data = data[data.sq__ft&gt; 0]</pre><p>In the latter part of that code I am loading in a sacramento housing into a pandas dataframe(which I will call DF for the rest of this post) and then cleaning the data.(I skipped over my analysis of the data to find the tainted rows, but don’t forget to clean your data!)</p><pre>dummy_col = pd.get_dummies(data[&quot;type&quot;]) <br>dummy_col.head(1)</pre><pre>data_with_dum = data.merge(dummy_col[[&quot;Residential&quot;, &quot;Multi-Family&quot;]], left_index = True, right_index = True) <em>#merges dummy col to my DF by index since they have the same index</em><br></pre><p>I made a new DF called dummy_col to make my “type” column into my dummy variable. printing dummy_col.head(1) will just print the first row so I can visually see what I just did without printing the whole DF.</p><p>I then merges this DF with the dummy variables into my original DF on the indexes because they have the same index values (same number of rows).</p><p>Why you might ask are we making a dummy variable? This dummy variable will come in handy when using our MLR because it represent subgroups, so we do not have to code specifically for every subgroup.</p><pre>targets = pd.DataFrame(data_with_dum, columns=[&quot;price&quot;])<em>#have to set my target, which in this case will be the price</em></pre><p>My target is the price which is also our dependent variable, because we want to see how the price is affected by other variables.</p><p>Now here comes the fun part, making our model!</p><pre>X = data_with_dum[[&quot;beds&quot;,&quot;sq__ft&quot;,&quot;Residential&quot;]] <em>#chose three variables (one of which is a dummy variable)</em><br>y = targets[&quot;price&quot;]<br>X = sm.add_constant(X) <em>#add intercept</em></pre><p>I am setting an X equal to three variables. I am setting my y equal to our dependent variable. That last line of X = is just adding a constant to our model. What this constant does is sets a starting point. In this case we know price of a house/condo is never going to be $0.00 so this constant accounts for that.</p><pre>model = sm.OLS(y, X).fit() <br>predictions = model.predict(X)</pre><p>In the first line we are setting model to a simple ordinary least squares of y and X and then fitting it to that data with the .fit() command.</p><p>Then we are setting predictions = to our model that we defined above.predict() on X. Which will use our model to predict values of our dependent variable.</p><pre>plt.scatter(predictions, y, s=30, c=&#39;r&#39;, marker=&#39;+&#39;, zorder=10)<br>plt.xlabel(&quot;Predicted Values from model&quot;)<br>plt.ylabel(&quot;Actual Values Prices&quot;)<br>plt.show()<br><strong>print</strong> &quot;MSE:&quot;, model.mse_model</pre><p>This code above just shows us a scatter plot of how our model predicts the price vs the actual prices of this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*tC1BCE_lC5TwGnIVyFUHDQ.png" /></figure><p>As you can see, our model is relatively correlated. This predictive model does not do a train test split and is therefore suspect to over fitting, but I will leave that for another blog post.</p><p>I hope you enjoyed my experience with creating an MLR</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=988785c3fa55" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>