<?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 Walker Payne on Medium]]></title>
        <description><![CDATA[Stories by Walker Payne on Medium]]></description>
        <link>https://medium.com/@walker-payne?source=rss-c693b9460084------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1psUmyt9qH6fB8ZI3i-JDA.jpeg</url>
            <title>Stories by Walker Payne on Medium</title>
            <link>https://medium.com/@walker-payne?source=rss-c693b9460084------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:34:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@walker-payne/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[Alternative Data Sources And Informational Advantages Via Web Scraping And Machine Learning]]></title>
            <link>https://medium.com/codex/alternative-data-sources-and-informational-advantages-via-web-scraping-and-machine-learning-8da4ab8aecc3?source=rss-c693b9460084------2</link>
            <guid isPermaLink="false">https://medium.com/p/8da4ab8aecc3</guid>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[esport]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Walker Payne]]></dc:creator>
            <pubDate>Tue, 16 Nov 2021 01:29:21 GMT</pubDate>
            <atom:updated>2022-05-03T17:46:34.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Predicting Rocket League Match Outcome With Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*mSuiyzFfF_Y6WUdq" /><figcaption>Figure 0. Alternative Data (<a href="https://medium.com/earnest-research/alternative-data-what-is-it-how-can-it-help-consumer-brands-and-investors-14065997bcbd">source</a>)</figcaption></figure><p>I’ve always been fascinated by the concept of an “informational advantage”, specifically in the finance world. When conventional economic data taught in textbooks is the status quo, investors (mainly hedge funds) seek <a href="https://www.cnn.com/2019/07/10/investing/hedge-fund-drones-alternative-data/index.html">alternative data sources</a> to gain an edge over their competitors.</p><p>Examples of these alternative data sources are compelling and seemingly endless:</p><ul><li>Swiss investment firm <a href="https://internationalbanker.com/brokerage/how-satellite-imagery-is-helping-hedge-funds-outperform/">UBS Investment Research</a> uses satellite imagery to estimate occupancy rates of Walmart parking lots, extrapolating quarterly sales and thus gain useful investment insights. For example, consistently empty parking lots could signal poor foot traffic, indicating that a fund might want to short the stock.</li><li>Thinknum, an alternative data provider, uses <a href="https://www.cnn.com/2019/07/10/investing/hedge-fund-drones-alternative-data/index.html">web-scraping data</a> to analyze vehicle inventory at Carvana and CarMax. Funds can act on this data to predict upcoming earnings for these companies, or even to assess demand in the broader auto industry for vehicles by manufacturers of interest like Tesla or Ford.</li><li>Two Sigma, a quant hedge fund with $60 billion AUM, has a Macro <a href="https://en.wikipedia.org/wiki/Alpha_capture_system">Alpha Capture</a> Platform that pays investment professionals to submit trade ideas with a timeframe, rationale, and conviction level. This information is then (<em>presumably</em>) used in various machine learning models to either execute trades or provide insights to Two Sigma fund managers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*b-Fkv4DDoQm1_tbe.png" /><figcaption>Figure 1. eSports betting volume by game. <a href="https://www.legalsportsreport.com/esports-betting/">Source</a>.</figcaption></figure><p>With alternative data sources in mind, I decided I wanted to implement my own attempt at creating an informational advantage.</p><p>Sports betting is predicted to be a <a href="https://www.bloomberg.com/press-releases/2021-10-19/sports-betting-market-size-worth-140-26-billion-by-2028-grand-view-research-inc#:~:text=Read-,Sports%20Betting%20Market%20Size%20Worth%20%24140.26%20Billion,%3A%20Grand%20View%20Research%2C%20Inc.">140 billion dollar industry</a> by 2028 and happens to be ripe with exploitable, underutilized datasets. The umbrella of “sports betting” also includes eSports, which features games such as CS:GO, League of Legends, Dota 2, Starcraft, and others (Figure 1).</p><p>One game that’s not on this list but may well be in the future is Rocket League (RL). It’s my favorite game at the moment and can be explained quite easily — it’s basically soccer but with flying cars instead of people. If that sounds silly, well, it kind of is, but it’s a beautiful game — a simplistic concept combined with an incomprehensibly high skill ceiling. And with nearly <a href="https://afkgaming.com/esports/news/rocket-league-player-count-how-many-people-still-play-in-2021">100 million monthly active players</a>, it’s nothing to laugh at. It’s no stretch to think that RL will have some widely available forms of betting in the near future.</p><p>With this in mind, my goal began to crystalize: <strong>to exploit publicly available data in a unique way and attempt to predict Rocket League match outcome, creating an informational advantage for a future sports betting scenario.</strong></p><p>This exercise serves as a great analogy to the broader financial world and their utilization of alternative datasets. Is the data publicly available? Sure. Does the average retail investor have the knowledge, skillset, and capital available to scrape, aggregate, and process that data into actionable insights? Absolutely not. Fairness, it seems, is out of the question.</p><blockquote>The next three sections go into the technical details of scraping and exploring the dataset and machine learning model evaluations. Feel free to skip to the end for “lessons learned”.</blockquote><h3>Alternative Data Sources: Scraping the Web</h3><p>My idea was to gather data on RL 1v1 matches and the players involved in each. To make a predictive model, I needed input data:</p><ul><li>Player 1 and player 2 statistics — win rate, total number of wins, Match Making Rating (MMR), goal/shot ratio, etc. <em>(goal/shot ratio defined as the number of goals scored by a player divided by the number of shots they take, which is a proxy metric for accuracy. More on this later.)</em></li></ul><p>and output data:</p><ul><li>game outcome (win or loss, from the perspective of player 1).</li></ul><p>I would then use the input data to train a machine learning model, which would output the probability of a player winning or losing in a 1v1 match. If the accuracy of the model is high enough to warrant usefulness, it could be used in the future to inform betting on matches.</p><p>Having outlined what data I needed, I ended up scraping two separate websites. It would be super convenient if all of the above information was served up on a silver platter for me, but unfortunately I had to work for hard for <em>this </em>informational advantage. The two websites I scraped are described below:</p><ul><li><a href="https://ballchasing.com/">Ballchasing.com</a>, which allows users to upload replays of their own matches and automatically analyze them. From here I gathered match information and player names — <em>player1_name, player2_name, and player1_outcome</em>.</li><li><a href="https://rocketleague.tracker.network/">Rocketleague.tracker.network</a>, which automatically tracks player profiles and creates summarizing statistics for each. From here I gathered skill stats for both players— <em>total wins, MMR, and goal/shot ratio.</em></li></ul><p>The code is a rats nest that not even I know how it works, but if you’re sadistically curious you can check it out on my <a href="https://github.com/walkerpayne/Rocket-League-Match-Prediction">GitHub</a>. I’ll describe the process on a high level here:</p><ul><li>Ballchasing.com has an API. Using Python packages like <em>JSON</em>, <em>requests</em>, and <em>pandas</em>, I accessed JSON data for 200 pages of the website and scraped the relevant information into a dictionary, converted it to a DataFrame, and saved it as an excel spreadsheet. This resulted in about 40,000 data points, one for each match.</li><li>I took that data and used it to parse Rocketleague.tracker.network, which unfortunately did not have a public API. I imported the data from Ballchasing.com, iterated through each match and constructed custom URL’s for each player based on either their steam profile or xbox/psn/psynet name. Then for each profile I scraped the player stats into another DataFrame and excel spreadsheet.</li></ul><p>The end result can be seen in <strong>Figure 2</strong> below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iG-n-6o691y0Flo6BzFrbw.png" /><figcaption><strong>Figure 2</strong>. Dataset resulting from scraping various websites. (Image by author)</figcaption></figure><h3><strong>Exploratory Data Analysis &amp; Feature Engineering</strong></h3><p>The next step is to clean the data and engineer some new features to use as inputs for the machine learning model. After removing data with null values (e.g. players with private profiles or deleted accounts, or simple HTTP request timeouts), I ended up with about 10,000 useable data points.</p><p>I also like to explore the dataset and identify any interesting trends or relationships among variables. A quick way to start off the exploration is to get summary statistics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RgQpGOa9TW2R9zKjJy3bhQ.png" /></figure><p>From the above, a few interesting points stand out:</p><ul><li>Player 1, the one who uploaded the replay to Ballchasing.com, had on average 5954 wins. Their average MMR was 1240.</li><li>One player in particular had <strong>35,000 wins. </strong>Their name is <em>Scripts_RL</em>, and while they’re in the top 0.1% of players in terms of total number of wins, they’re only in the top 40% of players in terms of rank. <em>(For reference, I have about 3,000 wins and am in the top ~1% of players by rank. I’m not sure if this should be a source of pride for me or humility for them.)</em></li><li>Assuming a match length of about 7 minutes and a 50% win rate, that equates to 8,000 hours of in-match play time. Since RL’s release in July of 2015, this equates to nearly <strong>four hours of game play, every single day, for six years straight. </strong>Wild.</li></ul><p>It’s also important to check for a balanced dataset, which can be done quite easily:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghLswSpJwpQziEQ5rXk8rg.png" /></figure><p>Then I moved on to the relationships between various features, such as MMR and goal/shot ratio (<strong>Figure 3</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTtozS9_H7rqjQPxINklsA.png" /><figcaption><strong>Figure 3. </strong>Goal/shot ratio vs. skill rating (MMR). (Image by author)</figcaption></figure><p>From the graph we can see a clear negative correlation between MMR and goal/shot ratio. It makes sense that this metric should decrease as skill level increases, because a skilled player will save or block more shots on their net than an unskilled player. Because of this relationship, I may want to exclude the feature from my model training process to avoid <a href="https://statisticalhorizons.com/multicollinearity">multicollinearity</a>.</p><p>To train the ML model, I needed to do some feature engineering to create predictors based on my scraped data. The final dataset, ready to be split into training and testing subsets, can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5xC7UT9o5sZ1ZyEUoyePg.png" /></figure><h3><strong>Model Fitting &amp; Results</strong></h3><p>I used two different models to predict match outcome. It’s trivial to play around with various models when you have non-production code and static data, so I chose to implement both <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost</a> and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html">scikit-learn’s Logistic Regression</a>.</p><p>XGBoost is a relatively new algorithm (released in 2014) which gained popularity due to its success in various machine learning competitions. It’s an easily accessible “<a href="https://machinelearningmastery.com/gentle-introduction-xgboost-applied-machine-learning/">implementation of gradient boosted decision trees</a> designed for speed and performance”. The algorithm can be used for both regression and classification problems (among others). (Note that XGBoost, a decision tree based algorithm, does not require feature scaling/normalization.)</p><p>Logistic Regression is a supervised machine learning classification algorithm that predicts the probability of the dependent variable being 0 (in our case, a loss) or 1 (a win).</p><p>A significant difference between the two is that XGBoost is an ensemble model (new models are added sequentially, improving on previous models until a certain point) whereas Logistic Regression is a linear model. Additionally, XGBoost is much harder to interpret than Logistic Regression, which is an important consideration depending on the topic at hand.</p><p>The results are as follows:</p><ul><li><strong>XGBoost yielded an accuracy of 57%.</strong></li><li><strong>Logistic Regression yielded an accuracy of 57% as well.</strong></li></ul><p>Which brings up the question — what level of accuracy is acceptable? In this instance, my goal is for the model to be <strong>more accurate than a human at predicting the winner of a match. </strong>To establish this baseline, I manually classified around 100 matches based on the same data that the model is trained on. Using bootstrap sampling, I achieved an average accuracy of… 57.3%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swWTdpp60WuAIFiq_CtdNQ.png" /><figcaption><strong>Figure 4. </strong>Player 1 vs. Player 2 total wins. (Image by author)</figcaption></figure><p>My results using these two models bring up a fundamental and oft-overlooked issue: <strong>machine learning is not an appropriate tool for <em>all </em>datasets. If a well trained human cannot satisfactorily classify the data points, you shouldn’t expect a machine learning model to do so either.</strong></p><p>There are a few issues with the dataset I’ve gathered that explain this relatively poor accuracy. First, take a look at <strong>Figure 4 </strong>to the left. Each point on the graph represents a single match between two players. Orange points indicate that player 1 won, blue points indicate that player 1 lost. Would you be able to group the data into orange or blue points by simply looking at the graph? I know I couldn’t — there are no distinguishable trends or linear breakpoints that would indicate whether player 1 should have won or lost. We shouldn’t expect an ML model to be able to magically make these predictions either.</p><p>Another issue arises when we consider what is actually expressed by each feature, knowledge that many might say requires “domain expertise”. I chose to scrape player MMR, or Match Making Rating, and use it to train the ML model. It sounds like a good idea at first glance, but when we stop to think about it, the usability of MMR in predicting match outcome starts to unravel. Rocket League assigns an MMR that is updated after every match based on the difference between your MMR and the opposing players’ MMR, and whether you won or lost. In general, the reason MMR exists is to <em>match players against other players of the same skill level</em>. It follows that in most 1v1 matches the players will have similar if not equal MMR. The insight provided to the model is quite difficult to parse — MMR difference doesn’t have an easily discernable relationship with match outcome if the vast majority of matches are paired up evenly.</p><p>Despite the relatively poor accuracy of the models, they may not be entirely unusable. You can evaluate the variability of the performance of the model using <a href="https://machinelearningmastery.com/k-fold-cross-validation/">k-folds cross-validation</a>. If variability is low for each model (e.g. the accuracy of each model hovers around the same value {57.5%, 56.7%, 57.2%, etc.}) then it might be safe to use the model in production to place actual bets. To elaborate, imagine you are 95% confident that your model accuracy is 57% plus or minus a few percentage points. This means that over enough bets your odds of being correct will approach 57%, so you would be executing bets with positive expected value. Conversely if you are less confident in the variability of the model outputs you should beware utilizing it in any real capacity.</p><h3>Lessons Learned</h3><p>Alternative data sources are ripe for exploitation, especially on the internet. Web scraping is a powerful and useful skill to obtain, allowing you to generate unique datasets that may have never been utilized before. Though this example is fictitious, there may be similar datasets out there that are more expressive and directly actionable, creating an informational advantage that results in real gains.</p><p>To reiterate, machine learning is a very valuable and useful tool but its applicability is not universal. <strong>If the features in your dataset are not descriptive enough for a human to predict the outcome with high accuracy, then you cannot expect a machine learning algorithm to do any better.</strong></p><p>And lastly, even if your model accuracy is poor you may learn something in the process that makes you more knowledgeable and better prepared to take advantage of future opportunities. As Matthew McConaughey once said,</p><blockquote><em>“I’ll take an experienced C over an ignorant A any day.”</em></blockquote><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8da4ab8aecc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/alternative-data-sources-and-informational-advantages-via-web-scraping-and-machine-learning-8da4ab8aecc3">Alternative Data Sources And Informational Advantages Via Web Scraping And Machine Learning</a> was originally published in <a href="https://medium.com/codex">CodeX</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 Analyze Blood Glucose Data with Python Data Science Packages]]></title>
            <link>https://medium.com/data-science/how-to-analyze-blood-glucose-data-with-python-data-science-packages-4f160f9564be?source=rss-c693b9460084------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f160f9564be</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[diabetes]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Walker Payne]]></dc:creator>
            <pubDate>Wed, 01 Sep 2021 16:35:46 GMT</pubDate>
            <atom:updated>2021-12-01T17:57:14.232Z</atom:updated>
            <content:encoded><![CDATA[<h4>Extracting insights from glucose monitor data using Pandas, NumPy, Matplotlib, Seaborn, Plotly, and more.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyUrNWsd9YYKsROx9_h4gg.jpeg" /><figcaption>The Death of Seneca, <a href="https://www.museodelprado.es/en/the-collection/art-work/the-death-of-seneca/7a5faebf-1111-4d01-bc18-c47c771533c0">Manuel Domínguez Sánchez</a>, 1871.</figcaption></figure><p>Type 1 diabetes sucks. Maintaining blood glucose levels within the target range at all times is important to prevent and/or delay the onset of serious health problems such as heart disease, vision loss, kidney disease, nerve damage, and a <a href="https://www.hopkinsallchildrens.org/Patients-Families/Health-Library/HealthDocNew/Diabetes-Control-Why-It-s-Important">whole slew</a> of other bad things. I’m not here to lament about how terrible it is, though. I’m here to demonstrate how to analyze blood glucose data to improve overall glycemic control for yourself and/or your loved ones.</p><p><strong>The goals of this article are:</strong></p><ul><li><strong>to provide an insightful analysis of my blood glucose (BG) behavior over time,</strong></li><li><strong>to determine actionable steps to improve my glucose control based on this data, and</strong></li><li><strong>to provide an educational template and toolkit for others to follow who wish to do the same.</strong></li></ul><p>The following visualizations and analytics are immensely valuable to someone struggling with T1 diabetes. My hope is that this article can empower those people with the knowledge and skills necessary to carry out their own analysis and ultimately improve their lives. All code discussed here is written by me, free, and available for download at the end of this post.</p><blockquote>“The thing that matters the most is not what you bear, but how you bear it.”— Seneca, Roman Stoic philosopher, On Providence</blockquote><p>I used a <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2903980/">paper</a> published in the <em>Diabetes Technology &amp; Therapeutics </em>journal to identify which statistical methodologies and graphical representations would be relevant and provide the most value to someone who’s looking to analyze data from a BG monitor. The following are the most important statistical tools for this type of analysis:</p><ul><li><strong>mean glucose value </strong>(mg/dL), a common descriptor of overall blood glucose control.</li><li><strong>Interquartile range of BG values</strong>, suitable for non-symmetric distributions.</li><li><strong>Standard deviation of BG rate of change, </strong>representing the spread and range of glucose transitions, or a measure of stability of glucose fluctuations.</li><li><strong>Percentage of time spent within, below, and above predetermined values.</strong> The three clinically distinct glycemic regions suggested by the <a href="https://pubmed.ncbi.nlm.nih.gov/8366922/">Diabetes Control and Complications Trial</a> are: <strong>hypoglycemia </strong>(BG &lt; 70 mg/dL), <strong>target range</strong> ( 70 &lt; BG &lt; 180), and <strong>hyperglycemia </strong>(BG &gt; 180).</li><li><strong>Glucose trace with superimposed aggregate glucose traces, </strong>to visually demonstrate the amount of time that BG values are above or below the relevant thresholds.</li><li><strong>Poincaré plot (lag plot), </strong>to easily visualize overall glucose control and rapid glucose excursions.</li><li><strong>Control Variability Grid Analysis</strong>, a visualization tool used to determine trends in glucose control.</li></ul><p>The following sections will demonstrate how to calculate or create the relevant value or visualization, an explanation of why it’s important, and an example analysis of my own data.</p><h3>Data Pre-Processing</h3><p>The first step is to pull the data. In my case, I use a Dexcom Continuous Glucose Monitor (CGM). Dexcom provides easy access to your data which can be downloaded as a CSV file through Dexcom Clarity. I’ll be pulling data for a 30 day period. The output looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AdzIqUyr39_cKCav5UI1Q.png" /><figcaption><strong>Figure 1.</strong> Screenshot of Dexcom Clarity data as a CSV file. (Image by author)</figcaption></figure><p>The important data for us to look at are the <em>Timestamp </em>and <em>Glucose Value (mg/dL) </em>columns. Every 5 minutes, the CGM acquires a data point, stores it, and displays it to the user.</p><p>Next we need to import all the relevant libraries. Today we’ll be using Pandas, NumPy, Matplotlib, Seaborn, and Plotly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0rUscONKW9E7QLo4xII3A.png" /></figure><p>The only relevant columns we need are <em>Timestamp </em>and <em>Glucose Value (mg/dL). </em>We can also drop the first couple of rows of the DataFrame, reset the index, and clean up the column names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-2kosW_zuej14HRkRTyhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*WUtmQnNQVxhv9hSPWzOaeA.png" /></figure><p>And now, with a clean DataFrame, we’re ready to proceed with the analysis.</p><h3>Mean Glucose Value</h3><p>The mean glucose value over a given period is a <strong>straightforward descriptor of overall glycemic control</strong>. The target range for diabetics is between 70 and 180 mg/dL, with normal (non-diabetic) mean glucose between 90 and 110 mg/dL.</p><p>The pandas <em>.describe() </em>function provides us with the total number of values and some descriptive statistics, including the mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-M3jISJ-ic-4i3ty_W4yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*KsmwsuLLVg1zAqD21Hc4SQ.png" /></figure><p><strong>My mean glucose value over this 30 day period was 117 mg/dL</strong>, which is pretty good. I should note that I do not have an insulin pump and instead administer a minimum of 4 insulin shots per day to maintain target levels, the amount of each shot based primarily on carbohydrate consumption (with a number of other factors as well).</p><blockquote><strong>NOTE</strong>:<strong> the standard deviation (STD) value shown above can be misleading</strong> because the BG measurement scale is highly asymmetric — the hypo range (40–70 mg/dL) is numerically narrower than the hyper range (180–400+ mg/dL). As such, the distribution of glucose values is highly skewed and the STD would be influenced predominantly by hyperglycemic excursions and not sensitive to hypoglycemia[1]. For this reason, the interquartile range (IQR) is a more suitable measurement for non-symmetric distributions.</blockquote><h3>Interquartile Range of Blood Glucose Values</h3><p>A box and whisker plot can be created using Seaborn to demonstrate the IQR that we calculated in the last section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDyKWseiuRCijMGX8mmVcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*0OPwVFbtg8e_-TlFE6SErA.png" /><figcaption><strong>Figure 2.</strong> BG Interquartile Range. (Image by author)</figcaption></figure><p>The plot above is a visual representation of my IQR. Values range from ~40 (minimum detectable by the CGM) to 200, with points above 200 being classified as outliers as determined by the IQR.</p><p>We can split the plot based on day of the week to try to identify any trends:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26KGEH10VOA75UKLBBPs6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8mw8XRMgzqqzZpR_txsjA.png" /><figcaption><strong>Figure 3.</strong> Box and whisker plot split across day of the week, generated with Plotly. (Image by author)</figcaption></figure><p><strong>Figure 3</strong> above reveals some interesting insights. Let’s look at Saturdays in particular. Note the points that lie outside of the top “whisker”- these are outliers, or observations that are numerically distant from the rest of the data. Although the IQR (the “box”) on Saturdays was reasonably small, it looks like I had an excursion into high BG levels that was uncharacteristic. Since weekends are generally less structured for me in terms of eating and exercise habits, this makes sense. Alcohol consumption, non-normal meals (e.g. eating out at a restaurant), and potentially a lack of exercise are all things that happen with a greater frequency for me on Saturdays, and can all lead to poorer glycemic control.</p><p>Actionable insight from this analysis could be that I need to be more careful with my weekend habits and place more emphasis on glycemic control during these periods.</p><p>Below is the same graph in GIF format, showcasing one of the interesting benefits of Plotly: it’s interactive! Hovering the mouse over different areas of the graph make it quite easy to compare values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*blcI10JSmQEm7E9st70Jcg.gif" /><figcaption><strong>Figure 4. </strong>Box and whisker plot GIF, showcasing the interactivity of Plotly. (Image by author)</figcaption></figure><h3>Standard Deviation of Blood Glucose Rate of Change</h3><p>As was mentioned in the section on Mean Glucose Value, computing the standard deviation (SD) of simple glucose values over time is <em>not </em>recommended. To reiterate the reasons why:</p><ol><li>“the BG measurement scale is highly asymmetric,</li><li>the hypoglycemic range is numerically narrower than the hyperglycemic range, and</li><li>the distribution of the glucose values of an individual is typically quite skewed.”[1]</li></ol><p>Instead we can calculate the <em>rate of change </em>of BG values over time which typically is symmetric and compute the standard deviation of that. The resulting value will be statistically accurate and serve as an indicator of BG stability. <strong>A higher SD of BG rate of change is indicative of increased BG variability and thus worse control.</strong></p><p>To calculate the rate of change we use the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*XsgAPt8sNG9H0c4MOu2e-g.png" /></figure><p>Where rate of change is expressed in units of (mg/dL)/min. Since our readings are taken every 5 minutes, the denominator is simply 5. In Python, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOZdBA4IULlA2FUIqG0cdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*k43Cu4r03e591EhJqAE0fg.png" /></figure><p>To create a visualization of this, we’ll use a Seaborn histogram and some fancy f-string formatting to auto-populate the title with the mean and standard deviation values of the rate of change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ze4n1JOK2_TTGE6oDa1mUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*fOc5NPYPQHibrK5eu3cKIw.png" /><figcaption><strong>Figure 5.</strong> BG Rate of Change graph. (Image by author)</figcaption></figure><p>The value itself isn’t super intuitive. The SD for my glucose values was 0.99, meaning the majority (~68%) of my time was spent with a BG rate of change between -1 and +1. If the SD was 5 it would mean that my glucose levels were fluctuating much more widely and rapidly, which is not an ideal condition.</p><p>For this analysis to be the most impactful, it would be used as a <strong>comparison tool </strong>between treatment changes. You could calculate the SD for one 30 day period, then implement some change (insulin-to-carb ratios, routine exercise, different type of exercise, dietary change, etc.) and calculate it again for the next 30 day period. Hopefully the SD is smaller for the second dataset, and you can quantify the impact of the change on your overall glycemic control.</p><h3>Percentage of Time in Range (TIR)</h3><p>It’s useful to know the percentage of time in various ranges as an indication of the general behavior of CGM variations. As mentioned earlier in the study, the relevant ranges are:</p><ul><li><strong>hypoglycemia </strong>(BG &lt; 70 mg/dL)</li><li><strong>target range</strong> ( 70 mg/dl &lt; BG &lt; 180 mg/dL)</li><li><strong>hyperglycemia </strong>(BG &gt; 180 mg/dL)</li></ul><p>The calculation of this value was a little bit tricky for me, involving Pandas methods such as <strong><em>.grouper(), .unstack(), and .fillna(). </em></strong>See the following code and corresponding output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NiRnobHByPCZWl1g0JBSQ.png" /></figure><p>We can summarize these results by calculating a simple percentage of the total for each discrete time period. In this example, I used f-string formatting to create a nicely spaced tabular output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-E0KDp5fBjX_3XMVjNUzg.png" /></figure><p>Over this 30 day period, <strong>my BG values were in range ~90% of the time</strong>. I would prefer this number to be higher, but it will never be perfect. <strong>Ultimately, a higher TIR correlates to a lower risk for microvascular complications</strong> <strong>[2]</strong>. TIR should be considered in combination with lab-derived A1C values to accurately assess your own day-to-day glucose variations.</p><p>I have only been able to find a few examples for TIR goals. <a href="https://www.diabetes.org/healthy-living/devices-technology/cgm-time-in-range">Diabetes.org</a> specifies a goal of at least 70% TIR, but I personally feel that is too low. Suffice to say, the higher the TIR, the better.</p><h3>Glucose Trace</h3><p>The glucose trace graph is simply a time series of BG values. It’s useful to visualize the fluctuations in BG levels over time, to determine if there are any trends throughout the day.</p><p>I wrote the following code to create a Plotly interactive graph that has buttons to change the display region. For example, clicking “1d” will change the window to display only one days worth of data. Similarly, “1m” will change the view to encompass one month of data. From there, you can scrub back and forth to see how the BG values fluctuate over time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOrMlk309SAhstniFixOgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-9k03r2-ie-MPGjjucB0w.png" /><figcaption><strong>Figure 6. </strong>Glucose value vs. time, with superimposed aggregate glucose value. (Image by author)</figcaption></figure><p><strong>Figure 6</strong> above shows my BG on July 25, 2021. Around 1030 my BG crossed the hyperglycemia threshold until 1200. The duration of the excursion is made clear with the red line, which is termed the <em>aggregate glucose trace</em>. Without this line, it would be difficult to quickly know whether or not the BG values were within an acceptable range. For example, from 1500 to 1900 there was a distinct rise and subsequent decline in BG. While intuitively this may indicate a lack of control during that period, the superimposed aggregate glucose trace (red line) shows that the BG values never crossed the hyper- or hypo-glycemic thresholds, indicating satisfactory glycemic control.</p><p>To calculate the aggregate glucose trace, I created a new column in the DataFrame using simple if/else logic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_nQorBLRPjR0Og7MOC2zQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGeN5Dpzgp152yyIL5jHHg.png" /></figure><h3><strong>Poincaré Plot</strong></h3><p>A Poincaré plot is traditionally used in physics to visualize the dynamic behavior of a system. In this use case, “<em>a smaller, more concentrated plot indicates system (patient) stability, whereas a more scattered Poincare plot indicates system (patient) irregularity, reflecting in our case poorer glucose control and rapid glucose excursions</em>.”[1]</p><p>Each point of the plot has coordinates BG(t-1) on the x-axis and BG(t) on the y-axis. The difference between the coordinates (y-x) of each point represents the BG rate of change. To calculate this, I simply created a new column in the DataFrame called “Lag” and used the Pandas <em>.shift() </em>function to get (t-1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5diE0H4kTdx8bjoC2Db9PA.png" /></figure><p>This plot is an ideal comparison tool to visualize the <strong>effect of changes in treatment. </strong>For example, one could gather BG “control” data for a 30 day period, make some change in treatment (e.g. adjustment of carb ratios, adjustment of basal dose, regular exercise, dietary changes, etc.) for 30 days and gather that BG data, then plot the two periods next to each other and compare the spread. A more concentrated second 30 day period would be indicative of a beneficial treatment.</p><p>Since I didn’t have any treatment changes to compare across, I decided to showcase the Poincaré plot with 3 separate timeframes — one “good day”, one “bad day”, and the total 30 day period:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkWcNyXRYYtsngshIitDWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QcuPhbTEJ7drMUZTqs1Tw.png" /><figcaption><strong>Figure 7. </strong>Poincaré plot comparing glucose control for three distinct periods. (Image by author)</figcaption></figure><p>From <strong>Figure 7 </strong>above it’s clear that the left-most plot was indeed a “bad” day, with a greater spread of points indicating more variation in BG.</p><p>There is one outlier point on the “Total 30 Day” graph that is the result of a two-hour period where my CGM failed to acquire data. My BG changed by 108 mg/dL in that period, resulting in a significant difference between the two adjacent timestamps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XQOWFS4iE7-5UPb6QVzGg.png" /></figure><h3>Control Variability Grid Analysis (CVGA)</h3><p>Saving the best for last, the CVGA was the most insightful graph of this whole project for me. CVGA is yet another tool for visualizing overall glycemic control. I’ll explain what it is after we take a look at the graph itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBflijRDwu8hY3Z8jj3ChQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAmYv4h11gwUzZctC3kQYw.png" /><figcaption><strong>Figure 8. </strong>Control Variability Grid Analysis. (Image by author)</figcaption></figure><p>Each point on <strong>Figure 8 </strong>represents <strong>one day</strong> in this 30 day period. The x-coordinate for each point is the <em>minimum </em>BG in that 24 hour period and the y-coordinate is the <em>maximum </em>BG value in that same 24 hour period. (Note the inverse direction of the x-axis.) I calculated these values by creating a new DataFrame aggregated by day and using NumPy’s min and max aggregation functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzlsBsHGSPnU43WLZqX2nA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suXMgUUHjwZ5CXQCmvlcZw.png" /></figure><p>To interpret the graph, let’s look at an example point, the red ‘X’ in <strong>Figure 8</strong>, that has coordinates (56, 181). From our previous DataFrame output that showed min and max values on a daily basis, we can see that this coordinate corresponds to the day of July 19th, 2021. On this day my lowest BG value was 56 and my highest was 181 which places the data point in the “Lower C” section of the graph. An ideal day would fall in the green areas of the graph, with a perfect day being in the “A” subsection. Days in “A” would have lows between ~90 and 110, with highs less than ~180. See <strong>Table 1</strong> below for definitions for each zone[1]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTo9XhdQsUhoVmk06936Mw.png" /><figcaption><strong>Table 1. </strong>CVGA zone definitions. <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2903980/">Source</a></figcaption></figure><p>The CVGA demonstrates that my BG trends lower than it should. Specifically, it demonstrates that <strong>I am prone to overcorrection of highs</strong>. I clearly need to re-evaluate my high BG correction ratios and place more emphasis on decreasing the number of lows that I experience.</p><p>My results from the CVGA look rather poor, but we have to remember that they don’t take into account the duration of the low or high, just the absolute minimum and maximum values. I am quick to correct the lows (based on results discussed in the “Percentage of Time in Range” section), but these excursions into hypoglycemia are still detrimental to overall health and must be addressed. It’s important to consider these analyses together to develop a holistic understanding of your own glycemic control.</p><h3>Conclusion — Try it Yourself!</h3><p>Thanks a lot for reading along. If you or someone you know is a T1 diabetic, hopefully you’ve found value in this post. You can create all of the same graphs I demonstrated here with your own data — just download the Jupyter notebook from <a href="https://github.com/walkerpayne/Glucose-Analysis">my GitHub repo</a>. If you have any questions, I’m happy to help. Feel free to drop a comment below or on GitHub.</p><blockquote>Medical Advice Disclaimer: The information, including but not limited to text, graphics, images, and other material contained in this article are for informational purposes only. No material in this article is intended to be a substitute for professional medical advice, diagnosis or treatment. Always seek the advice of your physician or qualified health care provider with any questions you may have regarding a medical condition or treatment and before undertaking a new health care regimen, and never disregard professional medical advice or delay in seeking it because of something you have read or learned here.</blockquote><p>References:</p><p>[1]<a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2903980/">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2903980/</a></p><p>[2]<a href="https://clinical.diabetesjournals.org/content/38/5/439">https://clinical.diabetesjournals.org/content/38/5/439</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f160f9564be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-analyze-blood-glucose-data-with-python-data-science-packages-4f160f9564be">How to Analyze Blood Glucose Data with Python Data Science Packages</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 Much Bitcoin Should You (Reasonably) Own?]]></title>
            <link>https://medium.com/codex/how-much-bitcoin-should-you-reasonably-own-ae9b66cfb3d?source=rss-c693b9460084------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9b66cfb3d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Walker Payne]]></dc:creator>
            <pubDate>Sat, 19 Jun 2021 19:58:42 GMT</pubDate>
            <atom:updated>2021-07-01T16:03:05.680Z</atom:updated>
            <content:encoded><![CDATA[<h4>A data-driven how-to guide on quantifying risk for portfolios with crypto exposure using Python, Modern Portfolio Theory, Sharpe Ratio, and Monte Carlo Simulations.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*SWHATB6-7Edj-nP3" /><figcaption>A graphical breakdown of Systematic vs Unsystematic risk. Diversification can reduce unsystematic risk. <a href="http://premium.working-money.com/wm/display.asp?art=826">Source</a></figcaption></figure><h3>The Problem — How Does Crypto Affect Your Portfolio Volatility?</h3><p>Let’s say you’re an average 20-something year old with about <a href="https://www.synchronybank.com/blog/median-retirement-savings-by-age/">$16,000</a> in retirement savings. You know a little bit about “investing” and have most of your money in a Vanguard Total Stock Market Index and a Vanguard US Bond Index. You also like to play around with some individual stock picking and crypto currencies on Robinhood, because <em>what if I find the next big crypto before it blows up?? Imagine what would happen if I put in $1000 today and it goes up by 9150% in one year like ETH? I’d be </em><strong><em>rich</em></strong><em>!!</em></p><p>So then you decide to toss about a grand into Robinhood and see what happens. Making money isn’t so hard. After all — you’ve gained 50% in <em>two months</em> on AMC and BB, so why does everybody get excited about trying to make only 7 or 8% in a <em>year</em>?</p><p>In this article, we’re going to try to quantify how much risk you’re really taking on with this strategy. <strong>Specifically, the questions I’ll try to answer are:</strong></p><ul><li><strong>How risky is (or <em>was</em>, over a specific time period) Bitcoin, compared to your typical stock and bond indices?</strong></li><li><strong>How does adding Bitcoin to your portfolio affect your overall risk and return profile?</strong></li></ul><p>Additionally, I will:</p><ul><li>Explain the importance of diversification in an investment portfolio through concepts such as Modern Portfolio Theory and the Markowitz Efficient Frontier.</li><li>Compare the risks and volatility of various assets in a modern portfolio, specifically an example portfolio composed of stocks, bonds, and Bitcoin.</li><li>Demonstrate how to calculate asset correlation coefficients, to highlight how easy it is to become over-exposed to risk when a portfolio is composed of only positively-correlated assets.</li><li>Use a Monte Carlo simulation to generate portfolios of various allocations and identify the best allocations using the Sharpe Ratio.</li></ul><p>To do this analysis, I’ll use Python libraries such as yfinance, Pandas, Matplotlib, NumPy, and more. Let’s get started.</p><h3>What is Modern Portfolio Theory (MPT)?</h3><p>Before we talk about risk from crypto exposure, let’s cover the higher level topic of Modern Portfolio Theory. Straight from the <a href="https://en.wikipedia.org/wiki/Modern_portfolio_theory">wiki</a>: “<strong>Modern portfolio theory</strong> (<strong>MPT</strong>), or <strong>mean-variance analysis</strong>, is a mathematical framework for assembling a portfolio of assets such that the expected return is maximized for a given level of risk.”</p><p>The premise upon which MPT is built is that investing in multiple assets (indexing) is less risky than owning just one or a few (individual stock picking). More technically, <strong>you can reduce the risk of your investment portfolio by diversifying your holdings into assets that are negatively correlated.</strong></p><p>This has been conventional wisdom for a long time and shouldn’t be news to anyone with interest in personal finance, financial independence, or investing in general.</p><p><a href="https://en.wikipedia.org/wiki/Harry_Markowitz">Harry Markowitz</a> introduced MPT in the 50s, along with the concept of the <strong>Efficient Frontier</strong> (<strong>Figure 1</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LCefhBhzBuSOLQfv.png" /><figcaption><strong>Figure 1.</strong> A graph of the Efficient Frontier (<a href="https://www.youngresearch.com/authors/ejsmith/risk-and-reward-an-efficient-frontier/">source</a>)</figcaption></figure><p>The frontier itself is a set of all the optimal portfolios that offer the highest level of returns for a given level of risk. Any portfolio along the line is optimal, while any portfolio in the area below and to the right of the line is suboptimal. The X-axis is risk, measured as the standard deviation of annual returns, while the Y-axis is annual returns. The main idea I’d like to reiterate is that you can <strong>reduce the standard deviation (risk) of a portfolio’s returns by investing in assets with low or negative covariance. </strong>For a given level of risk, there are innumerable portfolios that can be constructed to generate higher or lower returns. Your goal as an investor should be to find a portfolio that sits on the curve, so that you’re getting the maximum amount of return possible for your chosen level of acceptable risk.</p><blockquote>NOTE: Check out these articles on Investopedia if you want to learn more about <a href="https://www.investopedia.com/terms/m/modernportfoliotheory.asp">MPT</a> and the <a href="https://www.investopedia.com/terms/e/efficientfrontier.asp#:~:text=The%20efficient%20frontier%20is%20the,for%20the%20level%20of%20risk.">Efficient Frontier</a>.</blockquote><h3><strong>How Risky is Bitcoin, Compared to Stocks and Bonds?</strong></h3><p>The <strong>standard deviation </strong>of an assets returns can also be called risk or volatility. A stock whose returns deviate greatly from the mean is said to carry more risk. The first step in trying to quantify this risk is to pull some financial data of various assets and calculate their returns. For this example, I’ll use:</p><ul><li><strong>^GSPC</strong>, the ticker for the SP500, to represent stocks.</li><li><strong>BND</strong>, a Vanguard Total Bond Index fund, to represent bonds.</li><li>and <strong>BTC-USD</strong>, AKA Bitcoin.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQYowAUhsbPkI3P05ROPUw.png" /></figure><p>For this analysis, I chose a <strong>2 year period</strong> as the timeframe. Next, we’ll find the <strong>logarithmic return</strong> of each asset so that we can examine them separately in the specified timeframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7LoBnd5tJ6iVhAFKN1BKg.png" /></figure><blockquote>Uh oh! It’s the methodology police. There are a LOT of different pros and cons for calculating either logarithmic or simple returns. An appropriate method for this example is to calculate the arithmetic mean of the logarithmic returns of the assets, as I’ve done here. Another appropriate method could be to calculate the geometric average of the simple returns. An arguably <strong>incorrect </strong>method for comparing asset performance is to calculate only the arithmetic mean of the simple returns. If this all sounds confusing, here’s a good <a href="https://money.stackexchange.com/questions/24382/what-does-the-average-log-return-value-of-a-stock-mean/24486">discussion</a> of the topic. The important thing to note is that due to the complex nature of compounding returns and the fact that, for example, +5% and -5% do not cancel out to 0%, there are many of considerations involved in making an appropriate calculation. Seeing as this post is for demonstrative purposes only, I’m OK with the selected method.</blockquote><p>This shows us the daily log returns of the assets. To see an annualized amount, multiply the mean daily returns by the number of trading days in a year for each asset: 250 for stocks and bonds, 365 for Bitcoin. (252 is technically more accurate, but the difference is negligible.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-iwduxqtanB1aHBcIORHcA.png" /></figure><p>For calculating standard deviation, we can use the Pandas <strong>.std() </strong>method. Following the same logic as before, we need to annualize this number. However, instead of simply multiplying by the number of trading days, we also need to take the square root of the number of trading days due to the algebra involved in converting variance to standard deviation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCKJZEUV5AumPqnF-dgv5Q.png" /></figure><p>From here we can summarize the data visually in Tableau — showing that Bitcoin has had significantly higher returns, while also carrying significantly more risk (<strong>Figure 2</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZw6FkPUZNJ_lTc7XZr4qA.png" /><figcaption><strong>Figure 2</strong>. Asset risk vs. annualized log returns over a 2 year period. Source: Walker Payne</figcaption></figure><p>From this graph we can answer our first question from earlier —<strong> how risky is Bitcoin compared to the typical stock and bond indices?</strong></p><p><em>During this specific two year period</em>, BTC provided a return that was about <strong>3.7x higher</strong> than that of the SP500. With higher return is an expectation for greater volatility, which is also present — BTC’s standard deviation was <strong>3.3x higher </strong>than the SP500.</p><blockquote>It’s time for everyone’s favorite financial disclaimer: <strong>past performance is no guarantee of future results</strong>. Notice how I am not making any claims about what could happen in the future — I am simply stating the results of my specific analysis over this given timeframe. Despite the high returns, this is <strong>absolutely not </strong>a suggestion to lever up and go 100% Bitcoin.</blockquote><p>One interesting point from <strong>Figure 2 </strong>is that BTC provided a greater increase in return per unit increase of risk relative to stocks and bonds. Because of that, it appears BTC would have been a “good” investment in this timeframe. This conclusion is corroborated by my own Roth IRA portfolio over a similar period (<strong>Figure 3</strong> below). (Note that the time period in <strong>Figure 3 </strong>is not the exact same as the one used in the analysis above, because my Roth IRA account was created in November of 2019 and thus has no data between June-October 2019.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mP0RZrgenfgAQ9bxRMeFAQ.png" /><figcaption><strong>Figure 3. </strong>Charles Schwab Portfolio Rate of Return tool. Source: Walker Payne</figcaption></figure><p>This graph is a screenshot from my own Charles Schwab Roth IRA account which depicts the risk and return of various benchmark portfolios along with my own (green square). If you imagine a linear regression line of best fit based on the benchmark portfolios, you can see that my own would lie above the line, indicating that it outperformed the predicted risk-return relationship by generating a greater-than-expected return for a given level of risk. The reason that my portfolio risk (and subsequent return) is so high is that I had significant exposure to BTC (via GBTC) in this account. Based on the data we calculated in <strong>Figure 2</strong>, this exposure to BTC affected my portfolio in exactly the way we expected — higher risk, but higher reward.</p><p>Notice how <strong>Figures 1, 2, and 3</strong> agree with one another nicely. <strong>Figure 1</strong> shows the theoretical efficient frontier, <strong>Figure 3 </strong>shows a real application of that frontier, and <strong>Figure 2 </strong>is just a subset of <strong>Figure 3 </strong>that we calculated ourselves.</p><p>The conclusion for this section is that BTC was an extremely volatile asset over the given 2 year period. Despite this, it did provide enough return to justify the risk.</p><blockquote>One last note before we move on. I want to emphasize that I treat Bitcoin and other cryptos as highly speculative assets. It’s hard to tell from the context given, but I never had more than 5% of my liquid net worth in Bitcoin at any given time. My Roth IRA is labeled as an “extremely aggressive” portfolio based on my allocation because I wanted to utilize the tax advantages of the account. In reality, my total portfolio (when you consider both my Roth IRA and my taxable investment accounts) is much more conservative.</blockquote><h3>How Does Adding Bitcoin To Your Portfolio Affect Your Overall Risk And Return Profile?</h3><h4>Calculating Correlation</h4><p>An important parameter to consider when discussing the risk of a specific asset is its correlation with the rest of the portfolio. Like we talked about in the section on Modern Portfolio Theory, you can reduce the risk of your overall portfolio by investing in assets that are negatively correlated. It follows logically, then, that we would see positively correlated assets in a portfolio like mine in <strong>Figure 3</strong>. To check this, we can use the Pandas <strong>.corr() </strong>method to calculate the correlation matrix for our 3 example assets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hujqP3LYDA7YSFTItrde0g.png" /></figure><p>It appears that within this period, Bitcoin was positively correlated with both stocks AND bonds. In fact, even stocks and bonds themselves were positively correlated. The main idea is that this portfolio, over this time period, took on an extremely high amount of risk and did not utilize the concept of negative correlation risk mitigation. It worked out well for me this time, but could have <em>easily </em>gone the other way.</p><h4>The Sharpe Ratio &amp; Monte Carlo Simulations</h4><p>The last analysis that we’ll do is identify what the “ideal” asset allocation was during this period amongst stocks, bonds, and Bitcoin. To determine this, we’ll use a metric called the <a href="https://www.investopedia.com/terms/s/sharperatio.asp"><strong>Sharpe Ratio</strong></a><strong> </strong>which is used to compare assets by understanding the return of an investment when you take into account its risk. Specifically, it is the “average return earned in excess of the risk-free rate per unit of volatility or total risk.” <strong>It describes how much excess return you receive for taking on the volatility of a riskier asset.</strong></p><p>To find the portfolio with the highest Sharpe Ratio during this time period, we will simulate thousands of portfolios with various weights amongst the three assets — stocks, bonds, and Bitcoin. For example, you could have a portfolio with 25% bonds, 25% stocks, and 50% bitcoin. Or one with 80% stocks, 10% bonds, and 10% bitcoin. A <strong>Monte Carlo simulation, </strong>in this scenario, simply generates thousands of random portfolio weights to estimate the different possible risk vs. return profiles.</p><p>The following code snippet demonstrates how to create this simulation using a simple for loop in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/132c875e75c1e3e300668e7aabf52c47/href">https://medium.com/media/132c875e75c1e3e300668e7aabf52c47/href</a></iframe><p>The output is a DataFrame with 5000 rows — each row being an individual portfolio with randomly generated weights for each asset, and the associated returns, variance, and Sharpe Ratio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYp4Kk9nPzJRLzKM9gRVzQ.png" /></figure><p>With this data set we can identify some interesting portfolios using some Pandas DataFrame operations like <strong>iloc(), idxmax(), idxmin(), etc.</strong></p><p>For example, we could find the portfolio with the highest Sharpe Ratio and see that it had a 23% annualized return and was composed of 37% bonds, 17% Bitcoin, and 45% stocks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yntEnYwbjGG1hdRbohgN1Q.png" /></figure><p>Or we can find the portfolio with the minimum risk which, interestingly, is not composed of 100% bonds but is instead ~98% bonds, 0.5% Bitcoin, and 1.5% stocks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*teWp5yLDe8vCQ3wfqW1HdQ.png" /></figure><p>Compared to the “optimal” portfolio above (the one with the highest Sharpe Ratio), there exists another allocation with nearly 4x the volatility:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sorQBTbpAnyOlJq4RXpJA.png" /></figure><p>Thus the effect of Bitcoin on a portfolio (<em>in this specific time period) </em>is clear — as allocation increases, so too does risk and return. To revisit our earlier example of the average 20-something year old, here are the values for a portfolio consisting of 80% stocks and 20% bonds for the two year period:</p><ul><li>Annualized returns: 17.5%</li><li>Standard deviation: 0.20</li><li>Sharpe Ratio: 0.86</li></ul><p>Now if we decided to “play around” with $1000 in BTC (by taking some allocation from bonds, for example), we would have a ~6.25% allocation ($1000/$16000) in Bitcoin, 80% in stocks, and 13.75% in bonds:</p><ul><li>Annualized returns: 22%</li><li>Standard deviation: 0.23</li><li>Sharpe Ratio: 0.95</li></ul><p>The above examples show that by diverting some of our original portfolio into BTC, we actually improved our risk-adjusted rate of return as indicated by the Sharpe Ratio. This is actually counter to my original hypothesis, and I’ll include it for the sake of good science. But it makes sense — the relative annualized return of BTC over this specific two year period was high enough to make it worth bearing the increase in volatility. Note too, though, that <strong>a minor 6% exposure to bitcoin increased the overall portfolio risk by 15% (0.20 to 0.23).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlqgczjaJ9mWTdRnjA3Ppg.png" /><figcaption><strong>Figure 4</strong>. A graph of risk vs. return for 5000 randomly generated portfolios comprised of stocks, bonds, and Bitcoin, colored by Sharpe Ratio. Source: Walker Payne</figcaption></figure><p><strong>Figure 4 </strong>shows all 5000 portfolios from the DataFrame, their risk vs. return spread, and the Sharpe Ratio distribution. As we would expect, the portfolios with the highest Sharpe Ratio lie along the top edge of the Efficient Frontier. This is because the portfolios along the top edge represent those with the highest possible returns for a given level of risk.</p><p>With this framework, you can now run the same set of simulations for any number and combination of assets that you desire, to see how exposure to them would affect your overall portfolio.</p><h3>The End</h3><p>In conclusion, we now have a better understanding of Modern Portfolio Theory and the importance of asset correlation on portfolio risk. Bitcoin, used here as a proxy for cryptocurrencies in general, provided significant returns at the cost of an incredible amount of volatility. Investors (or, in most cases, speculators) should tread carefully when entering assets with extremely high variance and should not discount the effect of said variance on their overall portfolio — even a minor amount of exposure can significantly change the risk/return profile of the portfolio.</p><blockquote>I hope you enjoyed this post. If you have any comments, questions, concerns, or corrections (I’m sure there are many), please feel free to drop them below.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9b66cfb3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/how-much-bitcoin-should-you-reasonably-own-ae9b66cfb3d">How Much Bitcoin Should You (Reasonably) Own?</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying Machine Learning to Nuclear Reactor Kinetics]]></title>
            <link>https://medium.com/data-science/applying-machine-learning-and-exploratory-data-analysis-to-nuclear-reactor-kinetics-d1dae16fb081?source=rss-c693b9460084------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1dae16fb081</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nuclear]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Walker Payne]]></dc:creator>
            <pubDate>Mon, 12 Apr 2021 13:41:49 GMT</pubDate>
            <atom:updated>2021-06-28T15:31:01.786Z</atom:updated>
            <content:encoded><![CDATA[<h4>A primer on nuclear physics, reactor operation, and predictive modeling using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAacUvBJv6w765US8TxubQ.jpeg" /><figcaption><strong>Figure 1.</strong> 2 Megawatt TRIGA reactor at full power. Source: me (Walker Payne)</figcaption></figure><p>According to the <a href="https://www.nrc.gov/reading-rm/doc-collections/datasets/index.html">Nuclear Regulatory Commission</a>, there are 31 nuclear research reactors in the United States. I happen to have a license to operate one of them, and in this article I’ll be demonstrating how I applied machine learning and general data analytics techniques to predict pulse power levels and increase the repeatability of our experiments.</p><h3>Background</h3><p>A <a href="https://en.wikipedia.org/wiki/Nuclear_reactor#:~:text=A%20nuclear%20reactor%2C%20formerly%20known,and%20in%20nuclear%20marine%20propulsion.">fission nuclear reactor</a> works by harnessing the power of fissile atoms. When uranium-235 absorbs a neutron it has a chance to fission and split, releasing fission products, neutrons, and kinetic energy. This energy heats a coolant medium which is usually piped to a heat exchanger and then a steam turbine, which generates electricity. My facility is home to a TRIGA reactor that doesn’t produce any electricity — it’s used purely for research and experimentation.</p><blockquote><a href="https://xkcd.com/1162/">Fun fact</a>: one kilogram of U-235 has about <a href="https://web.archive.org/web/20110927181836/http://bioenergy.ornl.gov/papers/misc/energy_conv.html">3 million times more energy</a> than one kilogram of coal. Oh, and the fission reaction produces no carbon emissions. (I’m not biased at all.)</blockquote><p>A <a href="https://en.wikipedia.org/wiki/TRIGA">TRIGA</a> reactor is unique in many ways when compared to a commercial reactor, one of which being its capability to perform a “pulse”. The highly negative reactivity coefficient of the fuel means that as temperature increases, the reactivity — and thus the rate of fission chain reactions — decreases. This means that the reactor is self-limiting in terms of power level and, due to the design of the fuel, will physically shut itself down after a pulse with no input from the operator. (That’s why they let people like me operate it!)</p><p>A pulse works by pneumatically (using pressurized air) ejecting one of the control rods from the core of the reactor, which causes a rapid increase in power level. The following happens in the span of a <em>few milliseconds</em>:</p><ul><li>The control rod is shot vertically upwards out of the core.</li><li>The power level increases from around 50 W to up to 2000 MW.</li><li>At this high power level, the prompt negative feedback effect of the fuel provides negative reactivity to the core, which shuts itself down.</li></ul><p>At this point the control rod may still be on its way out of the core but will subsequently fall back down due to gravity. You end up with a power response function <em>P(t) </em>that looks something like <strong>Figure 2 </strong>below — power increases as the control rod is ejected, then rapidly decreases with the addition of negative reactivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cpcna8tBBF7JsfPK.jpg" /><figcaption><strong>Figure 2.</strong> Reactor power, reactivity, and energy as a function of time during a pulse. <a href="http://www.rcp.ijs.si/ric/pulse_operation-s.html">Source</a>: M. Ravnika</figcaption></figure><p>While pulsing has numerous research applications, it works especially well to simulate, on a very small scale, the <em>radiation </em>emitted from a nuclear explosion. Specifically, we’re observing how neutrons and gamma rays interact with electronics on an atomic level. Say you were designing a new electronic component to be used to control some portion of a nuclear weapon system. How certain are you that your electronics will survive a nearby nuclear detonation? What damage will the integrated circuitry sustain by sitting next to a radioactive warhead in storage for 10 years? How will that damage affect the functionality of your component? Or what if, instead, you’re designing a CPU chip to be used in a new fighter jet. Is the flight control system that’s enabled by your CPU going to fail when exposed to a certain amount of radiation? You can see how these questions are of serious importance. Combine that with the fact that a true nuclear detonation is a bit of an ordeal to set up and has a number <a href="https://www.ctbto.org/nuclear-testing/the-effects-of-nuclear-testing/general-overview-of-theeffects-of-nuclear-testing/">issues</a> (not to mention banned by the <a href="https://en.wikipedia.org/wiki/Comprehensive_Nuclear-Test-Ban_Treaty">Comprehensive Nuclear-Test-Ban Treaty</a>) and you’ll soon agree that reactor pulsing is a key capability.</p><blockquote>NOTE: It’s worth elucidating that this pulse is only generating radiation. In this type of experiment, <strong>nothing is being exploded</strong>. We’re simply exposing a sample to high levels of radiation in an extremely controlled environment that’s designed for such a task.</blockquote><p>The maximum power level reached by a pulse can be chosen by the operator based on the reactivity “worth” of the control rods. For many nuclear reactors this worth is measured in units of <em>dollars</em>, and since it’s outside of the scope of this article to explain why we use this seemingly weird unit, you can read all about it <a href="https://en.wikipedia.org/wiki/Dollar_(reactivity)#:~:text=A%20dollar%20is%20a%20unit,means%20a%20steady%20reaction%20rate.">here</a> if you wish.</p><p>Depending on the experiment at hand, a specific pulse power level might be desired. The positions of the control rods in the core determine the power level at any given time. The dataset that I’ve compiled from my own work at this reactor consists of these values and a handful of others, described below:</p><ul><li><strong>Date</strong>. The specific datetime formatted date that the pulse occurred on.</li><li><strong>Estimated Reactivity</strong>. The <em>estimated </em>reactivity insertion amount, in dollars, of the pulse. This estimate is found by consulting the <a href="https://ansn.iaea.org/Common/documents/Training/TRIGA%20Reactors%20(Safety%20and%20Technology)/chapter2/physics122.htm">integral worth</a> of a certain control rod. Example: an experimenter will request a pulse worth $2.00. The operator will find the position to place the control rod at based on the total integral worth of said control rod.</li><li><strong>Rod Positions</strong>. There are four control rods in the core — transient, shim 1, shim 2, and the regulating rod. Labeled “Trans, S1, S2, Reg” in my dataset, these values are related to the physical location of the control rods in the core. They range from 0 to 960, where 0 is fully inserted into the core and 960 is fully removed.</li><li><strong>Peak Power</strong>. Measured in MW.</li><li><strong>Total Energy.</strong> Measured in MW seconds.</li><li><strong>Peak Temperature</strong>. Measured in degrees Celsius, this is the peak temperature reached in an instrumented fuel element (IFE). A few fuel rods have thermocouples embedded inside of them to monitor the temperature of the core.</li><li><strong>Calculated Reactivity</strong>. This is the “true” reactivity value, which generally differs from the estimated reactivity by a certain amount. It’s calculated automatically by the reactor console.</li></ul><p>In the rest of this post, I’ll analyze the dataset to see what insights I can glean. In addition, I’ll apply a linear regression machine learning model to predict <em>calculated reactivity</em><strong> </strong>based on <em>estimated reactivity</em><strong> </strong>and <em>rod positions</em>. This predictive model will help us to be more accurate with our pulse powers (to a certain extent — more thoughts on that later) and increase the efficacy and veracity of our experiments. <strong>My end goal is to make our pulses more accurate and repeatable in terms of the amount of radiation exposure given to a specific sample.</strong></p><h3><strong>Exploratory Data Analysis (EDA)</strong></h3><p>I went ahead and cleaned the data beforehand, so I’ll spare you the details. In most cases, the cleaning process consists of removing incorrect or incomplete entries from the dataset. There were a lot of manual entry errors (typos) that I had to identify and cleanse, as well as some missing data points that I either completely removed or replaced with average values.</p><p>Once I have my clean data, the first thing I’ll do is import the relevant libraries and load up my DataFrame:</p><pre>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import numpy as np</pre><pre>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br>from sklearn import metrics<br>from sklearn.metrics import r2_score</pre><pre>df = pd.read_excel(&#39;Pulse_Data_2021_NO_NULL.xlsx&#39;, )</pre><p>After that, I always like to use three main functions to learn the general characteristics of my data — <em>.head()</em>, <em>.info()</em>, and <em>.describe().</em></p><p><em>.head() </em>just shows the top few rows of the DataFrame, and we can see how the data is generally structured:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvibU7MR4vXJMeHBmNVrAA.png" /><figcaption><strong>Figure 3</strong>. df.head() output</figcaption></figure><p><em>.info() </em>outputs the number of entries in the DataFrame, the columns names, the number of null entries in each column, and the data type for each column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5UiW6aBZinTTPxUK3vx3A.png" /><figcaption><strong>Figure 4</strong>. df.info() output</figcaption></figure><p>And <em>.describe() </em>provides some summary analysis of the data itself — mean, standard deviation, quartiles, etc. of each column. I like to transpose it for readability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euuxhcALgiQSKgcTt6iFPg.png" /><figcaption><strong>Figure 5</strong>. df.describe() output</figcaption></figure><p>The next step of my EDA is to just start graphing whatever might make sense. For instance, I thought it would be interesting to see the relationship between calculated reactivity and peak power, so I made a simple scatterplot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnXLzY6DvQZMMZavnxr9Mw.png" /><figcaption><strong>Figure 6</strong>. Scatterplot of calculated reactivity vs. peak power.</figcaption></figure><p>There’s a clear exponential relationship between the two variables which is consistent with the principles of reactor kinetics that drive this operation. The graph is also useful in that it identifies potential outlier points — either weird behaviors of the reactor or, more likely, incorrect entries. From this graph, I found additional fat-fingered entries that needed to be cleaned or removed.</p><p>A correlation heatmap is another useful tool that can be applied to most numerical datasets. <strong>Figure 7 </strong>below depicts which columns are closely correlated to each other, with values ranging from -1 to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCAc5aFUDiVOMuEj3g2vdA.png" /><figcaption><strong>Figure 7. </strong>Correlation heatmap.</figcaption></figure><p>To interpret this heatmap, look for values that are high (close to one). The diagonal line of ones is an artifact of the layout of the heatmap, and just tells me that each feature is directly correlated to itself. Makes sense. S1 and S2 have a correlation of 0.99, which also makes sense because these two control rods are almost always in the exact same vertical position when pulsing. The feature I’m most interested in, calculated reactivity, is highly correlated with peak temperature, total energy, and peak power. This also seems logical, because as reactivity increases, I expect each of those features to increase as well.</p><p>Since I’m trying to improve the predictive accuracy of the estimated reactivity value, my next step is to compare a distribution of it versus the calculated reactivity. To accomplish this, I overlay two histograms and do some formatting to make it look nice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8UrZOJqYSAijkUB4fRVzQ.png" /><figcaption><strong>Figure 8</strong>. Reactivity histograms.</figcaption></figure><p>There are discrete pulse reactivity values that we generally use when deciding how “large” of a pulse we want. <strong>Figure 8 </strong>reflects this clearly, showing that $1.50, $2.00, $2.50, and $3.00 are common estimated values. One would expect a somewhat normal distribution of calculated reactivity values around each of the estimated reactivity values, which is shown (albeit loosely) by the blue graph.</p><p>Again looking at <strong>Figure 8, </strong>it appears that the estimated reactivity is skewed slightly higher than the calculated counterpart. What this means is that generally speaking, if you request a $2.00 pulse, you’ll actually get a value a bit less than that. I can quantify this by simply subtracting the two columns of data and finding the mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6S450miJ_iS-Poq8ePI3Q.png" /><figcaption><strong>Figure 9. Mean difference in reactivity values.</strong></figcaption></figure><p>Which demonstrates that, on average, the “true” calculated reactivity is $0.16 lower than the estimated reactivity.</p><p>Lastly, I generated a graph that serves as an interesting proxy for reactor utilization over time. This reactor first started up (AKA “went critical”) in 1992, and a graph of the number of pulses per year since then offers some deep rabbit holes to go down:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a59hZDq0kmkzEyf0BAe76g.png" /><figcaption><strong>Figure 10. </strong>Reactor pulse frequency on a yearly basis.</figcaption></figure><p>Questions that could arise from <strong>Figure 10</strong> include:</p><ul><li>Why were there so few pulses from 1994–1996, and from 2013–2014?</li><li>Was there an administrative change that affected the type of experiments run at this facility?</li><li>Were there any new national or university research developments that required additional pulses?</li><li>What experiments were happening in 2000 and 2020–20201 (now) that required so many pulses, and why were there no such experiments in between?</li></ul><p>It’s amazing how much insight can be garnered from a few small graphs.</p><h3><strong>Predictive Modelling</strong></h3><p>The task of predicting the <em>calculated reactivity </em>is fit (pun intended) for a linear regression model. This is considered a supervised machine learning model because the data is already labeled (x and y values are provided to train the model). It’s technically a multiple regression model (the definition of which encompasses linear regression) because <strong>it uses multiple independent variables (<em>Est_Reactivity, Trans, S1, S2, Reg</em>) to predict the outcome of the dependent variable (<em>Calc_Reactivity</em>).</strong></p><blockquote>NOTE: this linear regression model assumes that the relationship between the dependent variable and the independent variables are <strong>linear. </strong>Estimated reactivity is clearly linearly related to calculated reactivity, but the same cannot be said about our other independent variables (Trans, S1, S2, Reg). There is also clear multicollinearity among the independent variables, as rod placements (S1, S2, Reg) are highly correlated. For these reasons, a linear regression model may not be the best option. Further exploration of the independent variables is needed to know for sure, but polynomial regression or ridge regression might be a good fit. The bottom line is that it’s important to understand the assumptions and limitations of your model and how they vary across different techniques.</blockquote><p>I first split the data into a training set and testing set to ensure an unbiased evaluation of the model. I then instantiate the model and fit the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8E4A4Nq-_W2LM_EGazujxg.png" /><figcaption><strong>Figure 11. </strong>Code that demonstrates a train-test split and model fitting.</figcaption></figure><p>Once the model has been fit, I use the testing data to compare the model output against the expected values. A completely straight line would indicate a perfect model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIbYCOh4dPXgv3UEFqfu3A.png" /><figcaption><strong>Figure 12. </strong>Scatterplot demonstrating model output versus true data.</figcaption></figure><p>With a few notable outliers, the model does a great job of accurate prediction. Depending on the use case of the model, it may be worth investigating the data even further to determine where these outliers are coming from and how to mitigate them to improve model accuracy. In my case, this model is sufficient. I can even quantify the “goodness of fit” by calculating the R-squared value for my model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDPjb24lMtka5-8O73HOTA.png" /><figcaption><strong>Figure 13. </strong>R-squared value of 0.91.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pddVwmmNdOILOz1HUIGIw.png" /><figcaption><strong>Figure 14. </strong>Residuals plot.</figcaption></figure><p>R-squared is the proportion of variance in the dependent variable that’s predictable from the independent variable. Expressed as a percentage, 91% of the variance in the estimated reactivity of any given pulse can be explained with our input values. The takeaway is that this is a great model for our purposes. That being said, there’s one more check I can do to learn about the model. <strong>Figure 14 </strong>to the left is a histogram of residuals, or the distance between any given data point and the regression line of best fit. The graph indicates that there is a normal distribution of the random error around zero, which is good. If this were not the case, then we might have an issue with our model and/or dataset. Again there are notable outliers, but nothing to be concerned about when backed up with our impressive R-squared score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*S9Y5U3r_GJMVsdKY6lcVeg.gif" /><figcaption><strong>Figure 15.</strong> A pulse recorded in slow motion (originally 240fps). Source: me (Walker Payne)</figcaption></figure><h3>Conclusions (and limitations)</h3><p>With this model, I can now accurately predict a pulse reactivity value based on reactor parameters such as control rod positions and rod worth. <strong>Repeatability is important for all types of experimentation, and this model will help tighten our pulse values and ensure similar radiation exposure for each component being irradiated.</strong></p><blockquote>NOTE: The model does have a number of limitations that might be obvious to those with reactor kinetics and operations knowledge. Namely, the model has no knowledge of previous operations and the extremely important buildup of <a href="https://www.nuclear-power.net/nuclear-power/reactor-physics/reactor-operation/fuel-burnup/neutron-poisons-reactor-poisoning/#:~:text=Fission%20products%20are%20of%20concern,are%20known%20as%20neutron%20poisons.">fission product poisons.</a> Xenon-135 is created (and burned off) over time as the reactor operates and significantly affects neutron absorption and reactor behavior.</blockquote><blockquote>EDIT: After testing the model with brand new data before a pulse, the predicted reactivity was less than 3% off from the “true” reactivity calculated by the reactor console. Success!</blockquote><p>If you enjoyed this post, feel free to check out some of my others and let me know what you think in the comments. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1dae16fb081" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/applying-machine-learning-and-exploratory-data-analysis-to-nuclear-reactor-kinetics-d1dae16fb081">Applying Machine Learning to Nuclear Reactor Kinetics</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[Over-Analyzing Wildlife Activity With Python]]></title>
            <link>https://medium.com/data-science/over-analyzing-wildlife-activity-with-a-trail-camera-and-python-f7aaebbdbd01?source=rss-c693b9460084------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7aaebbdbd01</guid>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[wildlife]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Walker Payne]]></dc:creator>
            <pubDate>Wed, 03 Feb 2021 21:31:12 GMT</pubDate>
            <atom:updated>2021-09-23T18:52:46.437Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>What do you mean, “just go outside and look at the deer yourself”? Was that an option?!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_-s7Tl3YSCD_DqBb7NwUw.png" /><figcaption>Bushnell trail camera image of a big beautiful buck, with Amazon Rekognition Image tags underneath.</figcaption></figure><p>At the intersection of hunting and data analytics, there’s a crazy person out there who would look for ways to utilize their technological skills to improve their odds of a successful deer hunt. A person who straddles both seemingly dichotomous worlds of enjoying the outdoors and writing largely superfluous code. A person who, in an effort to learn more about nature, ended up spending hours upon hours pouring over his laptop.</p><p>That person is me.</p><p>A few months ago I set up a cellular-enabled trail camera to see the comings and goings of deer and other curious critters on some family land in central Texas. The device is a <a href="https://www.amazon.com/Bushnell-Impulse-Cellular-Verizon-119900V/dp/B07F46ZLBJ/ref=sr_1_2?dchild=1&amp;keywords=bushnell%2Bimpulse%2Bcellular&amp;qid=1610741644&amp;sr=8-2&amp;th=1">Bushnell Impulse Cellular Camera</a> that you can interact with via a webpage. When I went to inspect the images it had taken, I was expecting a simple repository — nothing more than a dump of pictures and the time that they were taken. You can imagine my surprise when I discovered these additional data points:</p><ul><li>Amazon Rekognition Image tags</li><li>Temperature</li><li>Moon phase</li><li>Wind direction</li><li>Wind speed</li><li>Barometric pressure</li></ul><p>The year 2020 had left me with a lot of free time that I spent, in part, learning concepts in data analysis using Python. This camera afforded me an interesting opportunity , a sudden wealth of personally-relevant data just waiting to be analyzed. What better way to test my knowledge than to apply it to a real world dataset?</p><p>When the idea hit me, I sat down in front of my laptop and prepared myself to do what any budding new analyst does when trying to prove their worth — solve a problem that doesn’t matter by drawing unnecessary conclusions from incomplete data. Let’s go save the world.</p><h3><strong>The Question(s)</strong></h3><p>Before we get started, I should probably define what it is that we’re looking for — what questions we’re trying to answer.</p><p>Firstly, I’d like to know <strong>when the deer are most active. </strong>This could be in terms of hours of the day, or days/weeks of the year. This will help me determine the most promising days of the year (within the legal deer hunting season) to go look for them. I’d also like to know <strong>which of the data points listed above is most relevant to deer activity</strong>. For instance, how much do deer care about the phase of the moon? Do they get nervous when the wind is coming from the south rather than the north? I’m sure we all have our guesses on which <em>features </em>are most <em>important</em>, but it’ll be interesting to see the data to back it up.</p><h3><strong>The Data</strong></h3><p>I could see the information I wanted, but I didn’t like the thought of manually entering the data for each and every picture into hundreds of rows on an excel spreadsheet. There must be a better way…</p><p>I decided to use Python’s HTTP requests library to gather the data after I reverse-engineered the Bushnell Javascript API to know what to look for.</p><p>I was able to piece together a script that scrapes the website and spits out a nice excel spreadsheet with my data. I’ll spare you the details — if you’re curious, check out the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be86af717c73372c6e2b3e9ddc61afd9/href">https://medium.com/media/be86af717c73372c6e2b3e9ddc61afd9/href</a></iframe><p>With the below excel spreadsheet, we’re ready to start analyzing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NW_ud4XaboOLBfIbgxdpKw.png" /><figcaption>Screenshot of the excel spreadsheet output.</figcaption></figure><h3><strong>The Exploratory Data Analysis</strong></h3><p>The first thing I did was import the libraries that I planned to use and convert the spreadsheet into a DataFrame.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import scipy.stats as stats<br>%matplotlib inline </pre><pre>df = pd.read_excel(&#39;SPREADSHEET_NAME_HERE.xlsx&#39;, index_col = 0)</pre><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ak7MFed2x0tXnPNtePMMuQ.png" /><figcaption>DataFrame information.</figcaption></figure><p>Here we can see each of our column names as well as the number of rows — it looks like we’ve gotten over 1700 pictures since I started the camera. Next, I wanted to be able to distinguish between the pictures that have deer and the pictures that were triggered by other furry friends. I added a new column that populates with a 1 or a 0 if the picture contains a deer.</p><blockquote>If you looked closely at the excel spreadsheet, you might notice some odd tags… Seeing as our ranch is in central Texas, I feel fairly confident that there are no elk, impala, or antelope to be seen. Instead, it appears that Amazon Rekognition is misidentifying these deer. With that in mind, I was sure to look for those additional animal tags in the code below and treat them as deer.</blockquote><pre># add a column that determines if Deer is in the string and will  #populate as True or False or NaN<br>df[&#39;contains_deer&#39;] = df[&#39;tag_name_string&#39;].str.contains(&#39;Deer|Antelope|Elk|Impala&#39;)</pre><pre>#replace Trues and Falses with 1s and 0s<br>df[&#39;contains_deer&#39;] = df[&#39;contains_deer&#39;].replace({True: 1, False:0})</pre><pre>#fill in the contains_deer column with 0&#39;s if no tags were present (NaN in tag_name_string)<br>df[&#39;contains_deer&#39;] = df[&#39;contains_deer&#39;].fillna(0)</pre><pre>#the df.replace from above defaults to float values (1.0 and 0.0), #so change them to ints (1 and 0)<br>df[&#39;contains_deer&#39;] = df[&#39;contains_deer&#39;].astype(int)</pre><p>I used the new <em>contains_deer</em> column to easily differentiate between the pictures that have deer, and those that don’t. This binary classification will come in handy later on…</p><p>To explore the proportion of pictures taken due to deer versus otherwise, I used the “hue” feature of a Seaborn countplot:</p><pre>sns.countplot(data = df, x = &#39;date&#39;, hue = &#39;contains_deer&#39;, palette = &#39;Paired&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfvWIMxssETSFdZ5_ZBEeA.png" /></figure><p>The light blue bars represent images that don’t have any deer in them (at least, according to AWS). <strong>We can see that, for any given day, there are WAY more pictures taken of things other than deer.</strong> But if not deer, what else is out there? What could possibly be accounting for so much precious memory on my camera?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0ieBetbaVTdLgMMbhCqUQ.jpeg" /></figure><p>Enter the trash panda. These guys are out every night stealing corn from the feeder like their lives depend on it (on some level, I suppose they do) and account for hundreds of pictures. Either way, now that we know why there are so many pictures taken that are irrelevant to my question(s), we can get rid of those and graph just the deer.</p><p>Before I show that, here’s a brief interlude with some other interesting pictures taken by the camera:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41uHJgXO2f4LEZb8Rs9iLA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSMRd6cS44nlG8WcYHYnsA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggPjB0goXK2AZVit7m75iA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5upwN2UyOjAnekCHkoDBGg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJ9aILDIpXwURqnQGmuxXA.jpeg" /><figcaption>Bobcats, bucks, skunks, and something even rarer altogether — snow!</figcaption></figure><p>On to that graph:</p><pre>sns.countplot(x = &#39;date&#39;, data = df2, palette = &#39;rainbow&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9E3GfDouKHhPC5fqhk0ZQ.png" /><figcaption>Camera activations tagged with “Deer” over time.</figcaption></figure><p>Now here’s where things start to get interesting. The above graph shows the number of tagged pictures of deer taken per day. Though there’s a decent amount of variability (anywhere from 1 to 12 pictures per day, generally), you might notice the increase in activity from the 13th to the 19th of November. The 15th, 17th, and 18th all have greater than 15 pictures!</p><p>If you noticed that large spike, then you should also have noticed the obvious lack of pictures on the 16th — smack in the middle of what appears to be the most active set of days for our deer friends. What gives?</p><p>It doesn’t take hours of work writing scripts and analyzing data to know that deer movement is heavily dependent on weather. To explore this, I decided to check the average temperatures for each day and overlay them on the activity graph. Here are the results:</p><pre>df.groupby([&#39;date&#39;]).mean()[&#39;temperature&#39;].plot(kind = &#39;line&#39;, ax = ax, linestyle = &#39;--&#39;, marker = &#39;o&#39;, markerfacecolor = &#39;c&#39;, ylabel = &#39;Temperature (F)&#39;, xlabel = &#39;Date&#39;) #line graph of avg temp per day</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2vqj-xJHflQ7If1ITMXDBA.png" /></figure><p>Lo and behold, <strong>the average temperature on the 16th was actually 11 degrees colder than the five day moving average temperature around that date</strong>. It looks like we’ve got a pretty compelling explanation for this oddity: a cold front blew in and caused the deer to take shelter, interrupting their natural tendency to be active during this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*yjpoWQFItGUPQcdugjMwXA.png" /><figcaption>Average daily temperature for the selected period. Note that on the 16th, it was 44 degrees — well below that of the bordering days.</figcaption></figure><p>There’s nothing better than arriving at a conclusion on your own, then finding outside data that supports your conclusion perfectly. The dates that we identified as peak activity at my ranch (<strong>November 13th through November 19th</strong>) fall neatly inside <a href="https://tpwd.texas.gov/huntwild/hunt/planning/rut_whitetailed_deer/#E11E5">Texas Parks and Wildlife’s predictions</a> for peak “rut” — the period when deer breed and are most active. For this area (Edwards Plateau), they found the rut to be between <strong>November 7th and November 24th</strong>. Our interpretation of the data is confirmed!</p><p>This analysis has given me some actionable insight. Next year, I’ll plan a trip to be out there during this period of high activity. I’ll also watch the radar, keeping in mind that even the most active periods can be severely impacted by inclement changes in weather.</p><blockquote>Sure, I could have just looked at the TPW website in the first place and gone out during peak rut, but where’s the fun in that?</blockquote><h3>Training a Random Forest Machine Learning Model</h3><p>If you thought the analysis I just did was unnecessary, you’re gonna love what’s next. In this section, I train a machine learning model to predict whether or not a deer will be present based on our quantitative data — temperature, windspeed, atmospheric pressure, etc.</p><blockquote>Note: If you don’t know what a random forest classifier is, that’s fine. Here’s a link to a few articles that might help explain it: <a href="https://stackabuse.com/random-forest-algorithm-with-python-and-scikit-learn/">here</a> or <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">here</a>.</blockquote><p>The first thing I did was import a Scikit-learn library and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html">split the data</a> into a training set and a testing set.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X = df.drop(columns = [&#39;filename&#39;, &#39;date&#39;, &#39;time&#39;, &#39;tag_name_string&#39;, &#39;contains_deer&#39;])<br>y = df[&#39;contains_deer&#39;]</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)</pre><p>The <em>X </em>variable is the data I used for my model and the <em>y </em>variable is what I’m trying to predict.</p><p>The below code contains pretty much everything else I needed to do — import some more libraries, train the model, and print out the results (in a classification report).</p><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report, confusion_matrix<br>from sklearn.inspection import permutation_importance</pre><pre>rf = RandomForestClassifier(n_estimators = 600)</pre><pre>rf.fit(X_train, y_train)<br>pred_rfc = rf.predict(X_test)</pre><pre>print(classification_report(y_test, pred_rfc))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Y20TIA6aKLWdOMivXAXwA.png" /><figcaption>Classification report for the random forest model.</figcaption></figure><p>The above classification report shows us (among other things) how accurate the model is. Since the model itself is totally unnecessary in this context, I’ll only highlight the <a href="https://www.scikit-yb.org/en/latest/api/classifier/classification_report.html">F1 score</a> — it’s the harmonic mean of the recall and precision scores. In more layman terms, it tells you what percentage of positive predictions made by the model were correct. <strong>I could now theoretically provide a set of data (temperature, barometric pressure, wind speed, etc.) to the model and let it predict whether or not a deer will be present based on said data.</strong></p><p>Like I said before, time and time again, this is all totally unnecessary. What I was really curious about was if any of the data points have a disproportionate effect on predicting deer activity. A <a href="https://machinelearningmastery.com/calculate-feature-importance-with-python/">feature importance</a> graph will show us which parameters of the model are most important when making predictions.</p><pre>feature_importance = pd.DataFrame(sorted(zip(rf.feature_importances_, X.columns)), columns=[&#39;Value&#39;,&#39;Feature&#39;])</pre><pre>sns.barplot(x=&quot;Value&quot;, y=&quot;Feature&quot;, data=feature_importance.sort_values(by=&quot;Value&quot;, ascending=False))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9x9Ji4KCRx7Ecv13e9JCEw.png" /><figcaption>Feature Importance graph.</figcaption></figure><p>With the above graph, it’s clear which input parameters are most important. An important caveat is that this analysis won’t work (as it stands currently) for “circular” data. For example, <em>windDirection</em> is listed as the most important feature of our model. The data points are 0 to 359 degrees to indicate the prevailing wind direction. A 0 degree wind direction and a 359 degree wind direction are nearly the same, but the model treats them as maximally different values. For this reason, we should ignore the <em>windDirection </em>and <em>moonPhase </em>features (and consider removing them from our model entirely).</p><p>With those erroneous features removed, we now can see that temperature is the most important predictive feature for our model, followed closely by pressure. Wind speed is a much less important feature when trying to predict deer behavior. This serves to validate our earlier insight about why deer activity suddenly dropped during a fast-moving cold front.</p><p>If you made it this far, congratulations. I hope you learned something about data analytics or wildlife activity or both. Next time you get your hands on some data about deer, maybe you too can carry out some insightful analysis. Otherwise, you know who to call.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7aaebbdbd01" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/over-analyzing-wildlife-activity-with-a-trail-camera-and-python-f7aaebbdbd01">Over-Analyzing Wildlife Activity 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[Using Decision Trees and Random Forests to Predict Lending Profitability]]></title>
            <link>https://medium.com/swlh/using-decision-trees-and-random-forests-to-predict-lending-profitability-c208b8106cb5?source=rss-c693b9460084------2</link>
            <guid isPermaLink="false">https://medium.com/p/c208b8106cb5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Walker Payne]]></dc:creator>
            <pubDate>Wed, 06 Jan 2021 02:30:05 GMT</pubDate>
            <atom:updated>2021-01-08T07:30:07.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Su_uqZVJh8_DufNEo8wVTA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/s/photos/technology?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This project uses lending data from LendingClub.com to determine if potential customers will successfully pay off a loan after entering a lending agreement. <strong>Our main goal will be to compare two models: one created using a single decision tree, the other using a random forest.</strong></p><blockquote>Note: This project was covered in a <strong>Udemy “Python for Data Science &amp; Machine Learning” </strong>course. My code and explanations are shown below. This post is for demonstration purposes only and is not meant to be a tutorial or exhaustive guide.</blockquote><p>We’ll start off with the usual analytics workflow — import some relevant libraries, read in the data (from a course-provided CSV file), and do some exploratory data analysis (EDA) to see what exactly we’re working with.</p><h3><strong>Importing Libraries</strong></h3><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>%matplotlib inline #this line is for viewing plots in Jupyter</pre><h3><strong>Reading the Data and Viewing the DataFrame</strong></h3><pre>loans = pd.read_csv(&#39;loan_data.csv&#39;) #reads a CSV into a DataFrame<br>loans.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*-rY3Ybcpi2zhaydNsbn1sA.png" /></figure><p>The <em>.info()</em> call shows us the names of the columns (0–13) and the number of rows (9578), among other things. The most relevant columns that we’ll be checking out today are:</p><ul><li><strong>int.rate: </strong>The interest rate of a loan. Borrowers that are deemed “more risky” would be subject to a higher interest rate loan.</li><li><strong>fico</strong>: the customers FICO score.</li><li><strong>credit.policy</strong>: a 1 if the customer met the lending criteria, and a 0 if not.</li><li><strong>purpose:</strong> the purpose of the loan — whether that’s to pay off a credit card, pay student loans, debt consolidation, etc.</li><li><strong>not.fully.paid</strong>: our main column of interest that we’ll be trying to predict. <strong>We want to see if our use of various machine learning algorithms can help us to predict whether or not someone will pay back their loan based on the given data.</strong> This is either a 1 or a 0, 1 meaning the customer did <strong>not </strong>pay their loan back on time and in full.</li></ul><p>The rest of the columns are important to our future models but aren’t necessary to explain here. The main idea is that, based on data for a specific customer (their FICO score, how many days the credit line has been open, the size of each monthly installment, their public records, etc.) we should be able to predict how likely they are to pay their loan off in full.</p><p>This has obvious business-driven importance — if our model assigns someone a score of 1 for the <em>not.fully.paid</em> variable, then we may want to re-evaluate our loan agreement with them and find some way to intervene. Correctly identifying (with a reasonable amount of accuracy) those who are likely to default on a loan is a top priority of any loan origination business (or private individual) and could significantly affect the bottom line profitability of the company.</p><h3><strong>Exploratory Data Analysis</strong></h3><p>Let’s do some EDA. The following graph compares the FICO scores of two groups — the people who did not meet the lending criteria versus those who did. We’ll utilize some built-in Pandas functionality to overlay two histograms.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d9e3d2bfdab282f956dd04d677c0b08/href">https://medium.com/media/4d9e3d2bfdab282f956dd04d677c0b08/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vf5GNRJ5FG-2ZyFAoz71ng.png" /></figure><p>The above graph demonstrates the distribution of FICO scores in this study. Though nothing revelational, it shows us that there were more people who passed the lending process than failed it, and that the average FICO score tends to be lower for people who failed.</p><p>Next, we’ll use a Seaborn countplot to visualize the various reasons or <em>purposes</em> for taking out a loan, and if that <em>purpose </em>affects the default rate.</p><pre>plt.figure(figsize=(12,7))<br>sns.countplot(x = &#39;purpose&#39;, data = loans, hue = &#39;not.fully.paid&#39;, palette = &#39;pastel&#39;)<br>plt.title(&#39;Purposes of Loan Origination&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*veDTGe0jJ6XfIdKrc2VFog.png" /></figure><p>Debt consolidation appears to be the primary purpose for taking out a loan, and each purpose has a (mostly) similar ratio of success to failure.</p><p>Now we’ll use a jointplot to visually confirm what we might expect regarding interests rates and FICO scores — as your FICO score increases, the interest you pay on a loan should be more favorable.</p><pre>sns.jointplot(x = &#39;fico&#39;, y = &#39;int.rate&#39;, data = loans, color = &#39;royalblue&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xo3Vfm4NrOx11ermzAN8VQ.png" /></figure><p>To finish off our EDA, lets see what trends there are when comparing <em>not.fully.paid </em>and <em>credit.policy</em>. We can use an lmplot to fit regression models across conditional subsets of a dataset. It sounds complicated — what we’re really doing is allowing multiple variables to be compared in one figure.</p><pre>sns.lmplot(x = &#39;fico&#39;, y = &#39;int.rate&#39;, data = loans, col = &#39;not.fully.paid&#39;, hue = &#39;credit.policy&#39;, markers = [&#39;o&#39;, &#39;x&#39;], palette = &#39;mako&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmIW4pR9xA99CMPDEwq99A.png" /></figure><p>In this case, we want to see if the relationship between FICO scores and interest rate change at all depending on whether or not the customer paid back their loan. From the above graphs we can see that the trend (indicated by the regression line of best fit) remains largely the same across the split.</p><h3><strong>Preparing Data For Use With Machine Learning Algorithms</strong></h3><p>So now we’re ready to get started prepping the data. Before we can fully utilize the scikit-learn ML algos, we need to <strong>replace any categorical columns with dummy variables so that each data point is represented numerically rather than with words/strings</strong>. Recall the image from when we first checked the DataFrame:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*-rY3Ybcpi2zhaydNsbn1sA.png" /></figure><p>Notice how column 1, <em>purpose</em>, is listed as an “object”— non-numerical. We can use <em>pd.get_dummies() </em>to create a new DataFrame with additional columns, like so:</p><pre>final_data = pd.get_dummies(data = loans, columns = [&#39;purpose&#39;], drop_first = True)</pre><pre>final_data.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjdiU0ii1vq_l1d_cZX5oQ.png" /></figure><p>Now we have 19 columns instead of 14 — the 6 new columns (with the original <em>purpose </em>column removed) each represent one purpose, with a “1” in only one of the last 6 columns to indicate which purpose applies to each customer (see below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dY1xm1zRdGhL-ncCej5QmQ.png" /></figure><h3><strong>Train-Test Split</strong></h3><p>The train-test split procedure is used when you want to evaluate the performance of a supervised machine learning algorithm. You split the data into two subsets. The “train” subset will be used to fit the machine learning model, where the “test” subset will be used to, you guessed it, test the performance of the model.</p><p>This is an important distinction. You wouldn’t want to train the model <strong>and </strong>test the model using the same data — that would be cheating, since the model would have already seen the data it’s being asked to predict. More technically, using a train-test split procedure avoids <strong>overfitting</strong>, where a model has near perfect accuracy when handling training data.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X = final_data.drop(&#39;not.fully.paid&#39;, axis = 1)<br>y = final_data[&#39;not.fully.paid&#39;]</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)</pre><p>Note that we’ve split our data into two variables, X and y, because the y value is what we’re interested in predicting — in this case, only whether or not the customer has paid back their loan. The X variable should contain everything else in the dataset.</p><h3><strong>Decision Tree Model</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*n8UMW6qDTKXV8Ruv.jpeg" /><figcaption>An example visualization of a decision tree from <a href="https://dev.to/nexttech/classification-and-regression-analysis-with-decision-trees-jgp">Next Tech</a>.</figcaption></figure><p>The code behind a decision tree is relatively straightforward. We won’t get in to how the model actually works — you can <a href="https://scikit-learn.org/stable/modules/tree.html">read all about it</a> in the scikit-learn documentation. Below, we’ll fit the model and then print out a classification report to assess its performance.</p><pre>from sklearn.tree import DecisionTreeClassifier</pre><pre>dtree = DecisionTreeClassifier()<br>dtree.fit(X_train, y_train)</pre><pre><br>from sklearn.metrics import classification_report, confusion_matrix</pre><pre>predictions = dtree.predict(X_test)<br>print(classification_report(y_test, predictions))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWZP81W6mgpSNwZGU7vbow.png" /><figcaption>Classification report for the decision tree model</figcaption></figure><p>We’ll tackle the classification report by looking at the first two columns. <strong>Precision </strong>is the proportion of predictions in that class that are true. This model accurately predicted 86% of the 0’s and 19% of the 1’s. Remember that our interest is in predicting the 1’s — the people who did not repay their loans. <strong>Recall </strong>is the ability of the model to correctly identify positive samples. This model correctly identified 24% of the true 1’s in our test data.</p><h3><strong>Random Forest Model</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*i0o8mjFfCn-uD79-F1Cqkw.png" /><figcaption>Visualization of a random forest from <a href="https://en.wikipedia.org/wiki/Random_forest">Wikipedia</a>.</figcaption></figure><p>The random forest model creates a combined output of multiple randomly generated decision trees (at the cost of greater training time). As the name implies, the forest is made up of multiple trees. A random forest does not rely on <a href="https://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html"><strong>feature importance</strong></a><strong> </strong>that can often be a crux of singular decision tree models.</p><pre>from sklearn.ensemble import RandomForestClassifier<br>rf = RandomForestClassifier(n_estimators = 600)<br>rf.fit(X_train,y_train)</pre><pre>predictions_rfc = rf.predict(X_test)<br>print(classification_report(y_test, predictions_rfc))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SP_OFk91jrgqJGdxh9iWzA.png" /></figure><p>Comparing the two classification reports, it’s not immediately obvious which model performed “better” than the other. <strong>This is where you’ll require an intuitive understanding of the problem, the dataset, and the potential strengths and weakness of each model type.</strong> The random forest has a higher overall accuracy, though accuracy as a singular metric can oftentimes be misleading. Note how the random forest has poor recall (only 3%!), meaning it only correctly identified 3% of the people who failed to pay back their loans based on the test data. Ultimately, the model you choose will depend on exactly which parameter you’re trying to optimize for.</p><p>This has been a demonstration of decision trees, random forests, and a set of real world data to showcase how machine learning concepts and EDA can be used to extract meaningful insights for businesses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c208b8106cb5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/using-decision-trees-and-random-forests-to-predict-lending-profitability-c208b8106cb5">Using Decision Trees and Random Forests to Predict Lending Profitability</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>