<?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 Matt Kirby on Medium]]></title>
        <description><![CDATA[Stories by Matt Kirby on Medium]]></description>
        <link>https://medium.com/@matt42kirby?source=rss-d65a2bb7f56b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4O1fDtuHaL8DviQE.jpg</url>
            <title>Stories by Matt Kirby on Medium</title>
            <link>https://medium.com/@matt42kirby?source=rss-d65a2bb7f56b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:57:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matt42kirby/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[Predicting Baseball Pitches]]></title>
            <link>https://medium.com/@matt42kirby/predicting-baseball-pitches-33f906cbbdee?source=rss-d65a2bb7f56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/33f906cbbdee</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[lambda-school]]></category>
            <category><![CDATA[baseball]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Matt Kirby]]></dc:creator>
            <pubDate>Mon, 14 Oct 2019 16:36:02 GMT</pubDate>
            <atom:updated>2019-10-14T16:36:02.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPFRlhQvYT6eN74PX_-lxg.jpeg" /></figure><h4>Utilizing Machine Learning to Predict The Next Pitch</h4><h3>Introduction</h3><p>The task of hitting a baseball at the major league level is extremely difficult- consider the benchmark for a GREAT hitter is a batting avg of .300- that’s only a 30% success rate. If the batter knew what pitch the pitcher was likely to throw next, his chances of success could improve significantly. Current analysis does a poor job of telling the story of the game through data. Pitchers are more predictable than people realize — people just aren’t using the proper tools to measure them.</p><p>Based on data obtained from the current pitcher’s prior tendencies, batter’s prior tendencies, game state, and the last n-chronological pitches, we use both techniques laid out in previous studies, and our own novel methods, to build machine learning models capable of predicting the next pitch.</p><p>Our work is intended to form the foundation for further study, and eventually, a consumer application encapsulating the pitch prediction functionality, integrating this with other information about the current game, pitcher, and batter, and presenting all of this information within an attractive user interface. Design decisions were made with this eventuality in mind, and many components were designed to be generalizable and scaled with elastic resources.</p><h3>Literature Review</h3><p>We scowered the web for relavent work and found numerous studies and posts relating to the problem of predicting the next pitch, but one stood out.</p><h4><a href="http://www.sloansportsconference.com/wp-content/uploads/2012/02/98-Predicting-the-Next-Pitch_updated.pdf">Predicting the Next Pitch</a></h4><p><em>By: Gartheeban Ganeshapillai and John Guttag, Massachusetts Institute of Technology</em></p><p>Using data compiled from a MLB STATS Inc. dataset the authors utilized pitcher specific linear support vector machines trained on input vectors from the 2008 season of 48 features and a binary label indicating the type of pitch. The model was tested on data from the 2009 season. A total of 359 individual pitchers were examined.</p><p>Features used included: the previous pitch, the count, the current score differential, the current base runners and some information about the pitcher’s tendency to throw a pitch (prior) with that property in various situations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YQ_zVimQdPs_dGXs" /></figure><p>The previous actions of the pitcher on the specific count, and the pitchers conduct with regards to the specific batter were found to be some of the most important features. An engineered feature referred to as shrunk prior was also found to be of prime importance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*fyK4o6zt5khm2Ijo" /><figcaption>Top 12 Features by Weight</figcaption></figure><p>A majority baseline accuracy of 59.5% on average was used to assess the performance of the model, which on average saw an accuracy score of 70%, with an average improvement of 18% on a by pitcher basis.</p><p>A suggestion for a future improvement was to add features pertaining to the batter who was on deck.</p><h3>Data Gathering</h3><p>Pitch data was collected from Statcast via the pybaseball package. Pybaseball’s statcast class allows us to query pitches by date range. After identifying the start and end dates of the 2016, 2017, 2018, and 2019* regular seasons, we were able to pull in Pandas Dataframes containing every pitch for each regular season. These Dataframes were then subject to rudimentary data cleaning described further in the Data Cleaning &amp; Feature Engineering section of this paper. After cleaning, the dataframes were compressed and stored in github as pickle files.</p><p>With future project developments in mind, the data, in addition to being compressed and stored in the main project GitHub repository as pickle files, was also stored in an S3 bucket as both pickle files and csvs. These csv files were then used to create a Redshift table, containing all regular season pitches from 2010–2019. This storage architecture is revisited in the following sections.</p><h3>Data Cleaning and Feature Engineering</h3><p>As is often the case in the field of data science, the majority of the time spent on this project was devoted to data cleaning, processing, and feature engineering. We built on the procedures and methods of previous iterations of similar projects undertaken in the past. First, we took a sort of high level overview of the project, and tried to layout a blueprint of all the necessary steps and how we wanted to approach transforming the raw pitch data from statcast into the format we wanted for our input vector into machine learning models. The main steps can be summarized as follows:</p><h4>General Data Cleaning</h4><p>Without going too far into the details, we encountered a few glitches in the data here and there during the process of data wrangling and feature engineering, so we added some code upfront to try to take care of most of it. Basically this included things like weeding out a small number of games played overseas w/o the Statcast camera tracking system installed, replacing unknown pitch type w/ NaN values, and fixing the number of balls from 4 to 3 in a few instances.</p><h4>Game State Features</h4><p>Here, we used the balls and strikes features to create a feature representing the current count for that at-bat, and then mapped the count into 3 categories representing whether the count favored the pitcher, the batter, or if the count was neutral. It stands to reason that pitchers approach these situations differently, and their choice of pitch should be heavily variable based on the favorability of the count.</p><p>Next we created a feature that represented the score differential, or how many runs ahead or behind the pitchers team was. Next, using the data for baserunners, we converted the baserunner features from using the baserunner id to a binary 1/0 whether or not a runner was on each base. Also we added a feature for whether ANY player was on any base vs bases empty, and also a feature whether or not the bases were loaded. A runner on first base has the potential to steal a base and advance, so perhaps some pitchers are less likely to throw as many breaking balls in the dirt that could get away from the catcher and allow the runner to advance into scoring position. Perhaps a runner on 2nd base with a clear view of the catchers pitch signals and potential to steal the sign and tip off the player at bat with a signal of their own could influence a pitchers choice of pitches. Maybe some of these tendencies could contribute to a machine learning model in making predictions.</p><h4>Strikezone and Batting Features</h4><p>Using the location data from the statcast camera system, of both the boundaries of the strikezone for that particular hitter based on his height/stance, as well as the dimension of the size of home plate, we created a feature that classified each pitch as in or out of the strikezone (regardless of whether the umpire called it a ball or a strike). Also, using the description feature, we extracted the descriptions and created a binary feature representing whether or not the batter swung at the pitch. By combining these engineered features, we created a feature to represent whether or not the hitter ‘chased’ a pitch that was outside of the strikezone. We thought this would be useful later when creating our scouting report on each batter, since if a batter has a tendency to chase at certain pitch types outside the strike zone, that information may be known by the pitcher in advance of the matchup and he may be more likely than otherwise to throw certain pitch types vs that player.</p><h4>Pitch Category and Null Value Imputation</h4><p>Unfortunately a very small percentage of the pitches in the statcast database, perhaps due to random glitches in the camera system or some other reason, had missing pitch type classification for that pitch. Rather than simply dropping all these rows from the dataframe, in order to preserve continuity of pitches on a game by game basis, we decided to impute these values. Our imputation strategy was just to use the overall distributions of pitch type for a given pitcher, and make a random guess (using those distributions as the weights for the random guess). Next, we mapped different pitch types into a more general pitch type category: fastballs (4-seam, 2-seam, cutter, sinker), breaking balls (curveballs, sliders, knuckle curves, screwball), and offspeed pitches (change-up, knuckle ball, and eephus pitch).</p><h4>Batter Specific Features</h4><p>Based on the intuition that most teams at the major league level create a scouting report on their opponents, we wanted to try to recreate that using data from the statcast pitch database. In addition to velocity, location, and break distance and angles, and various other data related to the pitch itself, the statcast data includes some cool features regarding balls put into play off the hitters bat. This data includes the launch speed and the angle/trajectory of the ball off the bat into the field of play. It also includes estimated values for batting avg, woba (weighted on base avg), and iso value (a power statistic) based on aggregate data for balls hit into play w/ a similar speed and angle/trajectory. Essentially sometimes a batter gets unlucky and hits a line drive squarely into play directly at where a defensive fielding player is positioned and makes the catch. If the ball had perhaps been a few feet in either direction, it would have resulted in a base hit or multiple-base hit. These estimated statistics sort of smooth out the variance of getting unlucky by hitting a ball directly at a fielder, and provide a more accurate representation of when a hitter makes solid contact on the pitch and the associated percentage of the time that contact would result in a base hit or the batter reaching base.</p><p>For each hitter, we filtered the dataframe for all pitches that hitter faced, and recorded the overall percentage of pitches faced for each pitch type category, thinking that if a batter faces an unusually high percentage of a certain pitch type category, perhaps there was an underlying reason that pitchers were doing that vs that hitter. Also, we aggregated those estimated batting avg, woba, and iso values for balls hit into play for each pitch category. Finally, we computed a feature for the batters taken strike percentage for each pitch type (how often the pitch was a in the strikezone and the batter chose not to swing), as well as how often the batter chased a pitch outside the strike zone, for each pitch category. Lastly, based on the ratio of the number of times the batter swung at each pitch type relative to the number of times the ball was put into play (rather than missed or fouled), we created a ‘ball in play swung’ percentage for each pitch category.</p><p>The goal of all of these batter scouting report features was essentially to try to capture any strengths/weaknesses for a particular hitter vs the different pitch type categories, that would perhaps be known in advance of the matchup and would replicate a real world scouting report that influences the pitchers choice of pitch vs a given hitter.</p><p>In order to prevent data leakage, where future/unknown data regarding a hitters tendencies was used to create these aggregates, the batter scouting report was created iteratively, month by month. The initial seed statistics were computed from 2017 pitch data, and then for each month of the regular season from 2018 thru the end of August 2019, we calculated the batter scouting report for all pitches in that month based only on prior information. The statistics for that month were then concatenated with the prior 2017 data and included in prior data for the next months calculations. Also, in order to lessen the effects of outlier data due to small sample sizes, if a batter had not faced 100 pitches of that pitch type, we assigned NaN values for that hitters scouting report for that pitch type. Later, we used aggregate data based on that batters position in the batting order to impute those NaN values, figuring that similar batters in the same batting order position was a close enough approximation.</p><p>At this point in the data pre-processing, we decided to save the dataframe to a pickle file and store in github, and eventually could be imported to csv or SQL db. This was a natural stopping point, because further pre-processing was done after choosing a particular pitcher.</p><h4>Pitcher Specific Features</h4><p>Once a particular pitcher has been chosen and a subset of the pitches thrown by him has been filtered from the database of all pitches, we used a similar approach to the batter scouting report to make features regarding prior tendencies of that pitcher. Here again we tried to avoid data leakage of future/unknown data to influence our aggregate statistics for that pitcher, so we used the same month by month iterative approach with 2017 data as the seed/prior database. We split the data into 2 subsets based on the handedness of the batter, assuming that the pitcher would approach left and right handed batters differently enough to be considered separately. We calculated the tendencies of that pitcher to throw each pitch type category, both overall, and further stratified by the count category (whether he was ahead, behind, or neutral situation relative to the batter).</p><p>We only chose a few select pitchers with a large sample of pitches, so, unlike the batter scouting report, we didn’t have to address imputation of NaNs or small samples from the prior database.</p><h4>Game by Game features</h4><p>Next, on a game by game basis, we added some features to the dataframe related to that particular game. These features can further be categorized as relating to the overall game state, or relating to the game-flow/ results of recent pitches.</p><p><strong>Batter Order and Pitch Count</strong></p><p>Using the at bat number and pitch number for each at-bat (and the batters id), we reverse-engineered the batting order for each hitter throughout the game. We created a batting order slot feature (including pinch hitters and pitchers, as well as added a binary feature for if the batter was a pitcher or position player), and additionally kept a running pitch count total for the full game. If a pitcher has any tendencies such as throwing more breaking balls later in the game the 2nd or 3rd time through the batting order, we wanted our machine learning models to be able to pick up on that.</p><p><strong>Game Flow Features</strong></p><p>Just because a pitcher historically throws pitches of a certain type at a certain frequency, there is a large degree of variance on a game by game basis, for various reasons. One major contributing factor is that on any given day, each pitcher may throw a certain pitch with more command and control than on another night. Maybe precipitation or humidity are affecting his grip and ability to generate spin on his curveball, so that game he may throw a higher percentage of fastballs and change-ups. Or maybe for whatever reason he is struggling to throw strikes and/or get guys out with his fastball, but he’s having more success with his slider and curveball on that particular day. In order to attempt to encapsulate some of these variables, we created a few features based on the trailing pitches he has thrown recently.</p><p>For the last three pitches, we tracked the pitch type, the location, whether the batter swung, chased, and what was the result of the pitch (ball, strike, or hit into play). For both the previous five and also the previous fifteen pitches, we created features that calculated the pitch type category percentages of those recent pitches, and we also tracked the percentage of strikes thrown.</p><p>Finally, we wanted to attempt to encapsulate any tendencies the pitcher may have, perhaps even at an unknown/subconscious level to the pitcher himself, on pitches thrown after giving up a walk, a base hit, run, or homerun, or after striking a hitter out. We created binary features for each of those scenarios relating to the previous at bat.</p><h4>Pitcher-Batter Prior Matchup Features</h4><p>The final category of features that we engineered were based on the pitch type frequencies from all previous at bats where a particular hitter faced off against the pitcher. Again, we used the iterative month by month approach here to prevent data leakage. For each pitch type category, we just created a feature for the overall percentage of that pitch category thrown vs that batter in all prior matchups. If the pitcher had never faced a particular batter in the prior database, we just used his overall tendencies vs batters of the same left or right handedness.</p><h3>Model Development and Hyperparameter Tuning</h3><h4>Binary Classification</h4><p>Initially, we approached predictive modelling as a binary classification problem. We wanted to establish some baseline models to predict whether a pitch was likely to be a fastball or not a fastball. After all, as a hitter, of course it would be useful to know the exact pitch type a pitcher is about to throw, but without such specific clairvoyance, knowing whether a fastball or not a fastball would also provide tremendous competitive advantage. If he knows a fastball is forthcoming, he can be on high alert to start his swing in time to catch up with the higher velocity. Conversely, the few extra milliseconds of anticipation/holding back for something breaking or offspeed would also confer an advantage to a major league caliber hitter.</p><h4>Multiclass Classification</h4><p>We used a similar approach as with our binary classification models, but instead of using fastball/not fastball as the target variable, we used the specific pitch type. The number of different types of pitches varies by pitcher, of course, since not every pitcher has every possible pitch type in their arsenal.</p><p>For all of our predictive modelling, we tested several different types of models and compared the accuracy of the predictions across model types for a handful of select starting pitchers who had a large sample size of pitches thrown in 2018–2019.</p><h4>Encoding Categorical Variables</h4><p>For our binary classification models, we encoded the categorical variables using a custom ordinal encoding strategy. For features that contained information about the description of the result of a previous pitch, we used a sliding scale that mapped values along a spectrum. The spectrum ranged from lower values for strikes and foul balls, to more neutral values for pitchout, hit into play where the result was unknown, to higher values for more negative results such as balls, hit by pitch, hit into play and no out was recorded, and finally, hit into play run scored as the highest value. A similar spectrum was used for previous pitch result, with strike as lowest, hit into play-unknown higher, and ball the highest. The count and count category (ahead, neutral, behind) was also encoded along a sliding scale, from most favorable to the pitcher at the low end of the spectrum and least favorable at the high end, and neutral count situations in between. It is difficult to determine exactly what an appropriate scale would be for these values as part of the input vector in machine learning models, however, compared to random label or ordinal encoding, we felt that mapping according to some type of polar spectrum from good to bad outcomes/situation was a superior choice.</p><p>For our multiclass classification models, we decided to try and test a couple different encoding strategies for the categorical variables to see how that choice would affect model accuracy. In addition to the custom ordinal encoding, we also used one-hot encoding, as well as one-hot encoding plus Principal Component Analysis, with 99% of variance explained as the threshold.</p><h4>Numeric Features Scaling</h4><p>In order to best account for potential outliers in the numeric data to have an oversized affect on the machine learning models, we chose Robust Scaler as our scaling method for all of the numeric features (the batter scouting report features, pitcher tendencies and percentages, etc).</p><h4>Train Test Split</h4><p>For each pitcher, we split the data into an 85% / 15% train-test split. The split was calculated based on date, so the 85% test set was comprised of the first 85% of pitches thrown, and the test set was the most recent 15% of pitches thrown. This method ensures that no leakage of future unknown data can be used in the training of the model.</p><h4>Model Selection</h4><p>For the binary classification models, we trained several different types of models from the sklearn library, including Random Forests, Gradient Boosted Tree Classifiers, Support Vector Machines, Linear SVC, Linear Discriminant Analysis models, and a Stochastic Gradient descent Classifier. For multiclass classification models, we used all of those, but substituted XGBoost instead of sklearn for gradient boosted trees, and also added in a Logistic Regression Classifier as well as a K-Nearest Neighbors classifier.</p><h4>Hyperparameter Optimization</h4><p>For each model, we performed either a grid search or a randomized search across a range of various hyperparameters, including different regularization strategies to prevent overfitting of the models to the training set, performing a minimum of three-fold cross-validation for each. We stored the results of that search in a pandas dataframe, and sorted by rank of the validation accuracy score. Depending on the processing power required and how long that model type took to train, we then used the top 30–100 hyper-parameter tuned models for each type and tested the accuracy on the test set, and saved the top 10 most accurate models for each different model type, for further analysis and for later input into an ensemble Voting Classifier</p><h3>Model Interpretation and Feature Importances</h3><h4>Binary Models</h4><p>The aforementioned cross-validated gridsearch and randomized searches were performed on four different pitchers, chosen from among the starting pitchers with the largest sample of pitches in 2018–2019 data.The pitchers selected were Jacob deGrom, Trevor Bauer, Max Scherzer, and Zack Greinke.</p><p>For each pitcher, the majority class from the training set was used as the naive guess, baseline model accuracy to compare vs the accuracy of the different models. Specifically, whichever percentage of pitches for the target variable of fastball / not-fastball was higher in the training set, was selected as the naive guess for every pitch in the test set. The accuracy score for each of the models was then compared vs the accuracy of the naive guess. Among the four pitchers, after grouping all models together and taking the mean of the difference in model accuracy vs naive guess, Jacob deGrom showed the highest percentage increase in accuracy, at just under 15% better than naive guess. The model accuracy for Max Scherzer was far less successful, with an average difference of about 3% better than naive guess.</p><p>When grouping by pitcher and comparing across the types of models used, Random Forests had the highest accuracy relative to baseline naive guess, coming in at around 12% higher. Slightly under Random forests, gradient boosted trees, LDA models, and Linear Support Vector Machines averaged about 9–10% above naive guess. Stochastic Gradient Descent Classifier and sklearn SVC performed much worse, averaging around 6% above naive guess.</p><p>We realize that this analysis of just four pitchers is unlikely to be conclusive or statistically significant, in the time constraints we faced for the duration of this project, we felt it was likely demonstrative enough of some of the differences among model types for these selected pitchers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33f906cbbdee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing with Python]]></title>
            <link>https://medium.com/analytics-vidhya/natural-language-processing-with-python-cb3f83d5a393?source=rss-d65a2bb7f56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb3f83d5a393</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[spacy]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Matt Kirby]]></dc:creator>
            <pubDate>Wed, 21 Aug 2019 04:11:45 GMT</pubDate>
            <atom:updated>2020-08-20T19:36:50.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pafJWI7KZZQEMVPKXrm-Pw.jpeg" /><figcaption>The Library of Congress, Washington D.C</figcaption></figure><h4>Part 1: Tokens</h4><p>Natural Language Processing (NLP) is a ubiquitous application of modern machine learning techniques. You’d be hard pressed to find a professional data science team not using NLP in one form or another. It is for this reason I have set out to produce a gentle introduction to the subject, both its concepts and application.</p><p>This post covers some basic methods and tools for a barebones beginner. If you are a more advanced practitioner you might want to move on to <em>Part 2: Vector Representations</em>, or <em>Part 3: Pipelines and Topic Modeling</em> of this series.</p><p>Like any area of study, NLP has its own jargon, inherited from not only from the fields of machine learning and data analysis, but linguistics as well. This mashup of technical terms can be intimidating at first, but I will do my best to keep the technobabble to a minimum.</p><p>I’m assuming at least a basic understanding of python from the reader, and some experience with machine learning would be helpful, though not necessary. As always, I’m providing copious links to documentation in order to help explain areas in which my techniques or explanations are short on detail.</p><h4><strong>1. Tokenization</strong></h4><p>A token is a sequence of characters in a document that are useful for an analytical purpose. Often, but not always individual words. A document in an NLP context simply means a collection of text, this could be a tweet, a book, or anything in between.</p><p>Attributes of good tokens</p><ul><li>Tokens should always be stored in an iterable data structure (list, generator, etc.) to allow for easy future analysis</li><li>Tokens should all be the same case to reduce complexity</li><li>Tokens should be free of non-alphanumeric characters</li></ul><p><em>Example 1: Tokenization</em></p><pre>import re</pre><pre>def tokenize(text):<br>    text = text.lower()<br>    text = re.sub(r&#39;[^a-zA-Z ^0-9]&#39;, &#39;&#39;, str(text))<br>    return text.split()</pre><pre># We are using the text from above as our sample_text<br>tokens = tokenize(sample_text) <br>tokens[:10]<br>____________________________________________________________________</pre><pre>[&#39;a&#39;,  &#39;token&#39;,  &#39;is&#39;,  &#39;a&#39;,  &#39;sequence&#39;,  &#39;of&#39;,  &#39;characters&#39;,  &#39;in&#39;,  &#39;a&#39;,  &#39;document&#39;]</pre><h4><strong>2. Word Count</strong></h4><p>Once we have tokens we can perform some basic analysis on our document. Let’s start with getting a simple word count using a python <a href="https://docs.python.org/2/library/collections.html#collections.Counter">Counter</a> object.</p><p><em>Example 2: Word Count</em></p><pre>from collections import Counter</pre><pre>def word_counter(tokens):<br>    word_counts = Counter()<br>    word_counts.update(tokens)<br>    return word_counts</pre><pre>word_count = word_counter(tokens)</pre><pre>word_count.most_common(5)<br>____________________________________________________________________</pre><pre>[(&#39;a&#39;, 7), (&#39;of&#39;, 4), (&#39;in&#39;, 4), (&#39;be&#39;, 4), (&#39;an&#39;, 3)]</pre><p>We can visualize these word counts with a simple bar chart.</p><p><em>Example 3: Word Count Visualization</em></p><pre>import matplotlib.pyplot as plt</pre><pre>x = list(word_count.keys())[:10]<br>y = list(word_count.values())[:10]</pre><pre>plt.bar(x, y)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOwaBCWFo3sM_4YVh07Czw.png" /></figure><h4><strong>3. Document Makeup</strong></h4><p>Word counts can be useful on occasion, but often, more advanced analytics are needed to answer business questions, especially when our data consists of more than a single document. We can set ourselves up for success by creating a Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html">DataFrame</a> containing features representing the number of documents a token appears in, a count of that tokens appearances, its rank in relation to other tokens, tokens percentage of total document makeup, a running sum of these percentages, and the percentage of documents a token appears in.</p><p><em>Example 4: Document Makeup DataFrame</em></p><pre>import pandas as pd</pre><pre>def count(docs):<br>  <br>    word_counts = Counter()<br>    appears_in = Counter()<br>    total_docs = len(docs)<br>    <br>    for doc in docs:<br>        word_counts.update(doc)<br>        appears_in.update(set(doc))<br>        <br>    temp = list(zip(word_counts.keys(), word_counts.values()))<br>    <br>    # Word and count columns<br>    wc = pd.DataFrame(temp, columns = [&#39;word&#39;, &#39;count&#39;])<br>    <br>    # Rank column<br>    wc[&#39;rank&#39;] = wc[&#39;count&#39;].rank(method=&#39;first&#39;, ascending=False)<br>    <br>    # Percent Total column<br>    total = wc[&#39;count&#39;].sum()<br>    wc[&#39;pct_total&#39;] = wc[&#39;count&#39;].apply(lambda x: x / total)<br>    <br>    # Cumulative percent total column<br>    wc = wc.sort_values(by=&#39;rank&#39;)<br>    wc[&#39;cul_pct_total&#39;] = wc[&#39;pct_total&#39;].cumsum()<br>    <br>    # Appears in column<br>    t2 = list(zip(appears_in.keys(), appears_in.values()))<br>    ac = pd.DataFrame(t2, columns=[&#39;word&#39;, &#39;appears_in&#39;])<br>    wc = ac.merge(wc, on=&#39;word&#39;)<br>    <br>    # Appears in percent column<br>    wc[&#39;appears_in_pct&#39;] = wc[&#39;appears_in&#39;].apply(lambda x: x / total_docs)<br>    <br>    <br>    return wc.sort_values(by=&#39;rank&#39;)<br>  <br>wc = count([tokens])</pre><pre>wc.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMD0SX8xiWNQp39dNpVYJA.png" /></figure><p>Using this dataframe we can generate a cumulative distribution plot showing how a token’s rank relates to the cumulative makeup of our documents.</p><p><em>Example 5: Cumulative Distribution Plot</em></p><pre>import seaborn as sns</pre><pre>sns.lineplot(x = &#39;rank&#39;, y = &#39;cul_pct_total&#39;, data = wc)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hf0225wzXdkdxyADVASbsA.png" /></figure><p>From the cumulative distribution plot we can see that the 13 most common words make up about 45% of the document after that the distribution looks pretty uniformly linear. We can see the relative percentage of document makeup of these top 13 tokens in a tree plot.</p><p><em>Example 6: Tree Plot</em></p><pre>import squarify</pre><pre>wc_top13 = wc[wc[&#39;rank&#39;] &lt;= 13]</pre><pre>squarify.plot(sizes=wc_top13[&#39;pct_total&#39;], label=wc_top13[&#39;word&#39;], alpha=.8 )</pre><pre>plt.axis(&#39;off&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*UhVHVIPUTti3CDpPFmwukw.png" /></figure><p>These examples demonstrate some of the initial principles required for understanding the deeper world of NLP. Tokenization, word counts, and document makeup analysis are foundational concepts, and while we could write an entire NLP library from scratch, that often not the most efficient way to solve problems. There is a zoo of open source NLP libraries we could use to enhance our powers, but one in particular stands out as the leader.</p><h4><strong>4. Introducing SpaCy</strong></h4><p><a href="https://spacy.io/">SpaCy</a> is “spaCy is a free, open-source library for advanced Natural Language Processing (NLP) in Python”, developed by<a href="https://explosion.ai/"> explosion_ai</a>. Spacy’s datamodel for documents is unique among NLP libraries. Instead of storing the documents components repeatedly in various data structures, Spacy indexes components and simply stores the lookup information. This is often why Spacy is considered to be more fit for production grade projects than other libraries like NLTK.</p><p>Spacy has a wide array of tools that can be utilized for NLP purposes.</p><p><em>Example 7: Tokens with SpaCy</em></p><pre>import spacy</pre><pre>nlp = spacy.load(&quot;en_core_web_lg&quot;)</pre><pre>def spacy_tokenize(text):<br>    doc = nlp.tokenizer(text)<br>    return [token.text for token in doc]</pre><pre>spacy_tokens = spacy_tokenize(sample_text)</pre><pre>spacy_tokens[:10]<br>____________________________________________________________________</pre><pre>[&#39;a&#39;,  &#39;token&#39;,  &#39;is&#39;,  &#39;a&#39;,  &#39;sequence&#39;,  &#39;of&#39;,  &#39;characters&#39;,  &#39;in&#39;,  &#39;a&#39;,  &#39;document&#39;]</pre><h4>5. Stopwords</h4><p>Words such as “I”, “and”, “of”, etc. have almost no semantic meaning to us. We call these useless words “stopwords,” because we should ‘stop’ ourselves from including them in our analysis.</p><p>Most NLP libraries have built in lists of stop words that common english words: conjunctions, articles, adverbs, pronouns, and common verbs. The best practice, however, is to extend/customize these standard english stopwords for your problem’s domain.</p><p><em>Example 8: Stopword Removal</em></p><pre>spacy_stopwords = spacy.lang.en.stop_words.STOP_WORDS</pre><pre>def remove_stopwords(tokens):<br>    cleaned_tokens = []<br>    <br>    for token in tokens:<br>        if token not in spacy_stopwords:<br>            cleaned_tokens.append(token)<br>    <br>    return cleaned_tokens</pre><pre>cleaned_tokens = remove_stopwords(spacy_tokens)</pre><pre>cleaned_tokens[:10]<br>____________________________________________________________________[&#39;A&#39;, &#39;token&#39;, &#39;sequence&#39;, &#39;characters&#39;, &#39;document&#39;, &#39;useful&#39;, &#39;analytical&#39;, &#39;purpose&#39;, &#39;.&#39;, &#39;Often&#39;]</pre><h4>6. Lemmas</h4><p>Lemmatization looks up the lemma of the word or the root word. A <a href="https://en.wikipedia.org/wiki/Lemma_(morphology)">lemma</a>, put simply is the version of a word one would find in a dictionary. For example: run, runs, running, and ran are all forms of the same lexeme with run as the lemma.</p><p><em>Example 9: Lemmatization</em></p><pre>def spacy_lemmatize(text):<br>    doc = nlp.tokenizer(text)<br>    return [token.lemma_ for token in doc]</pre><pre>spacy_lemmas = spacy_lemmatize(sample_text)</pre><pre>spacy_lemmas[:10]<br>____________________________________________________________________<br>[&#39;A&#39;, &#39;token&#39;, &#39;be&#39;, &#39;a&#39;, &#39;sequence&#39;, &#39;of&#39;, &#39;character&#39;, &#39;in&#39;, &#39;a&#39;, &#39;document&#39;]</pre><h4>Final Words</h4><p>These are just some of the basic methods and tools used in NLP. Tokens, document makeup, stop words, and lemms will all play a part in the wars to come, but are rather elementary on their own. My next post <em>Natural Language Processing with Python Part 2: Vector Representations</em> will dive deeper into NLP.</p><p>Big shoutouts to Lambda School and Jon-Cody Sokoll for compiling a curriculum that includes material like this and presenting it in such an approachable way.</p><p>Thanks for reading!</p><p>Find me on T<a href="https://twitter.com/matt42kirby">witter</a>, <a href="https://github.com/mkirby1995">GitHub</a>, and <a href="https://www.linkedin.com/in/mathew-kirby-082062ba/">LinkedIn</a></p><p>P.S. Here is the link to the <a href="https://github.com/mkirby1995/Natural-Language-Processing-with-Pyhton/blob/master/Part%201%20Tokens.ipynb">Notebook</a> I used for this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SL9Q7xTdU57EjOMBGjdv3A.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb3f83d5a393" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/natural-language-processing-with-python-cb3f83d5a393">Natural Language Processing with Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predictive Modeling for Tanzanian Water Pumps]]></title>
            <link>https://medium.com/analytics-vidhya/predictive-modeling-for-tanzanian-water-pumps-701bcc7760b2?source=rss-d65a2bb7f56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/701bcc7760b2</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle-competition]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Matt Kirby]]></dc:creator>
            <pubDate>Tue, 02 Jul 2019 19:28:11 GMT</pubDate>
            <atom:updated>2019-07-10T04:25:45.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13eTNzkTNtrL23ksafPwqg.jpeg" /><figcaption>Tanzania is home to the Serengeti plains. <a href="https://www.harpersbazaar.com/culture/travel-dining/a17259/how-to-plan-your-first-safari/">image credit</a></figcaption></figure><h4>A Kaggle Competition Walkthrough</h4><p>This post will serve as a textual and visual exposition of my predictive modeling process from initial exploration to hyperparameter tuning. We will explore a dataset infested with missing records and duplicate information, and then will attempt to build an accurate model to predict whether a given water pump is functioning, in need of repairs, or non-functional.</p><h4>Phase 1: Import Data and Familiarize</h4><p>Most data for Kaggle competitions can be found in the form of a .csv file linked in the competition information. Pandas provides an easy way to import a .csv file as a Pandas DataFrame object; <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html">pd.read_csv()</a>.</p><p>I usually find it helpful to examine a dataset’s individual qualities before diving head first into cleaning, wrangling, and feature engineering. Not every dataset is the same and different data will require different plans of attack. Pandas provides us .info() which prints a DataFrame&#39;s shape (59,400 instances, and 43 features), feature names, feature types, a count of non-null values for each feature, and the DataFrame&#39;s memory usage (19.9MB); it&#39;s a real workhorse.</p><pre>df.info()<br>____________________________________________________________________&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt; <br>Int64Index: 59400 entries, 0 to 59399<br>Data columns (total 43 columns):</pre><pre>key_0                    59400 non-null int64 <br>id_x                     59400 non-null int64 <br>amount_tsh               59400 non-null float64 <br>date_recorded            59400 non-null object <br>funder                   55765 non-null object <br>gps_height               59400 non-null int64 <br>installer                55745 non-null object <br>longitude                59400 non-null float64 <br>latitude                 59400 non-null float64 <br>wpt_name                 59400 non-null object <br>num_private              59400 non-null int64 <br>basin                    59400 non-null object <br>subvillage               59029 non-null object <br>region                   59400 non-null object <br>region_code              59400 non-null int64 <br>district_code            59400 non-null int64 <br>lga                      59400 non-null object <br>ward                     59400 non-null object <br>population               59400 non-null int64 <br>public_meeting           56066 non-null object <br>recorded_by              59400 non-null object <br>scheme_management        55523 non-null object <br>scheme_name              31234 non-null object <br>permit                   56344 non-null object <br>construction_year        59400 non-null int64 <br>extraction_type          59400 non-null object <br>extraction_type_group    59400 non-null object <br>extraction_type_class    59400 non-null object <br>management               59400 non-null object <br>management_group         59400 non-null object <br>payment                  59400 non-null object <br>payment_type             59400 non-null object <br>water_quality            59400 non-null object <br>quality_group            59400 non-null object <br>quantity                 59400 non-null object <br>quantity_group           59400 non-null object <br>source                   59400 non-null object <br>source_type              59400 non-null object <br>source_class             59400 non-null object <br>waterpoint_type          59400 non-null object <br>waterpoint_type_group    59400 non-null object <br>id_y                     59400 non-null int64 <br>status_group             59400 non-null object </pre><pre>dtypes: float64(3), int64(9), object(31) <br>memory usage: 19.9+ MB</pre><p><strong>Labels</strong></p><p>There are three possible values:</p><ul><li>functional : the waterpoint is operational and there are no repairs needed</li><li>functional needs repair : the waterpoint is operational, but needs repairs</li><li>non functional : the waterpoint is not operational</li></ul><p><strong>Features</strong></p><p>Your goal is to predict the operating condition of a waterpoint for each record in the dataset.</p><ul><li>amount_tsh : Total static head (amount water available to waterpoint)</li><li>date_recorded : The date the row was entered</li><li>funder : Who funded the well</li><li>gps_height : Altitude of the well</li><li>installer : Organization that installed the well</li><li>longitude : GPS coordinate</li><li>latitude : GPS coordinate</li><li>wpt_name : Name of the waterpoint if there is one</li><li>num_private :Private use or not</li><li>basin : Geographic water basin</li><li>subvillage : Geographic location</li><li>region : Geographic location</li><li>region_code : Geographic location (coded)</li><li>district_code : Geographic location (coded)</li><li>lga : Geographic location</li><li>ward : Geographic location</li><li>population : Population around the well</li><li>public_meeting : True/False</li><li>recorded_by : Group entering this row of data</li><li>scheme_management : Who operates the waterpoint</li><li>scheme_name : Who operates the waterpoint</li><li>permit : If the waterpoint is permitted</li><li>construction_year : Year the waterpoint was constructed</li><li>extraction_type : The kind of extraction the waterpoint uses</li><li>extraction_type_group : The kind of extraction the waterpoint uses</li><li>extraction_type_class : The kind of extraction the waterpoint uses</li><li>management : How the waterpoint is managed</li><li>management_group : How the waterpoint is managed</li><li>payment : What the water costs</li><li>payment_type : What the water costs</li><li>water_quality : The quality of the water</li><li>quality_group : The quality of the water</li><li>quantity : The quantity of water</li><li>quantity_group : The quantity of water</li><li>source : The source of the water</li><li>source_type : The source of the water</li><li>source_class : The source of the water</li><li>waterpoint_type : The kind of waterpoint</li><li>waterpoint_type_group : The kind of waterpoint</li></ul><h4>Phase 2: Clean, Wrangle, and Engineer Features</h4><p>Finding a good place to start when attacking a dataset for the first time is not a trivial act, as there are usually multiple obvious places to begin cleaning, feature engineering, and exploratory analysis. I’ll offer some reassuring words for the reader here: pick a place to start, trust your intuition and just start coding. If you hit a brick wall don’t be afraid to retreat, regroup, and attack elsewhere. It — and — you will be fine. We will start with cleaning the construction_year feature with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html">df.replace()</a>.</p><pre>features[&#39;construction_year&#39;].replace({0:1993})<br># 1993 is an arbitrarily chosen year</pre><p><strong>Feature Engineering</strong></p><p>With this cleaned construction year feature we can engineer a pump age and an average pop served per year feature.</p><pre>features[&#39;age&#39;] = features[&#39;date_recorded&#39;] - features[&#39;construction_year&#39;]</pre><pre>features[&#39;pop/year&#39;] = features[&#39;population&#39;] / features[&#39;age&#39;]</pre><p>We can take our feature engineering even further by creating a feature that represents the theoretical amount of water each person served by a wellhead has access to.</p><pre>features[&#39;water/person&#39;] = features[&#39;amount_tsh&#39;] / features[&#39;population&#39;]</pre><p><strong>Encoding</strong></p><p>Encoding is useful to quantify categorical or otherwise qualitative data. There is an ever expanding library of <a href="https://contrib.scikit-learn.org/categorical-encoding/">encoding methods</a> focused on different types of data. We will be using one hot encoding for low cardinality features and ordinal encoding for our high cardinality features. We also use null value <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html">imputing</a> and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html">standard scaling</a> on our data in order to clean it before we feed it to our model.</p><p><strong>Exploratory Visualization</strong></p><p>A smart way to explore data is to create visualizations. This is a very freeform process, and again each dataset is different, so there is no one size fits all strategy. Due to this part being very code intensive, I will just present the visualizations, However, if you are interested in the code, there is a link to a colab notebook at the end of this post.</p><p>Since the water pumps in our dataset are stationary devices it could help to visualize their geographic locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsJCo6TjEgsSILnZlCwfmQ.jpeg" /></figure><p>There seems to be no clear relationship between the latitude and longitude of a pump and its status. However there are many very distinct clusters of pumps which appear to have the same status.</p><h4>Phase 3: Build a Baseline Model and an Overfitting Model</h4><p>We will build a baseline model to set the lower bar of our prediction capabilities. I particularly like using a majority class prediction as a baseline because it is easy to wrap my head around.</p><pre>X_matrix, y_vector = df.drop(columns=&#39;status_group&#39;), df[&#39;status_group&#39;]</pre><pre>majority_class = y_vector.mode()</pre><pre>y_vector.value_counts(normalize=True)</pre><pre>____________________________________________________________________</pre><pre>functional                 0.543081 <br>non functional             0.384242 <br>functional needs repair    0.072677 <br>Name: status_group, dtype: float64</pre><p>Since functional is the status of 54% of our instances we expect our majority class prediction to be ~54% accurate.</p><pre>from sklearn.metrics import accuracy_score</pre><pre>majority_prediction = [majority_class] * len(y_vector)</pre><pre>accuracy_score(y_vector, majority_prediction)</pre><pre>____________________________________________________________________</pre><pre>0.543080808080808</pre><p>Awesome, we now have a bottom line for our predictions going forward.</p><p>Let&#39;s create a model that overfits our data to ensure we can make worthwhile predictions. My usual choice for this task is a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">decision tree</a>.</p><pre>from sklearn.tree import DecisionTreeClassifier</pre><pre>decision_tree = DecisionTreeClassifier(max_depth=50)</pre><pre>decision_tree.fit(X_matrix, y_vector)</pre><pre>____________________________________________________________________</pre><pre>DecisionTreeClassifier<br>(class_weight=None, criterion=&#39;gini&#39;,     max_depth=50,max_features=None, max_leaf_nodes=None,                        min_impurity_decrease=0.0, min_impurity_split=None,                        min_samples_leaf=1, min_samples_split=2,                        min_weight_fraction_leaf=0.0, presort=False,                        random_state=None, splitter=&#39;best&#39;)</pre><p>We can see how our overfitted model performs by using a confusion matrix.</p><pre>from sklearn.metrics import classification_report, confusion_matrix<br>import seaborn as sns</pre><pre>def con_matrix_analysis(model):<br>  x = model.predict(X_matrix)<br>  <br>  print(classification_report(y_vector, x,<br>        target_names=[&#39;Functional&#39;, &#39;Needs Repair&#39;, &#39;Not-Functional&#39;]))</pre><pre>  con_matrix = pd.DataFrame(confusion_matrix(y_vector, x), <br>             columns=[&#39;Predicted Functional&#39;, &#39;Predicted Needs  Repair&#39;, &#39;Predicted Not-Functional&#39;], <br>             index=[&#39;Actual Functional&#39;, &#39;Actual Needs Repair&#39;, &#39;Actual Not-Functional&#39;])<br>                            <br>  sns.heatmap(data=con_matrix, cmap=&#39;cool&#39;)<br>  plt.show();<br>  return con_matrix</pre><pre>con_matrix_analysis(decision_tree)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sCF44SC8wwuZoGn00W2ryQ.png" /></figure><h4>Phase 4: Build an Accurate Model and Tune its Hyperparameters</h4><p>We will use a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">random forest classifier</a> for our final model. A random forest is exactly what it sounds like, a forest of decision trees. We will also use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html">randomized-search cross-validation</a> to select the best model form an assortment of hyperparameter settings.</p><p>Based on our cross-validation the random forest classifier with the most accurate results is a model with 92 estimators and a max depth of 26. When we pass the selected model to our confusion matrix analysis function we achieve the results below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_x8iHgy6QqGnuqmVgwCng.png" /></figure><h4>Phase 5: Predict and Export</h4><p>The final phase in our process is to use our model to predict the status of pumps contained in our X_test dataframe, convert that dataframe to a .csv file, and export the file from our environment. Pandas again comes to the rescue with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html">pd.to_csv()</a> for converting dataframes to .csv files.</p><pre>prediction = model.predict(X_test)</pre><pre>submission[&#39;status_group&#39;] = prediction</pre><pre>submission.to_csv(&#39;submission_1.csv&#39;, index=False)</pre><pre>from google.colab import files<br>files.download(&#39;submission_1.csv&#39;)</pre><p>I hope I have presented an easy to follow and informative introduction to Kaggle competition, machine learning, and data science tasks for the reader. For those interested, the Colab notebook I used for this project is linked below.</p><p>Follow me on T<a href="https://twitter.com/matt42kirby">witter</a>, <a href="https://github.com/mkirby1995">GitHub</a>, and <a href="https://www.linkedin.com/in/mathew-kirby-082062ba/">LinkedIn</a></p><p>Here is the link to the <a href="https://colab.research.google.com/drive/1DaMeKnZzhSYdDY_Wden0gLt-vqwJhhcH">Colab Notebook</a> I used for this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W87v99m7Xf_L7DST0lRb6A.jpeg" /><figcaption><a href="https://www.serengeti.com/">image credit</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=701bcc7760b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/predictive-modeling-for-tanzanian-water-pumps-701bcc7760b2">Predictive Modeling for Tanzanian Water Pumps</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[Applying the Universal Machine Learning Workflow to the UCI Mushroom Dataset]]></title>
            <link>https://medium.com/data-science/applying-the-universal-machine-learning-workflow-to-the-uci-mushroom-dataset-1939442d44e7?source=rss-d65a2bb7f56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1939442d44e7</guid>
            <category><![CDATA[random-forest-classifiers]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[crossvalidation]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Matt Kirby]]></dc:creator>
            <pubDate>Fri, 17 May 2019 22:45:11 GMT</pubDate>
            <atom:updated>2021-06-11T16:04:01.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MYwjpwXOlwC2j3Sy" /><figcaption>Photo by <a href="https://unsplash.com/@phienix_han?utm_source=medium&amp;utm_medium=referral">Phoenix Han</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Universal Machine Learning Workflow</h3><h4>Applying François Chollet’s Universal Machine Learning Workflow to the UCI Mushroom dataset</h4><p>W e will be using the <a href="https://archive.ics.uci.edu/ml/datasets/mushroom">Mushroom Dataset</a> from <a href="https://archive.ics.uci.edu/ml/index.php">UCI’s Machine Learning Repository</a> to perform our demonstration. This work is meant for a reader who has at least a basic understanding of Python fundamentals and some experience with machine learning. That being said, I will provide copious links to supporting sources for the uninitiated so that anyone can make use of the information presented.</p><p>Before we get started, I’d like to give thanks to my fellow Lambdonian <a href="https://medium.com/u/8ed409584365">Ned H</a> for all his help on this post.</p><h4>The Universal Machine Learning Workflow</h4><ol><li>Define the problem and assemble a dataset</li><li>Choose a measure of success</li><li>Decide on an evaluation protocol</li><li>Prepare the data</li><li>Develop a model that does better than a baseline</li><li>Develop a model that overfits</li><li>Regularize the model and tune its hyperparameters</li></ol><h3>1. Define the problem and assemble a dataset</h3><p>Stated concisely our problem is the binary classification of a mushroom as edible or poisonous. We are given a dataset with 23 features including the class (edible or poisonous) of the mushroom.</p><p>From the features listed in the data information file we can create a list of column names for our dataset.</p><pre>column_names = [&#39;class&#39;,<br>                &#39;cap-shape&#39;,<br>                &#39;cap-surface&#39;,<br>                &#39;cap-color&#39;,<br>                &#39;bruises?&#39;,<br>                &#39;odor&#39;,<br>                &#39;gill-attachment&#39;,<br>                &#39;gill-spacing&#39;,<br>                &#39;gill-size&#39;,<br>                &#39;gill-color&#39;,<br>                &#39;stalk-shape&#39;,<br>                &#39;stalk-root&#39;,<br>                &#39;stalk-surface-above-ring&#39;,<br>                &#39;stalk-surface-below-ring&#39;,<br>                &#39;stalk-color-above-ring&#39;,<br>                &#39;stalk-color-below-ring&#39;,<br>                &#39;veil-type&#39;,<br>                &#39;veil-color&#39;,<br>                &#39;ring-number&#39;,<br>                &#39;ring-type&#39;,<br>                &#39;spore-print-color&#39;,<br>                &#39;population&#39;,<br>                &#39;habitat&#39;]</pre><p>Lets import our dataset and create a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html">Pandas DataFrame</a> from the .data file using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html">pd.read_csv()</a></p><pre>import pandas as pd</pre><pre>url = &#39;<a href="https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data&#39;">https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data&#39;</a></pre><pre>mushrooms = pd.read_csv(url, header=None, names=column_names)</pre><h3>2. Choose a measure of success</h3><p>Given the nature of our problem; classifying whether or not a mushroom is poisonous or not, we will be using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html">precision</a> as our measure of success. Precision is the ability of the classifier not to label as edible mushrooms which are poisonous. We would much rather people discard edible mushrooms that our model classified as poisonous than eat poisonous mushrooms our classifier labeled as edible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*aqXLekm1AEyueWOkgo1qig.png" /></figure><pre>from sklearn.metrics import precision_score</pre><h3>3. Decide on an evaluation protocol</h3><p>We will be using 10-fold <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_validate.html">cross validation </a>to evaluate our model. While a simple holdout validation set would probably suffice, I am skeptical of its viability given our ~8,000 samples.</p><pre>from sklearn.model_selection import train_test_split, cross_validate</pre><p>First lets split our data into a feature matrix (X), and a target vector (y). We will use <a href="http://contrib.scikit-learn.org/categorical-encoding/onehot.html">OneHotEncoder</a> to encode our categorical variables.</p><pre>import category_encoders as ce</pre><pre>#Drop target feature<br>X = mushrooms.drop(columns=&#39;class&#39;) </pre><pre>#Encode categorical features<br>X = ce.OneHotEncoder(use_cat_names=True).fit_transform(X)<br> <br>y = mushrooms[&#39;class&#39;].replace({&#39;p&#39;:0, &#39;e&#39;:1})</pre><pre>print(&#39;Feature matrix size:&#39;,X.shape)<br>print(&#39;Target vector size:&#39;,len(y))</pre><pre>____________________________________________________________________</pre><pre>Feature matrix size: (8124, 117) Target vector size: 8124</pre><p>Next we will split our data into a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html">training set and a test set</a>.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=.2, stratify=y)</pre><pre>print(&#39;Training feature matrix size:&#39;,X_train.shape)<br>print(&#39;Training target vector size:&#39;,y_train.shape)<br>print(&#39;Test feature matrix size:&#39;,X_test.shape)<br>print(&#39;Test target vector size:&#39;,y_test.shape)</pre><pre>____________________________________________________________________</pre><pre>Training feature matrix size: (6499, 117) <br>Training target vector size: (6499,) <br>Test feature matrix size: (1625, 117) <br>Test target vector size: (1625,)</pre><h3>4. Prepare the data</h3><p>Were almost ready to begin training models, but first we should explore our data, familiarize ourselves with its characteristics, and format it so that it can be fed into our model.</p><p>We could use .dtypes(), .columns, and .shape to examine our dataset, but Pandas provides a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.info.html">.info</a> function that will allow us to view all this information in one place.</p><pre>print(mushrooms.info())</pre><pre>____________________________________________________________________</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt; <br>RangeIndex: 8124 entries, 0 to 8123<br>Data columns (total 23 columns):<br>class                       8124 non-null object<br>cap-shape                   8124 non-null object <br>cap-surface                 8124 non-null object <br>cap-color                   8124 non-null object <br>bruises?                    8124 non-null object <br>odor                        8124 non-null object <br>gill-attachment             8124 non-null object <br>gill-spacing                8124 non-null object <br>gill-size                   8124 non-null object <br>gill-color                  8124 non-null object <br>stalk-shape                 8124 non-null object <br>stalk-root                  8124 non-null object <br>stalk-surface-above-ring    8124 non-null object <br>stalk-surface-below-ring    8124 non-null object <br>stalk-color-above-ring      8124 non-null object <br>stalk-color-below-ring      8124 non-null object <br>veil-type                   8124 non-null object <br>veil-color                  8124 non-null object <br>ring-number                 8124 non-null object <br>ring-type                   8124 non-null object <br>spore-print-color           8124 non-null object <br>population                  8124 non-null object <br>habitat                     8124 non-null object <br>dtypes: object(23) memory usage: 1.4+ MB None</pre><p>Another useful step is to check is the number of null values and where they are in the DataFrame</p><pre>print(mushrooms.isna().sum())</pre><pre>____________________________________________________________________</pre><pre>class                       0 <br>cap-shape                   0 <br>cap-surface                 0 <br>cap-color                   0 <br>bruises?                    0 <br>odor                        0 <br>gill-attachment             0 <br>gill-spacing                0 <br>gill-size                   0 <br>gill-color                  0 <br>stalk-shape                 0 <br>stalk-root                  0 <br>stalk-surface-above-ring    0 <br>stalk-surface-below-ring    0 <br>stalk-color-above-ring      0 <br>stalk-color-below-ring      0 <br>veil-type                   0 <br>veil-color                  0 <br>ring-number                 0 <br>ring-type                   0 <br>spore-print-color           0 <br>population                  0 <br>habitat                     0 <br>dtype: int64</pre><p>None… that seems a bit too good to be true.</p><p>Since we were studious and read the <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.names">dataset information file</a>. We’re aware that all missing values are marked with a question mark. Once this is clear we can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html">df.replace()</a> to convert the ? to NaNs.</p><pre>import numpy as np<br>mushrooms = mushrooms.replace({&#39;?&#39;:np.NaN})<br>print(mushrooms.isna().sum())<br>____________________________________________________________________</pre><pre>class                       0 <br>cap-shape                   0 <br>cap-surface                 0 <br>cap-color                   0 <br>bruises?                    0 <br>odor                        0 <br>gill-attachment             0 <br>gill-spacing                0 <br>gill-size                   0 <br>gill-color                  0 <br>stalk-shape                 0 <br>stalk-root               2480<br>stalk-surface-above-ring    0 <br>stalk-surface-below-ring    0 <br>stalk-color-above-ring      0 <br>stalk-color-below-ring      0 <br>veil-type                   0 <br>veil-color                  0 <br>ring-number                 0 <br>ring-type                   0 <br>spore-print-color           0 <br>population                  0 <br>habitat                     0 <br>dtype: int64</pre><p>There we are, stalk_root has 2480 blank features, lets replace these with m for missing.</p><pre>mushrooms[&#39;stalk-root&#39;] = mushrooms[&#39;stalk-root&#39;].replace(np.NaN,&#39;m&#39;)</pre><pre>print(mushrooms[&#39;stalk-root&#39;].value_counts())</pre><pre>____________________________________________________________________</pre><pre>b    3776 <br>m    2480 <br>e    1120 <br>c     556 <br>r     192 <br>Name: stalk-root, dtype: int64</pre><h3>5. Develop a model that does better than a baseline</h3><p><strong>Baseline Model</strong></p><p>Using the most common label from our dataset we will create a baseline model that we hope to beat.</p><p>First let&#39;s look at how class is distributed using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html">df.value_counts()</a></p><pre>mushrooms[&#39;class&#39;].value_counts(normalize=True)</pre><pre>____________________________________________________________________</pre><pre>e    0.517971 <br>p    0.482029 <br>Name: class, dtype: float64</pre><p>We will use the mode of the class attribute to create our baseline prediction.</p><pre>majority_class = y_train.mode()[0]</pre><pre>baseline_predictions = [majority_class] * len(y_train)</pre><p>Lets see how <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html">accurate </a>our baseline model is.</p><pre>from sklearn.metrics import accuracy_score</pre><pre>majority_class_accuracy = accuracy_score(baseline_predictions,<br>                                         y_train)</pre><pre>print(majority_class_accuracy)</pre><pre>____________________________________________________________________<br></pre><pre>0.5179258347438067</pre><p>~52%… Which is what we would expect given the distribution of class in our initial dataset.</p><p><strong>Decision Tree</strong></p><p>We will attempt to fit a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">decision tree</a> to our training data and produce an accuracy score greater than 52%.</p><pre>from sklearn.tree import DecisionTreeClassifier<br>import graphviz<br>from sklearn.tree import export_graphviz</pre><pre>tree = DecisionTreeClassifier(max_depth=1)</pre><pre># Fit the model<br>tree.fit(X_train, y_train)</pre><pre># Visualize the tree<br>dot_data = export_graphviz(tree, out_file=None, feature_names=X_train.columns, class_names=[&#39;Poisonous&#39;, &#39;Edible&#39;], filled=True, impurity=False, proportion=True)</pre><pre>graphviz.Source(dot_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*Y1O8rS4AaSEmM3GTx-V4Mg.png" /></figure><p>Now that we have fitted the decision tree to our data we can analyze our model by looking at the prediction probability distribution for our classifier. In simple terms, prediction probability represents how sure the model is about its classification label.</p><p>In addition to prediction probability, we will look at the precision score of our decision tree. Sklearn provides us with a simple way to see many of the relevant scores for classification models with <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html">classification_report</a>.</p><p>We will also generate a confusion matrix using sklearn’s <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html">confusion_matrix</a>. A confusion matrix shows the number of true and false positives and negatives.</p><p>Since we will be using these tools again we will write a function to run our model analysis for us.</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from sklearn.metrics import classification_report, confusion_matrix</pre><pre>def model_analysis(model, train_X, train_y):<br>  model_probabilities = model.predict_proba(train_X)</pre><pre>  Model_Prediction_Probability = []</pre><pre>  for _ in range(len(train_X)):<br>      x = max(model_probabilities[_])<br>      Model_Prediction_Probability.append(x)</pre><pre>  plt.figure(figsize=(15,10)) <br> <br>  sns.distplot(Model_Prediction_Probability)</pre><pre>  plt.title(&#39;Best Model Prediction Probabilities&#39;)</pre><pre>  # Set x and y ticks<br>  plt.xticks(color=&#39;gray&#39;)</pre><pre>  #plt.xlim(.5,1)<br>  plt.yticks(color=&#39;gray&#39;)</pre><pre>  # Create axes object with plt. get current axes<br>  ax = plt.gca()</pre><pre>  # Set grid lines<br>  ax.grid(b=True, which=&#39;major&#39;, axis=&#39;y&#39;, color=&#39;black&#39;, alpha=.2)</pre><pre>  # Set facecolor<br>  ax.set_facecolor(&#39;white&#39;)</pre><pre>  # Remove box<br>  ax.spines[&#39;top&#39;].set_visible(False)<br>  ax.spines[&#39;right&#39;].set_visible(False)<br>  ax.spines[&#39;bottom&#39;].set_visible(False)<br>  ax.spines[&#39;left&#39;].set_visible(False)<br>  ax.tick_params(color=&#39;white&#39;)</pre><pre>  plt.show();<br>  <br>  model_predictions = model.predict(train_X)</pre><pre>  # Classification Report<br>  print(&#39;\n\n&#39;, classification_report(train_y, model_predictions, target_names=[&#39;0-Poisonous&#39;, &#39;1-Edible&#39;]))</pre><pre>  # Confusion Matrix<br>  con_matrix = pd.DataFrame(confusion_matrix(train_y, model_predictions), columns=[&#39;Predicted Poison&#39;, &#39;Predicted Edible&#39;], index=[&#39;Actual Poison&#39;, &#39;Actual Edible&#39;])<br>  <br>  plt.figure(figsize=(15,10))</pre><pre>  sns.heatmap(data=con_matrix, cmap=&#39;cool&#39;);</pre><pre>  plt.title(&#39;Model Confusion Matrix&#39;)<br>  plt.show();<br>  <br>  return con_matrix</pre><p>Now to apply this function to our decision tree.</p><pre>model_analysis(tree, X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBKg3nu-emiPfS0JvUesEA.jpeg" /></figure><p>We will store our predictions as a tree_predictions variable for use in interpreting our models accuracy.</p><pre>tree_predictions = tree.predict(X_train)</pre><pre>accuracy_score(y_train, tree_predictions)</pre><pre>____________________________________________________________________</pre><pre>0.8862901984920757</pre><p>88% accuracy isn’t bad, but let&#39;s move on to the next step in our workflow.</p><h3>6. Develop a model that overfits</h3><p>We will use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">RandomForestClassifier</a> for our overfitting model.</p><pre>from sklearn.ensemble import RandomForestClassifier</pre><pre>random_forest = RandomForestClassifier(n_estimators=100, max_depth=5)</pre><pre>cv = cross_validate(estimator = random_forest, X = X_train, y = y_train, scoring=&#39;accuracy&#39;, n_jobs=-1, cv=10, verbose=10, return_train_score=True)</pre><pre>____________________________________________________________________<br></pre><pre>[Parallel(n_jobs=-1)]: Using backend LokyBackend with 2 concurrent workers.</pre><pre>[Parallel(n_jobs=-1)]: Done   1 tasks      | elapsed:    2.6s [Parallel(n_jobs=-1)]: Done   4 tasks      | elapsed:    3.2s [Parallel(n_jobs=-1)]: Done  10 out of  10 | elapsed:    4.7s finished</pre><p>Now we can see our random forest’s accuracy score.</p><pre>random_forest.fit(X_test, y_test)<br>test_predictions = random_forest.predict(X_train)</pre><pre>accuracy_score(y_train, test_predictions)</pre><pre>____________________________________________________________________<br></pre><pre>0.9924603785197723</pre><p>99% accuracy looks overfitted to me.</p><p>We can use our model_analysis function from earlier to analyze our model.</p><pre>model_analysis(random_forest, X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9oJftYteUHNnHtOjd_DBA.jpeg" /></figure><h3>7. Regularize the model and tune its hyperparameters</h3><p>Now we will tune the hyperparameters of our RandomForestClassifier and attempt to walk the line between underfitting and overfitting. We can use sklearn’s <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html">RandmoizedSearchCV</a> to search the hyperparameters in our param_distributions dictionary.</p><pre>from sklearn.model_selection import RandomizedSearchCV</pre><pre>param_distributions = {<br>    &#39;max_depth&#39;:[1, 2, 3, 4, 5],<br>    &#39;n_estimators&#39;: [10, 25, 50, 100, 150, 200]}</pre><pre>search = RandomizedSearchCV(estimator = RandomForestClassifier(), param_distributions = param_distributions, n_iter=100, scoring=&#39;precision&#39;, n_jobs=-1, cv=10, verbose=10, return_train_score=True)<br> <br>search.fit(X_train, y_train)</pre><p>We can use search.best_estimator_ to see which model has the highest precision score.</p><pre>best_model = search.best_estimator_<br>best_model</pre><pre>____________________________________________________________________</pre><pre>RandomForestClassifier<br>(bootstrap=True, class_weight=None, criterion=&#39;gini&#39;, max_depth=5, max_features=&#39;auto&#39;, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2,             min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=None,             oob_score=False, random_state=None, verbose=0,             warm_start=False)</pre><p>From the model description we can see that a RandomForestClassifier with a max_depth of 5 and 10 estimators is our optimal model. Now we can run our analysis function.</p><pre>model_analysis(best_model, X_test, y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyuIBpvDBi1ok-N9WBILiA.jpeg" /></figure><p>3 false positives, not perfect, but pretty good.</p><h3>Conclusion</h3><p>To restate our workflow.</p><ol><li>Define the problem and assemble a dataset</li><li>Choose a measure of success</li><li>Decide on an evaluation protocol</li><li>Prepare the data</li><li>Develop a model that does better than a baseline</li><li>Develop a model that overfits</li><li>Regularize the model and tune its hyperparameters</li></ol><p>While Chollet describes this as THE universal machine learning workflow, there are infinite variations depending on the specific problem we are trying to solve. In general though, you will always start with defining your problem and collecting data, (whether that be from a premade dataset or doing your own data collection).</p><p>I hope this post has presented an informative walkthrough of Chollet’s universal machine learning workflow.</p><p>Thanks for reading!</p><p>Follow me on T<a href="https://twitter.com/matt42kirby">witter</a>, <a href="https://github.com/mkirby1995">GitHub</a>, and <a href="https://www.linkedin.com/in/mathew-kirby-082062ba/">LinkedIn</a></p><p>P.S. Here is the link to the <a href="https://colab.research.google.com/drive/1HztKbgWR-fZT3-Evc4t8ru16kOcueuH5">Colab Notebook</a> I used for this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1939442d44e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/applying-the-universal-machine-learning-workflow-to-the-uci-mushroom-dataset-1939442d44e7">Applying the Universal Machine Learning Workflow to the UCI Mushroom Dataset</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[Tracking Congressional Revenue and Spending: From Nixon to Trump]]></title>
            <link>https://medium.com/@matt42kirby/tracking-congressional-revenue-and-spending-from-nixon-to-trump-4586ca720bf7?source=rss-d65a2bb7f56b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4586ca720bf7</guid>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[congress]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[charts]]></category>
            <dc:creator><![CDATA[Matt Kirby]]></dc:creator>
            <pubDate>Fri, 19 Apr 2019 00:52:37 GMT</pubDate>
            <atom:updated>2019-04-19T00:52:37.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldZFUIMvw2Ch0cHIew6X1g.jpeg" /><figcaption>Image Credit: <a href="https://www.nssga.org/">National Stone and Gravel Association</a></figcaption></figure><p>Week after week we are bombarded with partisan information about how we should be taxed and how that money should be spent. This bombardment can make interpreting the facts and forming an independent opinion quite difficult for many people. Most often, this difficulty results from a lack of contextual information perpetuated by pundits arguing for or against this policy or that.</p><p>Congressional revenue and spending data is buried in a <a href="https://www.cbo.gov/">government website</a> deep within the labyrinth that is the internet. Besides the obscurity of the base data, there are clear and present political motives for news media and politicians to make their presentation of this information as polarizing as possible.</p><p>A nonpartisan presentation of relevant information could help people develop a more informed opinion when it comes to important, albeit maybe not the most exciting, issues like tax policy. This is what we will attempt.</p><p>In best interest of the reader I will present a roadmap for our journey. When talking about anything numerical, it’s easy to get lost in the details and forget where we’re going.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwuI52qA9zNKyo08-RUoVA.png" /></figure><p>Our travels will take us first to the source of congressional revenue: taxes. We will then sail to the twin islands of discretionary and mandatory spending, before finally ending our quest by bringing it all together and looking at the big picture.</p><p>P.S. If you’re interested, here are the links to the <a href="https://github.com/mkirby1995/Data-Storytelling-Project">GitHub Repo</a> and <a href="https://colab.research.google.com/drive/15LCQO8DOxjj-bBwXrZRjFfUCOwHKC55U">Colab Notebook</a> I used for this post.</p><p><strong>Congressional Revenue</strong></p><p>Congressional revenue is the money coming into the Congressional budget. More formally; Article 1 Section 8 of the United States Constitution gives the United States Congress the power to:</p><blockquote>“lay and collect Taxes, Duties, Imposts and Excises, to pay the Debts and provide for the common Defence and general Welfare of the United States”</blockquote><p>In 1913, the 16th Amendment extended congressional power of taxation to include individual income taxes. The congressional power of the purse is one of the legislature’s primary checks on executive power.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MY7htMrHUqrY2gYydbXCpw.png" /></figure><p>Here we can see the fall in tax revenue following the 9/11 attacks and the 2008 financial crisis manifested as two sharp declines in the middle right of the chart.</p><p>Another striking observation is how little a part customs duties and estate &amp; gift taxes play in this story. Each of these two revenue streams on average account for just over 1% of congressional revenue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wAPCctdK0S1luO9NQCChw.png" /></figure><p>We can see the relative changes in how different streams of congressional revenue contribute to the whole in both 1969 and 2018. The respective rise and fall of payroll and corporate income taxes signals a rise in mandatory spending, but we will get to that later.</p><p><strong>Discretionary Spending</strong></p><p>When we hear news casts of how the government will shut down if both sides of the aisle don’t agree on a budget, this is what they can’t agree on.</p><p>Discretionary spending is government spending implemented through an appropriations bill. This spending is an optional part of fiscal policy, in contrast to entitlement programs (for which funding is mandatory and determined by the number of eligible recipients).</p><p>U.S. discretionary spending is allocated for:</p><ul><li>Education,</li><li>Employment &amp; Social Services</li><li>Transportation</li><li>Veterans’ Benefits and Services,</li><li>Income Security</li><li>Health</li><li>Administration of Justice,</li><li>International Affairs</li><li>The Environment</li><li>Science, Space and Technology</li></ul><p>For our purposes discretionary spending is split into defense and nondefense spending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAplizHexNirwSexj-3b6A.png" /></figure><p>The far left of the chart shows the de-escalation of the conflict in Vietnam. We can see the Reagan era military buildup as a blue hill left of center. Discretionary spending has remained relatively stable with the exception of the two previously mentioned periods and the post 9/11 increase in spending.</p><p><strong>Mandatory Spending</strong></p><p>Congress legislates spending for mandatory programs outside of the annual appropriations bill process. Congress can only reduce the funding for programs by changing the authorization law itself. This requires a 60-vote majority in the Senate to pass.</p><p>Entitlement programs such as Social Security and Medicare make up the bulk of mandatory spending. Other mandatory programs include:</p><ul><li>Income Security Programs</li><li>Earned Income Tax Credit</li><li>Supplemental Nutrition Assistance Program (SNAP)</li><li>Temporary Assistance for Needy Families (TANF)</li><li>Unemployment Insurance</li><li>Federal Retirement programs for Federal and Civilian Military Retirees</li><li>Veterans programs</li><li>Agricultural subsidies</li><li>Salaries of Members of Congress and the President.</li></ul><p>Prior to the Great Depression, nearly all federal expenditures were discretionary. Mandatory spending grew following the passage of the Social Security Act in 1935, and when Congress amended the Social Security Act to create Medicare in 1965.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3iYOeXSvD9xu8dOwlVp4g.png" /></figure><p>During the recession in 2008 and 2009, mandatory spending increased by 31% due to federal financial interventions and the economic downturn. Much of the money went to the Troubled Asset Relief Program and aid to Government Sponsored Enterprises such as Fannie Mae and Freddie Mac.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsFIDd6JSHxEq2sb2dbb6A.png" /></figure><p>The number of beneficiaries of entitlement programs has grown as the average age of the population has risen. The Medicare Act of 1965 extended health benefits for most retirees and expanded mandatory spending. As life expectancy has increased, the portion of the population over 85 has also increased, which has created a rise in Social Security and Medicare spending. In 1969, Medicare &amp; Medicaid spending accounted for only 13% of mandatory spending. By 2018, that has ballooned to nearly 40%.</p><p><strong>The Big Picture</strong></p><p>The surge in Medicare &amp; Medicaid spending has created somewhat of a crisis in recent years especially as healthcare costs continue to climb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Emy5xb4egw4LaGj-4YNPAw.png" /></figure><p>Mandatory spending first outpaced discretionary spending in 1975. Today, mandatory spending, driven by increases in Medicare &amp; Medicaid costs, makes up almost 69% of all congressional spending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6QPyq9FgpVnpikRxrRxqg.png" /></figure><p>The increases in both spending classes, but especially mandatory spending, is driving congressional expenditures to worrying levels, and is far eclipsing congressional revenue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sr6KHyaFB8RaFbFr0ua-1w.png" /></figure><p>Here we can see how often Congress runs a budget deficit. The large block of red towards the end represents the extra mandatory spending caused by the 2008 Financial Crisis. Running a congressional budget deficit is no anomaly in itself, but at the scale and persistence we have seen in the preceding decade it can be an indicator of larger issues.</p><p><strong>Final Thoughts</strong></p><p>If Medicare &amp; Medicaid spending continues to increase at the rate it has for the past 50 years, Congress will be forced to either raise taxes or continue to increase the budget deficit. It’s easy for news media and others to place blame for the problem on this group or that, but my instinct tells me that the underlying issue is systemic. The infrastructure of how healthcare is produced and distributed in the US is broken. We will dive into why this is and ideas of how to fix it in a future post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*cdkwJH82PRdLEgBKp9LWNw.jpeg" /><figcaption><a href="https://www.deseretnews.com/article/865685328/10-political-cartoons-on-the-Republican-health-care-debacle.html">Source</a></figcaption></figure><p>I hope I have presented a non-partisan exposition of relevant congressional revenue &amp; spending data. A well-informed electorate is imperative when it comes to the health of our nation. Please keep striving to inform yourself about important issues.</p><p>Thanks for reading!</p><p>Follow me on T<a href="https://twitter.com/matt42kirby">witter</a>, <a href="https://github.com/mkirby1995">GitHub</a>, and <a href="https://www.linkedin.com/in/mathew-kirby-082062ba/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4586ca720bf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>