<?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 Carlos Brown on Medium]]></title>
        <description><![CDATA[Stories by Carlos Brown on Medium]]></description>
        <link>https://medium.com/@carlos.brown3?source=rss-8003c12d339d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Tg2Bz_fxmgRIa3_VE2X6oA.jpeg</url>
            <title>Stories by Carlos Brown on Medium</title>
            <link>https://medium.com/@carlos.brown3?source=rss-8003c12d339d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:41:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carlos.brown3/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[Causal Inference for Data Scientists: Part 1]]></title>
            <link>https://medium.com/data-science/causal-inference-for-data-scientists-part-1-f97fa8614143?source=rss-8003c12d339d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f97fa8614143</guid>
            <category><![CDATA[causality]]></category>
            <category><![CDATA[judea-pearl]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[causal-inference]]></category>
            <dc:creator><![CDATA[Carlos Brown]]></dc:creator>
            <pubDate>Thu, 08 Jul 2021 21:24:15 GMT</pubDate>
            <atom:updated>2023-02-09T18:22:19.628Z</atom:updated>
            <content:encoded><![CDATA[<h4>Techniques you didn’t know you needed</h4><blockquote>This article is the first in a two part series that deals with the underlying concepts and mathematics of Pearlian causal inference. Part 2 will focus on a practical example using the <a href="https://github.com/microsoft/dowhy">DoWhy </a>library. If you prefer to begin with implementation first, skip to Part 2 when it becomes available then return here for the theory.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKhsYFFaW_TJQbEC6UeRaQ.jpeg" /><figcaption>Causality: Photo by <a href="https://unsplash.com/@nadir_syzygy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nadir sYzYgY</a> on <a href="https://unsplash.com/s/photos/cause-and-effect?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Causal inference has undergone tremendous growth in recent years. This surge has happened in parallel with the rise of Data Science (DS) more broadly, but they still remain distinct in practice. While the science behind causal reasoning has benefited from recent work by Judea Pearl, Donald Rubin, Susan Athey, and many more, the insights they found have not made their way into mainstream DS, despite readily available implementations of these techniques. Many DS practitioners simply do not know about or employ causal reasoning in their workflows and that may be for several reasons…</p><ol><li>The assumptions that go into causal reasoning, like Bayesian models, can be sliced, diced, and debated six ways from Sunday. (thanks to my Linkedin connection Gino Almondo for this insight)</li><li>People think that correlations are automatically causal and are enough in themselves. Look for this in your workplace and you’ll be surprised how often it shows up.</li><li>Causal inference is perceived to be hard. We don’t like hard.</li></ol><p>These points have varying degrees of validity, but ultimately miss the main point. The main point is that while there are challenges, we have in our hand a set of concepts and techniques that if applied with care, will completely transform the way that data science is practiced and perceived. We get to leverage domain knowledge to make robust inference. Let’s first set up the discussion with some preliminaries.</p><h3>What is Causal?</h3><p>For this article, we will adopt the interventionist approach to defining causality. We all have an intuitive idea of what is causal, but to work in the language of mathematics we will need something more formal.</p><blockquote>The definition is that for two distinct events A and B, A causes B if a change in A corresponds to a change in B, all else being equal.</blockquote><p>Most of causal inference deals with ensuring the “all else is equal” part. There are other definitions that are similar, with vigorous debate surrounding which is most correct, but we will settle on this one and proceed.</p><h3>How do we establish Causality?</h3><p>Before the causal renaissance of recent times took place, the gold standard in establishing causal links was <strong>randomized experimentation</strong>.<strong> </strong>In many ways they still are. So let’s set the stage by discussing causality in the context of a randomized experiment.</p><p>We have an outcome we would like to measure, named Y. We want to see if manipulating a specific treatment X will cause appreciable change in Y. In a randomized trial, such as a drug test, we would obtain a sufficiently large sample (using power analysis) of people <strong>at random </strong>from the broader population. The participants would be randomly assigned either the drug or a placebo. We would then measure the difference in Placebo group and Drug group, which is called the <strong>Treatment Effect, </strong>which can be done in a variety of ways (see cohen’s d or CATE). Any effect sizes would then be from the treatment alone and not due to any other factors, or <strong>confounders</strong>, that may be present.</p><h4>Random assignment ensures that “all else being equal” is true in the aggregate.</h4><h3>The Real World</h3><p>Now we come to the main hurdle that we face in causal inference. We don’t always have the time and money to do randomized experiments to establish a causal link. Even when we do, it may not be ethical to do so. We may in the end just have a set of observational data, and a few hypotheses we have built from observation. Can we test them using our non-randomized data? The answer is yes, and that is where our new toolkit comes into play. The techniques we will use will take our <strong>observational </strong>dataset and transform it into what is called the <strong>interventional </strong>dataset, from which we can draw causal inferences. The key here is that the data itself is not enough to establish causality (see <a href="https://en.wikipedia.org/wiki/Simpson%27s_paradox">Simpson’s Paradox</a>). We need more to reason robustly.</p><p>Given that the data is not enough, we will draw a literal picture of the world, called a causal graph, that encodes our <em>assumptions </em>about the data generating process. The <strong>data generating process</strong> is the system whose dynamics we are trying to understand. This will help us to construct our interventional distribution, and test whether our model is valid.</p><p>We are mirroring the scientific process. We start with a hypothesis, then we model how the world behaves under that hypothesis using our causal graph. Finally we test our model using the data, which may uphold the hypothesis or not. Additionally, we further test the model to see how sensitive it is to changes, unaccounted confounders, and other gotchas. Iterate until your theories fit the facts.</p><h3>Going Deeper</h3><p>Let’s define a few terms…</p><p><strong>Intervention: </strong>Actively doing X leads to a change in Y.</p><blockquote>Examples: If I push my punk brother, does he get mad? If I give a person the drug, does it make them better?</blockquote><p><strong>Counterfactual: </strong>What if I hadn’t done X, would Y have still occured?</p><blockquote>Examples: If I hadn’t pushed my punk brother, would he have fallen down? If the patient had not been given the drug, would they have gotten better?</blockquote><p>Reasoning with interventions and counterfactuals mirrors the normal, human approach to understanding causality. We are creating two different worlds and comparing the results in both. If we have an intervention case, and its counterfactual, we can establish causality. In a randomized experiment, we have those two readily in hand at the group level. When the level of analysis changes to the individual, then we realize one of the most fundamental problems we are trying to solve. We see that we have a <strong>missing data</strong> problem. We do not have the counterfactual in hand, because the counterfactual for an individual doesn’t exist. You cannot be both treated and untreated simultaneously. Twin studies come close. Thankfully, we have ways to estimate this counterfactual while controlling for everything that may muddy the waters (confound) of our analysis. Remember that we are trying to hold all else equal, which is why we need a counterfactual. Let’s dive into the math to understand what’s going on better.</p><h3>Derivations</h3><p>When we obtain observational data, what we are getting are probability distributions, whether the data is discrete or continuous. The two main types are joint probabilities and conditional probabilities. Anyone who has taken a basic probability course has covered these topics, but they provide the basis for construction of our causal formulas. Below are two data distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*SZfjiY5ZhCcNCAtVVXo6GA.png" /><figcaption>Observation and Intervention Diagrams</figcaption></figure><p>On the left, we see the observed model which shows the interrelationships between the variables in our raw data. Given our definition of causality, we need to estimate the effect that changing X has on Y, independent of everything else. For our observed data, we are unable to make a change in X that would not also have corresponded to a change in Z, therefore changes in X are not indicative of causal changes in Y. We need a way to disentangle the confounding effect of Z on X, such that P(X|Z) = P(X), or to put it another way, we need to MANIPULATE the observed data to make the two variables independent. We need to perform graph surgery.</p><p>The figure on the right shows us our desired state, post-surgical state. Z and X are not connected and therefore a change in one does not affect the other. This is called <strong>d-separation</strong>. And since X is still upstream of Y, any change in X will result in a causal change in Y, whether X is changing spontaneously or by direct adjustment.</p><h4>Assumptions</h4><p>Now we move on to the derivation that allows us to transform our observed data distribution into our intervention data distribution. We start the derivation with three links between the two. We use P to denote our observational data distribution, and Pₘ to denote the manipulated, intervention data distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*m2Lp20A16cRxZlz2QVrwBA.png" /><figcaption>Link 1</figcaption></figure><p>Since the incoming effects of Y remain unchanged between the two graphs, the probability distributions are the same as well. This is our first invariance link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*NFrLiAWu2q1CxfKMSZGFZQ.png" /><figcaption>Link 2</figcaption></figure><p>The process determining Z does not change by removing the connection between Z and X. This is our second invariance link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*uypl_7AotVhiiwG7I8EuVg.png" /><figcaption>Link 3</figcaption></figure><p>Z and X are d-separated in the manipulated model, and therefore are independent (having information about Z doesn’t tell us anything about X in the latter model). From link 3, it follows we can go one step further and obtain P(Z).</p><p>Given these links, we begin from the causal diagram on the right and define our <strong>do operator</strong>. We want to know, what is the probability of Y given that I intervene on X, denoted by do(X). It follows then that…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*7GxKMq0NWEhzBwpdzBVj8g.png" /><figcaption>(by definition)</figcaption></figure><p>Next we expand the right side of the equation to account for Z</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*hyw1iRPQb3IQBLN3XVft1w.png" /></figure><p>By the <a href="https://en.wikipedia.org/wiki/Law_of_total_probability">Law of Total Probability</a>, we are taking a weighted average of P(Y|X) over Z. This is how we control for the effect of Z. This is identical to Inverse Probability weighting and propensity score weighting techniques to control for confounding. Adam Kelleher has a great article showing the equivalence <a href="https://medium.com/@akelleh/introducing-the-do-sampler-for-causal-inference-a3296ea9e78d">here</a>, so definitely check it out if you’re interested in going deeper.</p><p>Next we use the principle of d-separation of Z and X to obtain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*oQ-MWdb5acTFyPBHl5dGlA.png" /></figure><p>Finally we invoke the invariance link between the manipulated and observational distribution to get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*Ws-MJXq6EnxE3UOXxmxUMA.png" /><figcaption>Adjustment Formula</figcaption></figure><p>Using this last expression, called the <strong>adjustment formula</strong>, we have now defined how we can generate our interventional distribution, P(Y|do(X)), from our pre-intervention, observational data. This is a broad definition of the interventional distribution that works for both continuous and discrete cases.</p><p>For our drug trial example which is a discrete binary outcome, estimating the treatment effect using our derived causal expression, we could define the Average Treatment Effect (ATE) as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*gQ_EYHQfCEYtLmkNabZj0Q.png" /><figcaption>Randomized Trial</figcaption></figure><p>Thus, we obtain the same outcome using a randomized trial as we do by controlling for all pertinent confounders (denoted as Z above).</p><p>The first term on the top is the observed treatment effect probability and the second is the counterfactual probability. Their difference, assuming Z stands for all confounders of Y and X, establishes the causal effect of treatment X on the outcome Y. Notice that Z could be either continuous or discrete itself, it does not matter. There is a beautiful flexibility apparent in the formulation.</p><h3>Final Matter</h3><p>Those are the basics of Pearl’s Causal Inference. For alternate discussion on causality, read up on <a href="https://en.wikipedia.org/wiki/Rubin_causal_model">Rubin’s Potential Outcomes Framework</a>. If you like debates between genius scientists, <a href="https://statmodeling.stat.columbia.edu/2009/07/05/disputes_about/">this </a>resource will make you happy. For an application of causal reasoning to high dimensional datasets using Random Forest, see <a href="https://www.gsb.stanford.edu/faculty-research/faculty/susan-athey">Susan Athey’s</a> recent work <a href="https://arxiv.org/pdf/1510.04342.pdf">here</a>. A great <strong>intro book</strong> by Amit Sharma and Emre Kiciman can be found <a href="https://causalinference.gitlab.io/book/">here</a>. Finally, read up on the backdoor criterion, an important next step in causal inference which can be read about <a href="http://bayes.cs.ucla.edu/BOOK-2K/ch3-3.pdf">here</a>.</p><p>We have just scratched the surface of powerful concepts that really put the Science into Data Science. I hope this has been helpful to establish the theory before the implementation. I also hope that it has sparked your curiosity, so that you want to learn more and start to apply these principles in your work. Part 2 of this series will be a hands on application of Pearlian do calculus to a causal problem in the healthcare space using the DoWhy package.</p><p>Stay Tuned! Thanks for your time, and God Bless.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f97fa8614143" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/causal-inference-for-data-scientists-part-1-f97fa8614143">Causal Inference for Data Scientists: Part 1</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[The Longing for Community]]></title>
            <link>https://medium.com/@carlos.brown3/the-longing-for-community-fd827f319280?source=rss-8003c12d339d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd827f319280</guid>
            <category><![CDATA[community]]></category>
            <category><![CDATA[faith]]></category>
            <category><![CDATA[boomers]]></category>
            <category><![CDATA[home]]></category>
            <category><![CDATA[millenials]]></category>
            <dc:creator><![CDATA[Carlos Brown]]></dc:creator>
            <pubDate>Tue, 20 Apr 2021 01:29:19 GMT</pubDate>
            <atom:updated>2021-04-20T01:29:19.257Z</atom:updated>
            <content:encoded><![CDATA[<p>Or rather, eternal life</p><blockquote>God blessed them and said to them, “Be fruitful and increase in number; fill the earth and subdue it. Rule over the fish in the sea and the birds in the sky and over every living creature that moves on the ground.”</blockquote><blockquote>— Genesis 1:26</blockquote><blockquote>“People wish to be settled”</blockquote><blockquote>— Ralph Waldo Emerson</blockquote><p>We all have the longing to be around other people. Modern life as we experience, does not orient itself around this fundamental need of ours. You could say, in fact, we are incentivized to disregard it. You could say it’s a form of deconstruction of how we have lived for millenia, but that would require a cabal or conspiracy. There is none here, just plain old economic incentives and human frailty. We are our own worst enemies. This lifestyle that doesn’t satisfy our needs seems to be particularly acute in my generation, Millenials. The generation that in their own mind, can do no wrong, and in everyone else’s mind, no good. We may not have been the first generation to spurn this built in need of ours, but we have refined it into an art form. Now give me my avocado toast.</p><h3>We don’t stay put</h3><p>Let’s start off the discussion by comparing generations. If there’s one way to quickly distinguish the habits of Millenials vs Boomers, it is to say that Millenials value experiences, while Boomers value physical things. Millenials rent, Boomers buy houses. Millenials have less kids and have them later because it messes up our life plan, however ill defined that plan may be. Or we have no kids, and our nation doesn’t reach <a href="https://en.wikipedia.org/wiki/Total_fertility_rate#Replacement_rates">replacement</a>. For Boomers, a family was the plan and they were set on making that work.</p><p>Like Aaron Renn said in the <a href="https://themasculinist.com/">Masculinist</a> #48, people in the Boomer generation were given a series of steps that if they followed them, they were essentially guaranteed to succeed. This no longer holds on the main for the world that Millenials have inherited as they have reached adulthood. Get a college degree so you can get a good job makes less and less sense every day, as the excesses of the college-industrial complex have become apparent. We have been incentivized to uproot ourselves from our families and friends to go to a new city, in order to obtain a degree that may or may not be used in our eventual job. We spend 4 years, making new friends and bad decisions, while taking superfluous courses for thousands of dollars where we essentially teach ourselves the material because the professor is in publish or perish mode and has no time for us idiots. Then, when the excesses have run their course, we uproot ourselves again to move for our job, where everything we need to know for it is taught to us in the 1st 6 months. We are a mobile people, following orders while taking no time to think about where the orders lead us. A generation of semi-conscious U-Haulers. We wouldn’t know community if it walked up and said hi nice to meet you, would you like to get coffee? (something with soy in it, we’re Millenials remember).</p><p>We are semi-nomads, searching for something permanent and lasting amongst a sea of commodities. And EVERYTHING is commoditized now, including significant others and gourmet meals. We are long on advertisements for things we don’t need, and short on the thing we do : <strong>stable community</strong>. We make so many acquaintances, very few long term friends. Those friends we do keep we see once or twice a year due to the distance. We have a thousand “friends” on Facebook, meanwhile we’re clueless about <a href="https://en.wikipedia.org/wiki/Dunbar%27s_number">Dunbar’s number</a> and how more isn’t necessarily better. Quantity is not a quality all its own, as some have said. Social media hasn’t shortened the distance between us and our fellow man, it has exponentially blown it out of the water. We understand each other less and less as we drown in a sea of information. Instead of seeing how other people live their lives in authentic interactions, we see the curated ideal of what they wish their life was. It is not the real thing. This isn’t life abundant.</p><p>Think the problem only exists in Millenials? The recent film <a href="https://www.imdb.com/title/tt9770150/">Nomadland</a> explores the phenomenon of older adults (Non-Millenials) who live what amounts to a vagrant lifestyle on the road, following the available, low skill work wherever it leads. What’s interesting about this movie is that it parallels the age of the gold rush and westward expansion across the United States that was one chapter in the story of the nation we now call home. It was an age where people uprooted themselves to better their economic situation. Some were motivated by greed. The great archetype of the time was Wyatt Earp. The movie Nomadland begins with the dissolution the town of Empire, Nevada that existed as a town of factory workers but ceases to be when the local mill shuts down. This happened over and over again in the 1800s. History never repeats, but it does rhyme. What’s so interesting is that with the 1:1 correspondence between Nomadland and our American mythos of the Wild West, we see the twilight reflection of our own time. Go where the best job is, forgetting other considerations. Strike it rich at any cost. Neglect community, family, stability, roots. And we find others forced into this lifestyle, not because they want it, but they need to in order to survive. A nation that incentivizes its people to neglect community is not a nation that will survive forever.</p><h3>Millenial Hospitality</h3><p>This unrooted lifestyle we live should show signs of having a negative effect, right? There should be evidence that it’s unhealthy. Well, there is. There’s something we need to understand. Life is a series of tradeoffs. It is the rarest of rare to get something for nothing. The choices we make in how we order our lives will materialize eventually, for good or for evil. The nomadic life we live, moving apart from family, differs drastically from our ancestors, with negative consequences. An easy way to see the fallout is trying to find Hospitality in the proverbial haystack.</p><p>I began to notice this in college, and have continued noticing the pattern ever since. While the vast majority of college students rent or live in student housing (renting), I can’t recall but one example of when I visited a friend’s place and they offered me something to eat or drink. Sebastian Maniscalco got it right in his hilarious bit on ringing the doorbell and what it meant 20 years ago vs today (link <a href="https://www.youtube.com/watch?v=5CznoAW2k1I">here</a>). People don’t react to company like they did before. Company just doesn’t come over as often.</p><p>One extreme example I remember was hanging out with a friend at the duplex he was renting out, then without even a word, he left me alone at his own place to go hang out with a girl… The level of extreme disownership of everything that hospitality entailed was evident. When you don’t own a place or think that you will be there long, the drive to show hospitality goes down. It’s a structural fault in the way we’ve chosen to live. We won’t be entertaining angels any time soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykWSvF7UthU2P08EucsMGA.jpeg" /><figcaption>Home</figcaption></figure><h3>You can’t have it all, until you can.</h3><p>Hospitality is necessarily tied to the concepts of a home and community. But we don’t want to stay at home all the time, even if the Coronavirus forced us to do just that. We crave adventure too. The pendulum doesn’t need to swing from lone hunter-gatherer lifestyle to homebody. Our global world, stitched together by supply chains and massive airlines affords modern man the ability to travel where once only Marco Polo could do the same. Though many Americans can only speak one language due to English’s dominance as a lingua franca worldwide, still many have a passport with stamps in it. Foreign travel opens your understanding of the world. We even have a new class of workers called digital nomads. The rise of the internet laid the foundations for people to live this kind of lifestyle, constant travel while working remotely on the internet, often as a freelancer.</p><p>What are the tradeoffs? The baby is gone with the bathwater. We weren’t meant to be on perpetual adventure. Just like your portfolio cannot be entirely risky assets if you want to survive financially, you need adventure, but you also need a home to come back to at the end of the adventure. This is a theme that J.R.R. Tolkien explores in the Hobbit and further in Lord of the Rings. The world wasn’t in Bilbo’s books, it was “out there,” as Gandalf said. Still the novels end with Bilbo/Frodo at home, reminiscing on the times of adventure they just experienced. There’s this dual reality that pervades the novels : That any adventure is a true adventure when you have a home to return to. So we see that adventure is not bad, but the brand of adventure our society tells us we can have is a fool’s game.</p><h3>The Greatest Commandment</h3><p>We as humans made in God’s image are like him in many respects. God existed in community since before the foundation of the world. Perpetual joy, love, and adoration. Out of the overflow of His being, God created us. Therefore, we mirror him in our desire for community. God has never been alone, though he stands alone in glory. The more that we spurn community for more temporal things that social media or our boss tell us are worth our life’s pursuit, the more we diverge from God’s best for your life. You cannot unmake God’s good design.</p><blockquote>By this all people will know that you are my disciples, if you have love for one another.</blockquote><p>— John 13:35</p><p>How can we feel the weight of this verse, and obey it, if we neglect the “one another?” The we of life is essential to becoming fully human.</p><blockquote>…Truly, I say to you, as you did it to one of the least of these my brothers, you did it to me</blockquote><p>— Matthew 25:40</p><p>So then, building a community becomes an expression of our love for the Lord, because if you love him, you will obey what he commands. And finally…</p><blockquote>And let us not neglect our meeting together, as some people do, but encourage one another, especially now that the day of his return is drawing near.</blockquote><p>— Hebrews 10:25</p><p>What encouragement is a brother that is here today, then willingly leaves tomorrow? His encouragement is brief. I’m speaking not only from the scriptures, but secondarily from my own painful experience. I have people I love and know well, all over the country. I can’t move them all to the same city so we can all be together. Even if I could, would they want to, simply for my sake and plan? There is a real sense of grief I feel that having gotten to know them, I can’t continue in communion with them in any real, embodied way due to the distance. At least on this side of eternity.</p><p>So what are we to do? Find a place and a people to commit to, over your career. Find a church over a job. Stay, serve, build. Glorify God in a community, as He is in community with himself, and with you through Christ and the Holy Spirit. Christ died “for the joy set before him”, which was heaven full of His redeemed sons and daughters, with Him and adoring Him forever. Let that vision captivate you, and mirror it here on earth to God’s glory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd827f319280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reproducibility in Data Science]]></title>
            <link>https://medium.com/data-science/reproducibility-in-data-science-c2ac9e689339?source=rss-8003c12d339d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2ac9e689339</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[reproducibility]]></category>
            <dc:creator><![CDATA[Carlos Brown]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 18:43:37 GMT</pubDate>
            <atom:updated>2020-08-30T20:02:21.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="#freehongkong" src="https://cdn-images-1.medium.com/max/1024/0*as15mzcRkRtkn8tu" /><figcaption>Photo by <a href="https://unsplash.com/@smnzhu?utm_source=medium&amp;utm_medium=referral">Simon Zhu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>It means more than you think</h4><p>Science as a pursuit has always had Reproducibility at its core. After all, if a claim is made about the physical world, and the evidence does not support such a claim, it doesn’t matter how much ideology or vested interest the idea has pushing it, there’s no reason for you to believe it. In a seemingly post truth world that we live in, where politicians, the media, and voices on social media propagate information that is often varying shades of dishonest, it pays dividends for your integrity to make <em>reproducible</em> claims. It’s part and parcel to your job as a data scientist.</p><p>I think Reproducibility in data science is less well understood than Reproducibility in more established fields of science. For example, a study can clarify one or two simple claims that have to do with testing the mean difference between two or more groups. Examples include…</p><ol><li>Does treatment A make a statistically significant difference over placebo treatment B?</li><li>Do groups exposed to differing lengths of stimuli exhibit varying outcomes?</li><li>What is the effect size of a treatment?</li></ol><p>Since there is generally a publication bias towards statistically significant <a href="http://elsevier.com/connect/scientists-we-want-your-negative-results-too">results</a>, some research does not get published if its goal is to repeat what other studies have done. However when they are performed, if they do not come to the same conclusion under similar inputs, then it casts doubt on the original claims. The research has not been reproduced.</p><p>In the field of <strong>structural engineering</strong> (my first career), we used a form of Reproducibility to validate designs performed by other people. Often an engineer would be tasked with designing a bridge, which is an awfully complex hunk of concrete and steel. In case you’ve never been outside, here is a picture of one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7xr4pchdiL-UCbFV" /><figcaption>Photo by <a href="https://unsplash.com/@christopher__burns?utm_source=medium&amp;utm_medium=referral">Christopher Burns</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Looks complicated huh? That engineer’s design was reviewed with a fine tooth comb many times before it was released to the contractors for construction. Often during the checking process, another engineer will make a design in parallel, given the same initial inputs, and then they compare notes. Same underlying phenomena, but arrived at by two, independent engineers. Any discrepancies usually highlight an inefficiency in the original design, or a point of disagreement on how the bridge should be modeled. The goal was consensus through <strong>Reproducibility</strong>.</p><h4>What is Reproducibility?</h4><p>There are more <strong>dimensions</strong> to Reproducibility than simply obtaining the same result as we have discussed. Mastering all of these dimensions makes it more likely that your work will be useful for people and be utilized to influence decision making at a higher level. Let’s explore</p><h4>Same Code</h4><p>Your code should be well documented and should actually run. Go figure. There are two main factors here for success</p><ol><li><strong>Dependency Management</strong> — how do you manage 3rd party packages, are they actively maintained, are the versions pinned? Do you have robust control over system level dependencies?</li><li><strong>Environment Management</strong> — what language version did you build your product in? Will the application environment use the same?</li></ol><p>In a data science consulting role, many times these two pieces are neglected and are tacked on later when client delivery becomes more important. Both are crucial because you should expect that the analysis will be run on a different machine than where the code was written, or be executed in someone else’s well manicured environment, and how can you guarantee that they have the same history of package needs, system dependencies, and language versions as you?</p><h4>Same Data</h4><p><a href="https://realpython.com/python-data-version-control/"><em>Data versioning</em></a><em> </em>is becoming more and more popular. The c<a href="https://drivendata.github.io/cookiecutter-data-science/">ookie cutter data science</a> framework has a loose version of this built in. For example in cookie cutter, data is divided into <strong>raw</strong>, <strong>interim</strong>, <strong>processed, </strong>and <strong>external</strong> data from third party sources. This intuitive way of splitting data can help you tell the story of data transformation, from its raw format into something able to be analyzed. Building a narrative around any data transformation using data versioning will allow you to validate with stakeholders that your logic is sound and your data can be trusted. The analysis can be extended, or even reverted as necessary which allows you to have the same agility that git offers code, but now in the data.</p><h4>Same Random Numbers</h4><p>Do you use random <a href="https://opendatascience.com/properly-setting-the-random-seed-in-ml-experiments-not-as-simple-as-you-might-imagine/">seeds</a> in your machine learning pipeline? They allow for quick troubleshooting of problems as the pipeline is built out, because they introduce Reproducibility into your model outputs. This is especially important when you use a learning algorithm with random effects in it, like neural nets or random forest. Random numbers will always be a part of machine learning workflows, when train/test splits, cross validation, or optimization takes place to name a few. You can control them with seed numbers. Think of these seed numbers as controlling for a <strong>confounding</strong> variable, the random error. If you don’t use seeds, then you don’t know if the change in model outputs, standard errors, importances, etc. is due to random effects or due to a change in the <strong>hyper-parameters</strong>. To ensure that this randomness is at least temporarily consistent while you build out your product, then setting a random seed controls and eliminates random deviation in your ML pipeline.</p><h4>Same Story</h4><p>Now that we have all of the above steps in place, we want to make sure that our work has an impact that lasts. We want to ensure the conclusions we’ve drawn replicate and persist themselves in the minds of stakeholders. We don’t just want our audience to nod their heads, and take no action on what has been presented. What makes these ideas stick in an effectual way?</p><p><em>Stories</em>. Whether it is your supervisor, a client, or C-level executives, a compelling story built around the data is the most effective way to achieve this goal. Our ancestors passed on knowledge this way because it was effective. Nothing has changed, it still works.</p><p>Here also is the link between Reproducibility and <strong>Interpretability</strong>. Telling a story around your data and model, and explaining why it made a prediction (using for example feature importances or <a href="https://github.com/slundberg/shap">SHAP</a> values) leads to the Reproducibility of your conclusions in people’s minds. The idea takes hold because you’ve communicated a compelling narrative, and people know why they should care about it, distilling complex mathematics into something rich and actionable. <strong>This is the art of the science</strong>. It’s truly a beautiful combination when it all comes together.</p><h4>In Summary</h4><p>What is the point of Reproducibility? To be able to not only have people run the same code and get similar results, but for them to come to the same conclusions, and for that to persist in time, <strong>on disk and in human memory</strong>. Don’t limit Reproducibility just to virtual environments, or even analytic conclusions, it’s a much richer, and crucial concept than that.</p><p>Something to think about: How can you introduce more Reproducibility into your own projects?</p><p>Thank you for reading this article! I hope it has been eye opening and informative. Feel free to connect with me on <a href="https://www.linkedin.com/in/carlos-brown-eit/">Linkedin</a> if you have any questions or are just looking to expand your network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2ac9e689339" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/reproducibility-in-data-science-c2ac9e689339">Reproducibility in Data Science</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[Recursion in Python, an exploration]]></title>
            <link>https://medium.com/data-science/recursion-in-python-an-exploration-bfaa452d3260?source=rss-8003c12d339d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfaa452d3260</guid>
            <category><![CDATA[back-to-the-future]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[feynman]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Carlos Brown]]></dc:creator>
            <pubDate>Sun, 03 May 2020 13:30:12 GMT</pubDate>
            <atom:updated>2020-05-04T17:53:06.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_bl7r2rQX48Toa7D" /><figcaption><a href="https://xkcd.com/">Image source</a>, <a href="https://creativecommons.org/licenses/by-nc/2.5/">License</a></figcaption></figure><p>Recursion is one of those ideas that may seem out of reach, likely from a higher plane of programming existence. Something that A. You don’t really know why it’s a thing and B. You don’t think you would ever need to utilize it. After all, there are no Functional Programming languages in the Top 10 of the <a href="https://www.tiobe.com/tiobe-index/">TIOBE index</a> as of this writing. Think again, and again…</p><p>Perhaps you’re right, recursion is only useful for a coding interview and otherwise FORGET IT. However, I am of the opinion that learning different programming paradigms, and the way in which they parse problems, will ultimately make you a better data scientist/coder. Learning a new paradigm exposes you to new ways of thinking and different ways to structure your code. “This is the way we’ve always done it” won’t be a part of your verbal repertoire with this attitude. Consequently, you’ll learn more and have a better handle on solving the data challenges that come your way. Plus, if you like math like I do, and let’s face it if you are doing data science and don’t like math, then LEAVE NOW (sorry for the tone, I love you), then you will find the exercise enjoyable in its own right.</p><h4>What is Recursion?</h4><p>To introduce recursion, let’s make a simple, hypothetical case that compares solutions. You have an array or list of numbers that need to be squared before they are utilized by the rest of your program. We could use a <strong>for loop</strong> or <strong>list comprehension</strong> in python to create the squared version as such.</p><pre># Set array<br>my_array = [10,11,12,13,14,15]</pre><pre># Method 1<br># Create a new squared array with for loop (can be considered an anti-pattern)<br>squared_array = []<br>for num in my_array:<br>   squared_array.append(num*num)</pre><pre># Method 2<br># Create a new squared array with list comprehension, a bit more beautiful and concise<br>my_squared_array = [x*x for x in my_array]</pre><blockquote>Typically when we loop over values in an imperative language like Python, we are using a <strong>for</strong> loop or a <strong>while</strong> loop. These are the constructs we are used to and we use them so often, they are second nature. But what if for and while loops got axed from python tomorrow? Aside from a majority of the world ceasing to function, we have the more pressing issue…how to use recursion now??</blockquote><h4>Recursion Intro: Squared Array</h4><p>We can’t use a list comprehension, so let’s use our new pal recursion to square our array. For this, we need to write a new function.</p><pre># Set array<br>my_array = [10,11,12,13,14,15]</pre><pre># Define our recursive, squared function that returns a new array<br>def squares(an_array, n=None, ret_array=None):<br>   if n == None:<br>      n = len(an_array)<br>      ret_array = []<br>   pos = len(ret_array)<br>   squared = an_array[pos] ** 2<br>   ret_array.append(squared)<br>   if n-1 == 0:<br>       return ret_array<br>   else:<br>       return squares(an_array, n-1, ret_array)</pre><p>Ok, that’s a bit ugly and verbose when a list comprehension would suffice, but it shows that we can use recursion in place of a for loop. The function begins by initiating a new array that holds our square values, uses n as a counter to determine where we are as we go over the array by position, then it calls itself until we have gone through the entire array and subsequently have our new squared array.</p><h4>Helpful Hints</h4><p>Think of a recursive function as a bit of code that does not only reside in one place in memory. Sure, the function is defined in one place, but can be called multiple times as data is passed into it. This is termed the <strong>Call Stack. </strong>Don’t think about it like a Python eating its own tail, though many R users would be cheering. Think about it like a bunch of clones passing a small box, each putting in a coin, then passing the box to the next clone. Ok, maybe now you’re even more confused. Going over the following 3 cases will be helpful to drive this point home and clear any confusion you may have.</p><h4>Recursion Case 1: Canonical Factorials</h4><p>Let’s use recursion to do what everyone who has ever touched recursion has done, calculate a factorial. Who else loves discrete mathematics!?</p><pre>def factorial(num):<br>    if num == 1:<br>        return 1<br>    return num*factorial(num-1)</pre><p>A factorial of n (notation as n!) is the product of all positive integers less than n. It is an operation on an arbitrary number defined as n! = n * (n-1) * (n-2)…(1!), where 1! = 1. This is what is called the <strong>stopping condition</strong> in our code. This idea is very important for recursion because without it, our code could go into an infinite loop, causing “a time paradox, the results of which could cause a chain reaction that would unravel the very fabric of the space time continuum and destroy the entire universe.” — Doc Brown</p><blockquote><strong>Say what?</strong></blockquote><p>Here’s a helpful way to visualize our factorial func for the case of 4!.</p><p>factorial(4) = 4*factorial(3) = 4*3*factorial(2) = 4*3*2*factorial(1) = 4*3*2*1 = 24</p><p>Each instance of the factorial function is the same as we have defined in <em>def factorial()</em>, but is a new instance that is taking the results of a previous factorial function instance and passing a new result on, all beginning with the base case of 1, in which case it all rolls up into the final calculation.</p><h4>Recursion Case 2: Sum of First N Integers</h4><p>Here’s how to use recursion to sum the integers between 0 and n</p><pre>def sum_n(n):<br>    if n == 0:<br>        return 0<br>    return n + sum_n(n-1)</pre><pre>sum_n(1000)</pre><pre>Outputs: <br>500500</pre><p>Let’s check our result with the closed form version of the same operation, to make sure we defined our recursive function correctly. Spot checks are always a good idea, because as <strong>Richard Feynman said: “The first principle is that you must not fool yourself — and you are the easiest person to fool.” </strong>Insert I and myself into the quote to make it personal.</p><pre>def check_sum(n):<br>    return int(n*(n+1)/2)</pre><pre>check_sum(1000)</pre><pre>Outputs:<br>500500</pre><h4>Recursion Case 3: Compound Interest</h4><p>You have probably seen the formula for compound interest before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*Uf9Im6GfGRuA3uWy5qQ9YQ.jpeg" /></figure><p>Since we have a number (1+r) that is raised to an exponential, then we can use recursion to calculate our future value FV.</p><pre>def future_val(pv, rate, t):<br>    if t == 0:<br>        return pv<br>    pv = pv*(1+rate)<br>    return future_val(pv, rate, t-1)</pre><p>The previous function assumes a compounding rate of n=1. That means we only compound once per period t, where t is usually meant to refer to a years time. Let’s extend our example to include different compounding rates, such as monthly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*-b-KM3bCYU0FsO1cLTkXfw.jpeg" /></figure><pre>def future_val_n(pv, rate, t, n):<br>    if t == 0:<br>        return pv<br>    pv = future_val(pv, rate/n, n)<br>    return future_val_n(pv, rate, t-1, n)</pre><p>We’ve been able to recycle our future_val function, and extend it so that we are compounding n times per time period t. Does our function work?</p><pre>future_val_n(1000, 0.07, 20, 12)</pre><pre>Outputs:<br>4038.73</pre><pre># Now we check our value from future_val_n</pre><pre>print(1000*(1+0.07/12)**(20*12))</pre><pre>Outputs:<br>4038.73</pre><h4>Final Words</h4><p>Remember a few things</p><ol><li>We don’t have to have a pure functional language to begin using functional programming techniques in our code</li><li>Python is not a pure functional language (of course), but borrows many features from them, such as functions as first class objects and list comprehensions to name a couple.</li></ol><p>Given these two items, we then realize that python has a limit to the number of times a function can be called recursively. This limit is defined here:</p><pre>sys.getrecursionlimit()</pre><pre>Outputs:<br>3000</pre><p>If we run our sum_n function with n&gt;3000, it will throw a <strong>RecursionError</strong> even though the function works for a recursion depth less than the limit. This is something to think about when incorporating these types of functions into your python code base.</p><p>Now that you know recursion, you will start to see things differently, and perhaps have some creative solutions up your sleeve for your next project. I hope this has been a fun and informative intro to recursion and the functional programming paradigm!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfaa452d3260" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/recursion-in-python-an-exploration-bfaa452d3260">Recursion in Python, an exploration</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[Remembering my father]]></title>
            <link>https://medium.com/@carlos.brown3/remembering-my-father-1577b69a9ba0?source=rss-8003c12d339d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1577b69a9ba0</guid>
            <category><![CDATA[fathers]]></category>
            <category><![CDATA[grieving-process]]></category>
            <category><![CDATA[grief]]></category>
            <category><![CDATA[georgia]]></category>
            <category><![CDATA[grief-and-loss]]></category>
            <dc:creator><![CDATA[Carlos Brown]]></dc:creator>
            <pubDate>Sat, 15 Feb 2020 21:09:32 GMT</pubDate>
            <atom:updated>2020-02-15T21:09:32.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>The shock of grief</h3><p>My father passed away on Wednesday, January 22, 2020. We had months to prepare as we saw it coming. My family has been dealing with his loss admirably. Grieving started before he died, which was a mercy. My heart goes out to families who lose a loved one suddenly. That was not our case, it was the culmination of a little over a year of waiting, and praying. First the cancer diagnosis a few months before I married my dear wife, then the completion of his course of treatment after so many doctor’s visits in Chattanooga and Dalton. Then the strokes hit him. The man I knew who would get up early to work on his projects would now spend most of the day sleeping. He passed away early on the 22nd, with my sister reading to him from the book of Ephesians. He left the world with the word of God in his ears, then stood face to face with The Word.</p><p>I had a chance to remember him publicly at his funeral that Sunday. I barely cried at all, but not because I didn’t love the man whom I had spoken to a few days earlier and now could not reach. My tears were few because of what I had to do and because of the shock. Shock is a phase of grief that helps us move through the initial pain of dealing with the death of a loved one without our inner world falling apart. In the world of grief, it can be a good thing at the beginning. I think it was for me, but it’s gone now.</p><p>Eventually, you feel more. But it’s not happiness that you feel more of. You realize everything seems distorted, like you are looking through an old fashioned tinted glass window. I want to explore the process of grieving in another blog post, but not this one. Especially since I am still in the thick of it. Every day is different. Your world is different, and there’s no going back to the way things were. So it was in this blunted state, the precursor to what I am experiencing now, that I talked about my dad to about 150 people or so. Many didn’t and don’t share my beliefs. I hope they heard and understood that everything I said, was said in love for God, for my dad, and for them. These words are an expression of what I really think is true.</p><h3>My father’s funeral</h3><p>Here are the words I spoke, almost verbatim. My father wanted this shared, but he didn’t know what exactly would be said, or who would be saying it. Before I went up to the large, wood pulpit to speak, I felt the love of God reassure me. I felt that he was proud of me, and so was my dad. So while I went to the stage with my heart beating, and heavy at the loss of one of my best friends, I also went up, truly, without fear. Life is short. You are here today, and gone tomorrow. What are you going to do with the time you have been given?</p><p>“Grief is new territory, and I don’t have a map. I only got 30 years with my dad, 25 if you only count the years where I have memories of him. It took a rare stage 4 cancer, a 15 ft fall from a ladder while painting, and multiple strokes to take this man down. I will remember him as he was with his constitution intact, and as he was right before he passed, because it’s all his story that the Lord knew before the beginning of time.</p><p>There are some things that stand out to me about my dad. If you weren’t around him as much as his family was, you may think that everything stands out about him, because he wasn’t a subtle man. My dad never did anything halfway. He was truly generous with his time and his money. As someone who had been through a lot of tough times in his life, he knew how to sit with you in your pain without lame platitudes. He had a general inability to whisper. He was a terrible speller, and the way he butchered words almost invented a new language. Constantly working on a project. An eminently useful man, and crazy good with woodworking. Full of life lessons, more lessons than you would think one life could hold. A great father, an amazing grandfather. I will miss his bear hugs and his cheerful disposition. I will miss working with him in his shop, with a fire going in the old timey stove. I will miss cutting down trees, and splitting logs, where he schooled us on the proper use of a maul every time. I will miss schooling him on the finer points of building a proper fire. Mornings on the porch, chatting while we drink coffee. His deep ‘Amen’ while Tim preached. His concern for others even as he was dying. His sayings like, ‘You’re cruisin’ for a bruisin’.’ ‘I’ll whoop you into next week’ or ‘Now we’re cooking with gas.’ I will miss it all. He is gone from us for a time. <strong>Precious in the eyes of the lord are the death of his saints -Psalm 116:15.</strong></p><p>God will restore everything that has been unmade by the devil and our own sin. He will restore the wasted years like it says in Joel. There is deep meaning in everything that happens, because of Jesus, the Logos, the word made flesh who made his dwelling among us. <strong>Job said that he knew that his redeemer lives, and that after his flesh was destroyed he would see him with his own eyes standing on the earth -Job 19:25–26</strong>. Jesus overcame the grave. Therefore there is hope for my dad’s resurrection, my own resurrection when I die, and for yours if you embrace the savior. <strong>And as it says in James, these trials are for our perfection in the faith -James 1:2–4</strong>. We don’t walk through them alone. After all, <strong>Jesus was a man of sorrows, and acquainted with grief -Isaiah 53.</strong></p><p>Have you ever considered your own position with God? Our lives are a breath. We are here today and gone tomorrow. Jesus came for sinners like my dad, like me, and like you. He loves you. He offers you new life. Do you fear God like my father did? You will stand before Jesus and give an account of your life. Be reconciled to God, while there is still time for mercy. Jesus says if you seek him, you will find him. And what a Savior and Friend He is.</p><p>I miss my father, and I’m proud of him. I know that our friendship is simply on hold, because Christ has overcome the grave. My dad’s legacy will continue to make a name for the Lord through the years. Jesus is close to those who mourn, therefore he’s close to me and he’s close to you. And we need to mourn. When Jesus makes his home inside of you, He also gives you new eyes to see. You see sin, life, morning and evening, kindergarten and retirement, life…and death differently. Like C.S. Lewis said, ‘<em>I believe in Christianity as I believe that the Sun has risen, not only because I see it but because by it, I see everything else.’</em> So, I do not grieve as someone who is without hope, but as one who sees with the eyes of faith that my dad’s life has eternal significance and that I will see him again one day. Lalo always used to tell his grandchildren, ‘What are you never supposed to forget? Lalo loves you!’ God is saying the same thing to us today, even as he keeps Lalo in his loving embrace forever. ‘<strong>My sheep hear my voice, and I know them, and they follow me. I give them eternal life, and they will never perish, and no one will snatch them out of my hand. My Father, who has given them to me, is greater than all, and no one is able to snatch them out of the Father’s hand.’ -John 10:27–29&quot;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1j3LZbAfeJHnLY3XsaQtCA.jpeg" /><figcaption>Dad, in the men’s lounge on my wedding day</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1577b69a9ba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 Lessons Learned for Data Scientists]]></title>
            <link>https://medium.com/data-science/7-lessons-learned-for-data-scientists-461d435d68d5?source=rss-8003c12d339d------2</link>
            <guid isPermaLink="false">https://medium.com/p/461d435d68d5</guid>
            <category><![CDATA[data-wrangling]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[lessons-learned]]></category>
            <dc:creator><![CDATA[Carlos Brown]]></dc:creator>
            <pubDate>Tue, 31 Dec 2019 21:36:34 GMT</pubDate>
            <atom:updated>2020-01-01T05:46:52.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDp3ZCRmoQ_WHpC-P_RDpw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@photified?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Justin Main</a> on <a href="https://unsplash.com/s/photos/ascend?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>“<em>It’s good to learn from your mistakes. It’s better to learn from other people’s mistakes.</em>” — Warren Buffett</p><p>We are about to enter a new decade. Many of you are starting a new career as a Data Scientist. Some of you are thinking of making the move. It’s better to have more information, more perspective, to make the best decisions. Hence, this article. I don’t claim to be wise, but these 7 tips are more along the lines of wisdom than anything else. They are a distillation of my experience working as a consulting Data Scientist at Guidehouse. They have been learned on what has so far been an incredibly fun journey. I wish I had known them from day one. Also, I hope they help you to level up on your own DS journey. Take the meat and spit out the bones.</p><h4>The Lessons</h4><ol><li>Use the basics of <strong>Functional programming</strong> (FP) as often as you can and makes sense for the context of your project. The reason I say that is because I am not an expert on programming paradigms and don’t want to prescribe FP as some panacea that will destroy your data headaches within 15 minutes. Object Oriented Programming exists too, and others. But where FP makes sense, use the following tips to enhance your code. First, <strong>Avoid</strong> for loops if necessary. Use mapping functions or recursion. “<em>Flat is better than nested </em>“ — Zen of python. Second, <strong>Method chaining</strong> is powerful and readable. The python Pandas package has some built in functions like this including the pipe method, but I believe that %&gt;% in R are more elegant than the python equivalent so I intend to learn them. Finally, functions should return the <strong>same value given the same input</strong> every time they are run. This rule brings your program functions in line with the mathematical definition of a function. Functions should operate only on variables in their local scope, not global. This reduces side effects that could cause unintended consequences in your code and it also increases the safety of the function by making your code more reusable and “functional.” Remember, computers do exactly what you tell them to, it’s just not always what you want to happen.</li><li><strong>Easily documented data cleaning process</strong> — use Directed Acyclic Graphs or similar flow chart to visualize the data cleaning process you chose. Since the analysis is highly dependent on any filters, aggregations, or transformations you apply to the data, you need a way to communicate your cleaning choices with stakeholders should you need to pivot the direction or make a correction. Always document. This goes hand in hand with version control and naming structures, which should be implemented thoughtfully, but in-depth discussion of that is for another article.</li><li><strong>Simple</strong> is often better than complex. Start there, then iterate. Always get feedback for intermediate steps. Don’t always reach for the flashiest new algorithm, double down on what works. Learn about the <a href="https://en.wikipedia.org/wiki/No_free_lunch_theorem">No Free Lunch Theorem</a>.</li><li><strong>Explainability</strong> — In a production environment, you may not need explainability since the model prediction is all that matters. But in a consulting environment, which is where I find myself, explainability is crucial. If you can’t explain the results of your analysis, no one will believe you, or worse, no one will care about your work. Explainability occurs on two fronts though, the front of model interpretability, and the front of your ability to explain what your models/analysis do and what insights can be drawn from them. Some models are harder to describe than others, but your intuition about them can be developed. Work on both so that people will utilize the fruits of your brain labor.</li><li><strong>Reproducibility</strong> — Write code that is as easy to follow as you can, but not easier. Other people will read and utilize your code, so bear that in mind. You may have to shelf the analysis for 6 months and pick it up again. So do yourself and everyone else a favor and write readable, commented code.</li><li><strong>Consider</strong> <strong>the audience</strong> you are presenting to, what they care about, and how you can persuade them by telling a story about the data and your findings using the data. This is similar to point 4. Maybe it is more important. Learn how to tell a story about the data, and ask yourself if the story is worth telling to the stakeholder at this particular point in time, with your particular project goals in mind.</li><li><strong>The tool </strong>you need may be in another language. Don’t be afraid to learn and don’t get involved in a flame war over what is best. “<em>In medio veritas</em>”. Every language has its strengths. Focus on those and ways to combine them, while keeping the previous lessons in mind (Simplicity, Reproducibility)</li></ol><p>Remember, “Big things have small beginnings.” — David, in <a href="https://www.imdb.com/title/tt1446714/">Prometheus</a>. Consistent effort over a long period of time can deliver out-sized gains. If you can’t start implementing all of these right away, or they don’t make sense to implement in the DS environment you find yourself in, focus on the 1 or 2 that will be most impactful (<a href="https://en.wikipedia.org/wiki/Pareto_principle">Pareto Principle</a>). Implement those and give the world the best you have to offer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=461d435d68d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/7-lessons-learned-for-data-scientists-461d435d68d5">7 Lessons Learned for Data Scientists</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[Today is a day, a beautiful, day]]></title>
            <link>https://medium.com/@carlos.brown3/today-is-a-day-a-beautiful-day-223ad3045c60?source=rss-8003c12d339d------2</link>
            <guid isPermaLink="false">https://medium.com/p/223ad3045c60</guid>
            <category><![CDATA[dogs]]></category>
            <category><![CDATA[world-trade-center]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[career-change]]></category>
            <category><![CDATA[birthday]]></category>
            <dc:creator><![CDATA[Carlos Brown]]></dc:creator>
            <pubDate>Thu, 12 Sep 2019 01:24:17 GMT</pubDate>
            <atom:updated>2020-01-03T18:47:27.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhSv7FBpneDVO5EtUELeVw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bkview?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jason McCann</a> on <a href="https://unsplash.com/search/photos/world-trade-center?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Today is a day, a beautiful day</h3><p>Today, I turn 30. Yesterday, I was a day younger, and now I am a day older. Birthdays have definitely lost the luster they had when I didn’t have so many under my belt. Still, it’s nice to be loved by those closest to you in a special way once a year.</p><h3>The Tragedy</h3><p>I remember that I was with my Dad on the seventh hole of Fort Jackson golf course in Columbia, SC when he received the call to come back to work. He was in the military at the time. We had heard of the first World Trade Center tower getting hit when we were pulling into the golf course, but didn’t understand the import of what had happened, or how our world was going to change. I spent the rest of that day watching news coverage of the tragedy. It was unlike any other day, but in a way since it was my birthday, it was just like all the other days where I age over the course of 24 hours.</p><p>That September 11, I turned 12. I barely knew anything about the world. But I did know that someone hated America enough to kill thousands of its innocent people. I didn’t know what I wanted to do with my life at the time either. I was young, didn’t need to care for myself, and I was processing a tragedy. It seemed so far away. I didn’t really process it all until this year when I visited the 9/11 memorial with my wife and some dear friends for a summer trip. Then, the tears of 18 years ago that had been hidden finally made their showing.</p><h3>Choosing a major</h3><p>When I got to college in 2008, I knew I wanted to do something technical (think STEM), but I wasn’t clear on the route I should take. So, I chose Civil Engineering and stuck with it since I liked it. There’s always a difference between like and love. God waited 10 years until one afternoon, on my honeymoon in Costa Rica with my dear wife, he gave me direction, direction I didn’t have when I walked onto campus that Fall. I didn’t have it because I hadn’t asked for it.</p><h3>Clarity in Costa Rica</h3><p>The Airbnb sat on the top of a hill outside and looking down on San Jose. It was a cozy place with a stunning view of the wild valley of San Jose below, and sunsets that would freeze you in your path with awe. The house had a library with let’s say, an eclectic mix of books. One of which was a book about the Yom Kippur war. I was riveted by the tension of a story told by people who thought that not only themselves, but their entire nation was about to be obliterated by people with immense hatred towards them. I loved the story. Maybe I understood it to some degree. After all, many of my countrymen were killed on my birthday so many years ago. My wife was in the other room. A tremendous feeling rushed over me and I froze in my tracks. It then became clear to me what I was supposed to be doing.</p><h3>A new step</h3><p>Tell stories. I didn’t know what it meant at first, but I knew it was the Word speaking to me. And then the clarity increased as I read more about this technical field I’d heard about for a while, and had always been drawn to. The field is Data Science, and I kept hearing that the best of them know how to tell stories with Data. I never saw this coming, but now my world was changed forever. I’m switching careers from what was good before, and something I’ll cherish forever, to something great. The best even. And even “Tell stories” could encompass so much more than my professional career. I have a feeling it does. But I know what it means for right now, and I’m walking it out. I’m so grateful for it all. Today is a day, a beautiful day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=223ad3045c60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Georgia (and Machine Learning) on my mind]]></title>
            <link>https://medium.com/data-science/georgia-and-machine-learning-on-my-mind-f32669cc090a?source=rss-8003c12d339d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f32669cc090a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bridge]]></category>
            <category><![CDATA[georgia]]></category>
            <dc:creator><![CDATA[Carlos Brown]]></dc:creator>
            <pubDate>Fri, 17 May 2019 13:12:39 GMT</pubDate>
            <atom:updated>2019-06-29T17:06:57.167Z</atom:updated>
            <content:encoded><![CDATA[<h4>Harnessing data for better bridges</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*J6qIvX68rDKEgEYK" /><figcaption>An inspector at work. Photo by <a href="https://unsplash.com/photos/qVZTU3lTKnU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Amogh Manjunath</a> on <a href="https://unsplash.com/search/photos/bridge?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3><strong>Problem</strong></h3><p>Recently, the American Society of Civil Engineers scored the overall health of America’s infrastructure as a D+. Our infrastructure is old. A major facet of this decaying group of assets is bridges. Understanding and managing the condition of these structures is crucial to the continuing goals of the Georgia Department of Transportation (GDOT). To aid these goals, our analysis will build predictive models to see when a bridge is in danger of needing repair or replacement. Our goal is to predict two measures of bridge condition, <strong>condition rating</strong> and <strong>sufficiency rating</strong>, before the inspection occurs, using already available data.</p><p>GDOT (and other DOT’s) will benefit from the analysis in multiple ways.</p><ul><li>A predictive model will allow <strong>early detection</strong> of problems.</li><li>It will allow more <strong>efficient allocation</strong> of bridge inspector resources and may increase the success of the entire bridge inspection pipeline.</li><li>Finally, the predictive model will provide for a <strong>safer infrastructure</strong> network, as we are now using untapped data to ensure the health and safety of the public.</li></ul><h3><strong>Datasets</strong></h3><p>The majority of our data comes from the freely available Bridge Inventory provided by the Federal Highway Administrations National Bridge Inventory (NBI) <a href="https://www.fhwa.dot.gov/bridge/nbi.cfm">here</a>. The data does not include elevation data, which we wanted to include as a feature, so we used the <a href="https://developer.mapquest.com/documentation/open/elevation-api/">Open Elevation API</a> from MapQuest to access this dataset and combine it with the NBI data.</p><h3><strong>Analysis</strong></h3><p>Data science is not a black box, and the best way to avoid it becoming one is to know your data really well. So we begin with Exploratory Data Analysis. First, let’s take a look at the distribution of bridge lengths in the state of Georgia.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*7D5cqTIJ-6tJiEtiFgrcnA.jpeg" /></figure><p>It’s interesting to see that most bridges in Georgia are less than 100 ft long and I bet that goes against your intuition. A takeaway is that not all bridges are like the ones you see crossing the interstate.</p><p>What else do we want to know about bridges? We can take a look at the distribution of years that these bridges were built to get an idea of their age distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Y2gTQNoRG_iGZVEDr_9eRw.png" /></figure><p>We can see that a spike of construction happened in the late 1950’s, early 1960’s. Cool enough, this corresponds to an actual historical event, the passing of the Federal-Aid Highway Act by Dwight Eisenhower. This act created what is now the interstate system in America. Link <a href="https://www.fhwa.dot.gov/infrastructure/50interstate.cfm">here</a>. This is also another reason why our infrastructure in America, and more specifically in Georgia is in great need of repair. A lot of them belong to the Baby Boomer generation.</p><p>Let’s take a look at the distribution of bridges geographically in the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*u0gQG-sikrQTH53t6eA4dA.png" /><figcaption>Atlanta dominates</figcaption></figure><p>Pretty neat, but this one jives with what we expect. Most of the bridges are located around the major metropolitan centers such as Atlanta, Augusta, Savannah, and Macon. Oh, and that blank spot at the bottom? That’s <a href="https://okeswamp.com/">Okefenokee Swamp</a>. Also note the distribution bars at the top and right.</p><p>Let’s also take a look at the distribution of condition ratings and sufficiency ratings, our variables we are trying to predict. Condition Rating is a discrete score from 0 to 9 that is given to each of three locations on a bridge, the Deck, Superstructure, and the Substructure. Think Deck as what a car drives on, Superstructure as mainly the beams that hold the deck up, and Substructure as the piers/columns/abutments that everything else sits on. Sufficiency rating on the other hand is a continuous score from 0 to 100 that is based heavily on condition rating, but also on other geometrical factors. We can see that all three have very similar distributions, and the superstructure seems to be in the best shape relatively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrBTU1wLhVFumgbSDHivyw.png" /><figcaption>Condition Rating</figcaption></figure><h3>Machine Learning</h3><p>In order to predict the bridge ratings, we have to prepare the data to be used in the machine learning models. This is called <strong>Preprocessing</strong>. Most of the time you do not simply dump the data into a black box model and hope for the best. In our case, the features that were selected are the following</p><p><strong>Features</strong>: Latitude, Longitude, Elevation, Age, Structure Length, Design Load, Roadway Width, Annual Daily Traffic (ADT), Percent Trucks, Degrees Skew, Horizontal Clearance</p><p>These features are selected mainly through domain knowledge and are not generated artificially from the dataset. They all represent fairly accessible information about a bridge that an engineer could get access to.</p><p>All of the features are on different scales, and many have outliers, such as we saw in the Bridge Length plot above. These outliers, and the relative scale of the feature, could have oversized effects on the model produced from the data. Since this is not desirable, we use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.QuantileTransformer.html">QuantileTransformer</a> from sklearn.preprocessing to prepare the data.</p><h3>Machine Learning Pipeline</h3><p>For most models in this analysis, a pipeline was constructed with a transformer and <strong>GridSearch</strong> over hyperparameters. The models were fitted to the data using nested cross validation and evaluated on a hold out set. Here is sample code for the Ridge Regression model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88975a72bc953d641b8ae29bdef07a84/href">https://medium.com/media/88975a72bc953d641b8ae29bdef07a84/href</a></iframe><h3>Model Performance</h3><p>The model results after all steps were performed is shown below.</p><p><strong>Regression models</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*U_crpj66Sn1wmlLaNhKjQQ.png" /></figure><p><strong>Classification Models</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*sjk7IV1jPxmdnoZ3k1ZBTQ.png" /></figure><p>Overall we can see that the classification models outperform the regression models. This is mainly due to the Design Load feature. Design Load as used in our model is not truly a continuous variable, but does include new information for the model, therefore a classifier is better able to use the information than regression. The Logistic Regression binary classifier has an advantage over all the other models, which is discussed later.</p><h3>Model Evaluation</h3><p>One of the best ways to evaluate a classifier model is to develop a <strong>confusion matrix</strong>. For all confusion matrices predicting any arbitrary number of n classes, an n x n matrix is developed in which the diagonals represent true predictions and any value off diagonal is an error in prediction. In the case of binary classification (is something, is not something), then the values off the diagonal of the matrix represent false positives and false negatives. The confusion matrix for the Random Forest classifier is a good example of the output, shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*lDNjRdooAbwHRhTuewkgFg.png" /><figcaption>Random Forest, non-random results</figcaption></figure><h3>Best Performing Model</h3><p>We notice that the <strong>Logistic Regression</strong> model — 2 class outperforms all models, but why is it head and shoulders above the rest? There are multiple reasons. One reason is that we mapped the 10 different condition rating values to 2, Poor/Good. If any of the the three locations have a condition rating of 4 or less, then the bridge is rated as Poor. In general, as you reduce the number of classes, the model will perform better and we have shown this to hold true in our case.</p><p>However, the results are not as rosy as they seem. Our 2 class model suffers from a high class imbalance. Referring back to the plots of condition rating above, we can see that when we re-aggregate our target variable into two classes, most of them will be in the class “Good” which means that the condition rating does not represent a deficient rating. Hence, the high accuracy of the logistic regression model is over inflated simply because most values do not belong to the “Poor” class. Metrics such as Precision and Recall will give a more accurate estimate of model performance than accuracy in this case.</p><h3>Conclusion</h3><p>With this analysis, we have shown that we can meaningfully predict the outcomes of bridge sufficiency ratings and bridge condition ratings in the state of Georgia using easily obtainable data from the FHWA. These models can be deployed to aid the DOT in their asset management business and will provide significant value to the department and the taxpayers.</p><p>This article only scratches the surface of the full analysis. Check out the full notebook and supporting code on <strong>Github</strong> <a href="https://github.com/carlosbrown2/Springboard/blob/master/Capstone%20Project%201/Capstone%20Project%201.ipynb">here</a></p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f32669cc090a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/georgia-and-machine-learning-on-my-mind-f32669cc090a">Georgia (and Machine Learning) on my mind</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[Stocks and the Normal Distribution, a second look]]></title>
            <link>https://medium.com/@carlos.brown3/stocks-and-the-normal-distribution-a-second-look-9e76ba1fdb29?source=rss-8003c12d339d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e76ba1fdb29</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Carlos Brown]]></dc:creator>
            <pubDate>Sat, 09 Mar 2019 19:54:55 GMT</pubDate>
            <atom:updated>2019-03-09T19:54:55.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyHqbH6OD_ISpwxKZkLHOA.jpeg" /><figcaption>Tokyo Stock Exchange</figcaption></figure><p><strong>“ truth … is much too complicated to allow anything but approximations.” — John Von Neumann</strong></p><p>Many people are encouraged to invest for retirement by companies, parents, and financial marketers trying to sell their products. More often than not, these people are shuttled to passive index funds as the current golden cow of investing, because actively managed investments typically underperform the indexes net of fees. And since your life is so busy getting the kids to school and planning your next vacation from that job you hate, you should take the easy route and funnel your money the way they tell you. Don’t ask questions!</p><p>There is a different approach, that of taking an active interest in your investments, and participating on a regular basis more than simply looking to make sure your balance has increased from last quarter. One way to invest actively is to trade actively on the stock market, whether through stocks or options. People will day trade, purchase on value investing principles like <strong>Warren Buffett</strong>, short sell, trade options, and many other strategies. Regardless of the theme you choose or the technique you employ, you should know how the markets behave (in general), and to some extent have an idea why they do what they do. Knowing these dynamics will decrease your chances of getting wiped out playing the game.</p><p>This leads us to the Normal distribution, sometimes called the <strong>Gaussian</strong> distribution or the “Bell Curve”. If you have taken a college level math or statistics class, you have probably encountered this distribution before. It is absolutely ubiquitous in the world of finance, and in many other domains it works quite well. For our purposes, it is the main model used to describe the movement of stocks over daily, weekly, and monthly time horizons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*AyeVrRJ-J3adHcRPux6Dpw.png" /></figure><p>You need two things to describe the normal distribution, mean and standard deviation. <strong>Mean</strong> is the measure of the center of the distribution and <strong>standard</strong> <strong>deviation</strong> is a statistical measure of how much the data varies from the mean, or intuitively, how wide the data is. The above normal distribution has a mean of zero and a standard deviation of 1 and is known as the standard normal distribution.</p><h3><strong>Can we use the normal distribution for stocks?</strong></h3><p>One of the common assumptions in investing is that daily, and therefore monthly and yearly stock movements are normally distributed. We can expect that stock movements will sometimes be large, but most of the time they will basically be benign. But do they really behave this way? There is a wealth of data and well established mathematical techniques to help us answer that question. And the answer is important, for people who want greater control over their investments.</p><p>The data we use to answer the question is taken from two major stock indices. Obtaining the data from Yahoo.com, I analyzed the <strong>Dow Jones</strong> and the <strong>S&amp;P 500 </strong>indices as measures of the market as a whole. Let’s plot the data and see what is shows us first.</p><h3>Plotting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*mPxhxZRulGu0g0TSM8g_Eg.png" /><figcaption>Figure 1 — q-q plot (blue=S&amp;P 500, red=normal dist.)</figcaption></figure><p>The above plot shows the quantiles plotted for the sample of stock movements vs the <a href="https://en.wikipedia.org/wiki/Quantile">quantiles</a> for a normal distribution with the same mean and standard deviation as the sample (S&amp;P 500). This way we can easily compare the two to see how close they are. If stock movement is normally distributed, then we would expect there to be little to no deviation of the blue points from the red line. However, we clearly see that the sides, known as the <strong>tails,</strong> are problematic. If we removed that data, then the middle portion would be very well behaved, as it tracks with the normal quantiles shown. But how accurate would our results be if we arbitrarily cut out data to fit what we want the outcome to be instead of letting it speak for itself?</p><p>Plotting is good, but it is not enough. We need to employ the tools of hypothesis testing to definitively answer the question. One test that will be particularly useful is the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.anderson.html"><strong>Anderson-Darling</strong></a> hypothesis test. It is a particularly powerful statistical test that will help us get an even better picture of what Figure 1 seems to be suggesting.</p><h3><strong>Hypothesis Testing</strong></h3><p>We now use the Anderson-Darling test to test for normality, using a hypothesis test with the following setup:</p><p>Significance level = 1.00% (probability of a type 1 error)</p><p><strong>H0</strong>: The data come from a population that is normally distributed</p><p><strong>Ha</strong>: The data come from a population that is not normally distributed</p><p>The Anderson-Darling test will return a test-statistic that we will compare to a critical value at our given significance level of 1%. If the statistic is greater than the critical value, then we reject the null <strong>H0</strong> in favor of the conclusion from our alternative hypothesis, <strong>Ha. </strong>Just<strong> </strong>remember that our significance level indicates the chances of us rejecting a true null hypothesis, which is obviously something we want to minimize. Historically, 5% has often been used, but we will arbitrarily use a stricter standard of 1%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7B1eHFXbdVfe5Z3DCVStQ.png" /><figcaption>Figure 2 — Jupyter Notebook Anderson-Darling Test Output</figcaption></figure><h3><strong>Results</strong></h3><p>After running the test on both the S&amp;P 500 and the DOW, we reject the null in favor of the alternative in both cases. We have good reason to believe that the stock market as a whole does not behave exactly as we would expect if it came from a normal distribution. This tells us nothing about how individual stock prices move in time. For example if <strong>Apple</strong> (<strong>AAPL</strong>) stock does move normally, the market as a whole does not necessarily follow suit.</p><h3><strong>What Gives?</strong></h3><p>So does this destroy modern finance? NO, of course not. But we did just provide evidence that a widely held belief is not completely true. The Normal distribution can be a useful approximation to stock movement, most of the time, but it may not be the best.</p><p>But another important take away is that stock movements, especially in this day of computer algorithm trading, are subject to “Black Swan” events, that Nassim Taleb refers to in his bestselling book <a href="https://www.amazon.com/Black-Swan-Improbable-Robustness-Fragility/dp/081297381X">Black Swan</a>. There are many more players in this market, with more capital, faster reflexes, and different goals than you. Instead of a nice predictable behavior, sometimes stocks can swing wildly in unpredictable ways. The normal distribution fails to capture this behavior when it does occur, because it is by definition unpredictable. But it works pretty well when those events aren’t happening. We can make better, less risky decisions with this information.</p><p>Thanks for reading, I hope this was informative to give a different perspective backed by data. Never be afraid to ask questions. Also, don’t forget to show some love below!</p><p>For access to the code that generated this analysis, check out my <strong>GitHub</strong> repository here: <a href="https://github.com/carlosbrown2/Stock-Normality/blob/master/S%26P500.ipynb"><strong>Stock Normality</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e76ba1fdb29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>