<?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 Andy Lee on Medium]]></title>
        <description><![CDATA[Stories by Andy Lee on Medium]]></description>
        <link>https://medium.com/@ourandy?source=rss-4d1657156354------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Qnc8_fDObd0N1zVn9NIekg.jpeg</url>
            <title>Stories by Andy Lee on Medium</title>
            <link>https://medium.com/@ourandy?source=rss-4d1657156354------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:49:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ourandy/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[Randomness in Sport]]></title>
            <link>https://medium.com/data-science/randomness-in-sport-6e60c6132838?source=rss-4d1657156354------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e60c6132838</guid>
            <category><![CDATA[football]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Andy Lee]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 16:39:39 GMT</pubDate>
            <atom:updated>2020-09-01T14:18:12.403Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why do more teams win the Super Bowl than the Premier League?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGPfy_JebHjhAQf9d6OR3Q.jpeg" /><figcaption>Some are luckier than others. Photo by Izaac Crayton (<a href="https://unsplash.com/@icrayton">@icrayton</a>) on <a href="https://unsplash.com/photos/ShDJMeadsfA">Unsplash</a></figcaption></figure><h3>Cursed</h3><p>Let’s start at Wearside in the Premier League, New Year’s Day 2012. Sunderland have spent the majority of their match against Manchester City camped outside their own penalty box, withstanding furious attacks from City. They’ve only had 3 shots on target compared to 11 from their opponents, and a meagre 41% ball possession over the entire 90 minutes. Their defenders have been chasing shadows- but for the profligacy of Blues striker Edin Dzeko, they would be out of sight.</p><p>Yet somehow, the score remained goalless until the 93rd minute. Sunderland regained possession from a failed City attack, and their midfielders broke past the halfway line for what seemed like the first time in the match. In what must be one of the slowest Premier League counter-attacks ever, Stephane Sessegnon and Ji-Dong Won traded a couple of quick passes, the South Korean striker eventually rounding goalkeeper Joe Hart to fire home. Goal in your game, final score 1–0 to Sunderland.</p><p>Never mind the lack of chances created or shots. Or that City dominated possession, racking up ten corners to Sunderland’s one. The Blues went home with nothing, while Sunderland nicked all three points.</p><p>This, despite post-match replays showing that Ji’s goal was incorrectly awarded despite being offside.</p><h3>Fuelled by Randomness</h3><p>The opening describes a concept loved and loathed by fans from all sports- <strong><em>randomness</em></strong>. In sports, nothing is certain- if it was, the best players and teams would win every single match, and it would lose its appeal as a spectacle pretty quickly. Randomness is what keeps the show going. But what does it mean?</p><p>Simply defined, randomness is a state or pattern which lacks organisation or predictability. An example would be the sampling of number of car accidents in a highly dangerous area, perhaps on a road with a sharp corner, or at a busy junction. You <em>know</em> that these areas experience a higher proportion of accidents compared to others- but do you know exactly <em>when</em> the next accident is about to happen? Do accidents occur at 9:17 am every morning, or when the clock strikes twelve? No one can say for certain. Accidents occur at <em>random.</em></p><p>Similarly, this lack of predictability is what causes millions of fans across the globe to tune in and pay to watch professional sport. Most scoring events in sport are random- NFL touchdowns are random. So are tries in rugby, or goals in football and ice hockey. All the above (and many others) are rare events that take place during a match, often preceded by a single piece of individual skill, bad decision making, or even a moment of pure luck. Moreover, these random events can occur against, or in favour of a team anytime during a match.</p><h3>Relentless</h3><p>Still, the fact that goals are random in football doesn’t stop the better teams from scoring more and winning more matches than others. O<em>ver a longer period of time, skill trumps luck</em>. That’s why the best teams almost always win the league- there are enough matches in this format for luck to “even itself out over the course of a season”, to coin a popular “football man” phrase. Basically, if you have the most money and the best players in the world, you’re much more likely to amass the most points over 30 or so matches.</p><p>To illustrate this, let’s have a look at the number of unique league winners from Europe’s top 5 leagues between 2016–2020:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*xZvwa7JW5Fv5ukk9Kozu5g.png" /><figcaption>Top European football league champions 2016–2020. Image by author</figcaption></figure><p>You don’t need to be a rocket scientist to deduce that the Premier League was the only competition to produce more than 2 winners in total (they had 4). Ligue 1 and La Liga had exactly 2 winners in 5 years, while the Bundesliga and Serie A were completely dominated by a single team.</p><p>Now let’s compare that table with the winners from North American sports:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTKx_AMZHiQAObLLpq8TRQ.png" /><figcaption>North American sports champions 2015–2019. Image by author</figcaption></figure><p>With the exception of the NBA, all other sports produced 4 or more winners over the last 5 years. In fact, the MLB and NFL had 5 unique winners!</p><h3>Do Ya Feel Lucky, Punk?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAGJ4SHbAdXkYznM8Q0TTA.jpeg" /><figcaption>Superb owl. Photo by Geronimo Giqueax (<a href="https://unsplash.com/@ggiqueaux">@ggiqueaux</a>) on <a href="https://unsplash.com/photos/w2WUqRvTmtg">Unsplash</a></figcaption></figure><p>What, then, is the reason for this? Is football so fundamentally different from the other sports in North America? Unlikely- we’ve already established similarities in that goals, touchdowns and tries are all random events.</p><p>One of the reasons why North American sport produces more winners is due to the incorporation of a <em>playoff </em>format after the end of a regular season. Short of adding excitement to the spectacle, playoffs are inherently random. Sure, sometimes the best regular season performers get byes in earlier rounds- but they then either have to beat other teams in a one-off match, or over a series of games, to advance to the next round and to eventually win the tournament.</p><p>Remember what we’ve established earlier- luck plays a greater role over a shorter period of time than in the long-term. Bad officiating decisions, moments of inspired skill by the opposition, and/or missed chances all harm a team much more during a single match (or over a playoff series) than over an entire season. Just like that, it’s Sunderland vs Manchester City all over again! All these conspire to mean the “best” teams don’t necessarily become champions disproportionately to the rest of the field.</p><h3>The Pen is Mightier Than the Sword</h3><p>One final thing- ever wondered why weaker football teams hold on for penalties against stronger teams in knockout competitions, subjecting the audience to 120 minutes of dull play? It’s all to do with randomness again. The weaker team has less chance of pulling off a result against a stronger team at the start- but the longer the match goes on, and the longer the scores remain the same, penalties decide the outcome.</p><p>Short of creating a random number generator in Microsoft Excel to pick a winner, penalties are probably the closest to a 50/50 decider that one can implement during a football match. Think of all the random events that could decide the outcome- a shot going wide, hitting the post, going into the top corner, being palmed away by the goalkeeper. It’s pretty ridiculous to think that this is the best way to separate two teams that have been tied for the whole match- but until someone comes up with a better idea, knockout football tournaments will continue to be blessed- and <em>cursed</em>- by randomness.</p><h3>Other Articles</h3><ul><li><a href="https://towardsdatascience.com/making-up-the-odds-73fbc509ee7f">Making up the Odds</a></li><li><a href="https://towardsdatascience.com/did-liverpool-deserve-to-win-the-premier-league-eda7a4e1b9ca">Did Liverpool Deserve to Win the Premier League?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e60c6132838" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/randomness-in-sport-6e60c6132838">Randomness in Sport</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[Forecasting Football Scores With GgPlot2]]></title>
            <link>https://medium.com/data-science/forecasting-football-scores-with-ggplot2-949de7c1cb52?source=rss-4d1657156354------2</link>
            <guid isPermaLink="false">https://medium.com/p/949de7c1cb52</guid>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Andy Lee]]></dc:creator>
            <pubDate>Mon, 24 Aug 2020 12:24:12 GMT</pubDate>
            <atom:updated>2020-09-01T12:40:40.745Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Poisson to help visualise football correct scores in R</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nA33Kf_SYByN2AAbUUYYZA.jpeg" /><figcaption>Photo by Michael Lee (<a href="https://unsplash.com/@guoshiwushuang">@guoshiwushuang</a>) on <a href="https://unsplash.com/photos/6J7eIvNwttQ">Unsplash</a></figcaption></figure><h3>Horsing Around</h3><p>In one of my earlier posts, I mentioned that the scores in a football match can be approximated somewhat using the <a href="https://en.wikipedia.org/wiki/Poisson_distribution">Poisson distribution</a>, but I didn’t go too much into the topic. Well, you’re in luck today… we’re going to have a look at the subject, and by the end of this post we’ll have Ggplot2 visual illustrating the likely scores of a football match, which really is excellent.</p><p>First off, a little bit on the roots of the Poisson distribution. The discovery of this probability distribution is attributed to <a href="https://en.wikipedia.org/wiki/Sim%C3%A9on_Denis_Poisson">Siméon Denis Poisson</a>, a French mathematician from the nineteenth century. Like many of his contemporaries at the time, he dealt mainly with its theories. It wasn’t until Russian statistician <a href="https://en.wikipedia.org/wiki/Ladislaus_Bortkiewicz">Ladislaus Bortkiewicz</a> published his book <em>The Law of Small Numbers </em>in 1898 that the Poisson distribution became widely used in practice.</p><p>Bortkiewicz famously had access to a data set of the Prussian army over a period of 20 years which recorded the number of soldiers that were killed by their horses’ kicks. Grim.</p><p>Anyway, he showed that these deaths could be approximated by the Poisson distribution, and the rest, as they say, is history.</p><p>Now… how does one go from Prussian cavalry to football scores?</p><h3>Making an Ass of U and Me</h3><p>Let’s first have a look at the basic assumptions that satisfy a Poisson process:</p><ol><li><strong>The probability of an event occurring in a given time interval does not vary with time</strong></li><li><strong>The events occur at random</strong></li><li><strong>The events occur independently</strong></li></ol><p>Now think of goals as an event in a football match. If we had a metric that could express a team’s scoring rate/intensity over 90 minutes, we can say that the first assumption is satisfied. This would’ve been a pain in the arse to define, but thankfully the sports nerds (people a hundred times more intelligent than me, I should add) have come up with <a href="https://fbref.com/en/expected-goals-model-explained/">expected goals</a> (xG) for this. Thanks for today!</p><p>Next question- do goals occur randomly in a football match? That is to say, is there a particular point in time in a match when goals are more likely to be scored? <a href="https://medium.com/@Soccermatics/luck-skill-and-randomness-aaa8d80836ea">This guy</a> says no, and many other <a href="https://www.nytimes.com/2014/07/08/science/soccer-a-beautiful-game-of-chance.html#:~:text=It%20involves%20hundreds%20of%20skillful,victory%20is%20a%20single%20goal.">articles and studies</a> also suggest that goals <em>do </em>occur at random in a football match. In practice, goals might not be as random as one might think but… we have enough evidence to argue that they are, so let’s tick that box and move on for now.</p><p>Now for the final assumption- that being, goals are independent of one another. If a team is behind, surely the players are working harder to get back into the game to score an equaliser. Or perhaps if a team is already leading by 5 goals, the players might take their foot off the gas and let one in due to complacency. Either way, you have to say that goals <strong><em>don’t</em></strong> occur independently of one another, and using a basic Poisson process to model football scores starts to break down here.</p><p>There are techniques to adjust for goal dependencies in a match, but we all have day jobs- so let’s leave that for another day… and agree for now that two out of three isn’t bad (also, I’m pushing to generate useful content innit, so here we are). For further reading, I suggest having a look at this <a href="https://dashee87.github.io/data%20science/football/r/predicting-football-results-with-statistical-modelling/">fantastic blog post</a> that has basically done a Bortkiewicz for football, showing you can approximate the number goals scored over a season with the Poisson distribution.</p><h3>Hoof</h3><p>In my <a href="https://towardsdatascience.com/did-liverpool-deserve-to-win-the-premier-league-eda7a4e1b9ca#h1">previous post</a> on xG, I created a simple Poisson model to help predict the outcomes of a football match (home win, draw, away win) in R. We’re going to use something similar here, but focus more on obtaining the probabilities of the correct scores as an output.</p><p>R has come a long way from its base heat map libraries which haven’t aged too well. Ggplot2 is a fantastic package which allows for all sorts of graphs and charts to be built. In order to use them, we have to first install some dependencies in RStudio:</p><pre>install.packages(&#39;tidyr&#39;)<br>install.packages(&#39;dplyr&#39;)<br>install.packages(&#39;scales&#39;)<br>install.packages(&#39;ggplot2&#39;)</pre><pre>library(&#39;tidyr&#39;)<br>library(&#39;dplyr&#39;)<br>library(&#39;scales&#39;)<br>library(&#39;ggplot2&#39;)</pre><p>Cool, now let’s go back to one of our original assumptions- that teams have a constant scoring rate over 90 minutes in a football match. We’ll be using the shot-based xG taken from <a href="https://projects.fivethirtyeight.com/soccer-predictions/champions-league/">FiveThirtyEight’s model</a> for the Champions League quarter-final between Barcelona and Bayern Munich (oh boy…). Let’s construct and source a ScoreGrid:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9e59a970dc4c0f0b707f9fe452cebae/href">https://medium.com/media/e9e59a970dc4c0f0b707f9fe452cebae/href</a></iframe><p>We’ve created a data frame with 11 columns and 11 rows, each entry representing a correct score. So the entry in [<strong>row <em>i </em>, column <em>j</em></strong>] is going to be the score <strong><em>i,j</em></strong><em> </em>with <strong><em>i</em></strong><em> </em>being the home score and <strong><em>j</em></strong><em> </em>as the away score. Hence entry [<em>1,2</em>] is going to be a 2–1 win for the away team. dpois helps to generate a random Poisson probability for each score <em>i</em>, given the homeXg and awayXg. Finally, we cap the individual scores at 9, and once we get to 10 we’re going to sum the probabilities together and group them as a single entry. It just makes things easier.</p><p>Let’s give it a quick spin. In the RStudio console, type</p><pre>ScoreGrid(1.7,1.1)</pre><p>and you should get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*LYfVcdQTgqhLD1idju0RqA.png" /><figcaption>Football correct score grid. Image by author</figcaption></figure><p>Nice grid, but not too easy on the eye.</p><h3>Robert Lewangoalski</h3><p>Let’s build the correct score visual now. We’re going to use geom_tile() in Ggplot2, which generates a nice heat map at the end. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01feb1a047b75e0ff93a268205f1f9ea/href">https://medium.com/media/01feb1a047b75e0ff93a268205f1f9ea/href</a></iframe><p>Ggplot2 requires the input data to be a tidy dataframe, so the conversion from base R data.frame takes place on line 10 with pivot_longer. Next, we’ll need to convert all our vars to factors and sort the levels in the correct order (remember that <em>10+</em> is a factor, using as.numeric will just cause it to become an NA. We want it to be the final level in the list). This is done on line 14 with ~forcats::fct_relevel. Everything beyond that just contains the usual building blocks of a Ggplot2 graph.</p><p>Right, here we go. Fire up the R console and enter the team names and xG inputs from wherever your source was from:</p><pre>ScoreHeatMap(&quot;Barcelona&quot;, &quot;Bayern_Munich&quot;, 1.2, 5.6, &quot;FiveThirtyEight&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*cafndS1XwgPL1hOdsYmExw.png" /><figcaption>Barcelona vs Bayern Munich correct scores visualisation. Image by author</figcaption></figure><p>Men against boys in this match, and just by looking at the visualisation/heat map you can see the most likely score would have been 5–1 to Bayern Munich based on xG. In reality, Bayern actually won 8–2. <a href="https://www.youtube.com/watch?v=rbk4K2OIe0g">Robert Lewangoalski</a> indeed.</p><p>One more to illustrate a closer match, yesterday evening’s Champions League final between Paris Saint-Germain and Bayern Munich:</p><pre>ScoreHeatMap(&quot;Paris_SG&quot;, &quot;Bayern_Munich&quot;, 1.4,1.6,&quot;FiveThirtyEight&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*1xzQqbSYxjA0KM4YqmnSxQ.png" /><figcaption>Paris Saint-Germain vs Bayern Munich correct scores visualisation. Image by author.</figcaption></figure><p>A much tighter match, with 1–1 being the most probable score- Bayern Munich actually won 1–0.</p><h3>A Stable Model</h3><p>As always there are several caveats, one of which we’ve already discussed- namely that goals aren’t independent of one another, so the model is worth revisiting. Also, if any one of those xG chances had a different result (i.e. a shot hit the post or went wide instead of going in), we likely <a href="https://en.wikipedia.org/wiki/Butterfly_effect">wouldn’t be here speaking about this today</a>… Let’s not forget too how xG itself is a flawed metric which doesn’t capture a lot of the nuances within a football match.</p><p>Still, these visuals are a nice representation of how a match might have turned out- if anything, it’s a good exercise in using some of the impressive R libraries for graphics and visualisation.</p><p>As usual, you can nick all of this on my Github repository if I struggled to make any sense. Cheers for today…</p><h3>Other Articles</h3><p><a href="https://towardsdatascience.com/did-liverpool-deserve-to-win-the-premier-league-eda7a4e1b9ca">Did Liverpool Deserve to Win the Premier League?</a></p><h3><strong>R Code for Football Correct Score Visualisations</strong></h3><p><a href="https://github.com/ourandy/blog-repo">ourandy/blog-repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=949de7c1cb52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/forecasting-football-scores-with-ggplot2-949de7c1cb52">Forecasting Football Scores With GgPlot2</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[Did Liverpool Deserve to Win the Premier League?]]></title>
            <link>https://medium.com/data-science/did-liverpool-deserve-to-win-the-premier-league-eda7a4e1b9ca?source=rss-4d1657156354------2</link>
            <guid isPermaLink="false">https://medium.com/p/eda7a4e1b9ca</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[football]]></category>
            <dc:creator><![CDATA[Andy Lee]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 10:04:33 GMT</pubDate>
            <atom:updated>2020-09-01T12:29:45.131Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Premier League Season Review Using Python, R, and Expected Goals</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5MLvKtmcAFQVP7pTmCAyqw.jpeg" /><figcaption>Photo by Shaun Donnelly (@<a href="https://unsplash.com/@shaunyness">shaunyness</a>) on <a href="https://unsplash.com/photos/bIyzFopbVOg">Unsplash</a></figcaption></figure><blockquote>I returned, and saw under the sun, that the race is not to the swift, nor the battle to the strong, neither yet bread to the wise, nor yet riches to men of understanding, nor yet favour to men of skill; but time and chance happeneth to them all.</blockquote><p><strong>Ecclesiastes 9:11</strong></p><h3>I Expect Gifts for Christmas</h3><p>What happens if a football team massively over-performs and wins the league by a country mile? How do we know if they won by luck, or if they were just <em>that </em>much better than everyone else?</p><p>One of the metrics in football that the sports analytics industry developed over the last 10 years to assess performance is the much-fabled expected goals (xG). The idea is that a goal being scored is just one of a number of outcomes that could have happened (shot hits the crossbar, keeper saves, shot goes wide, foul, etc.). Now I don’t want to go too much into detail over the xG definition (FbRef has a great explanation and method of computing it <a href="https://fbref.com/en/expected-goals-model-explained/#:~:text=Very%20simply%2C%20xG%20(or%20expected,what%20angle%20on%20the%20pitch%3F">here</a>) as there are many differing opinions available on what an xG is, or how to calculate it.</p><p>For simplicity, let’s think of xG as an indicator of how well a player has taken a shot (or chance) that might result in a goal. A player with a 1-v-1 chance against the goalkeeper? High xG. A midfielder takes a shot on goal from 40 yards past a wall of players? Low xG. Penalty? High xG. A shot taken from near the corner flag? Low xG.</p><p>Professional football clubs have been using xG to track performance for a few years now, as opposed to simply drawing conclusions by looking at the final result. It’s slowly <a href="https://www.bbc.com/sport/football/50822875">made its way to the media</a> to help inform debate- although maybe try avoiding it when <a href="https://www.youtube.com/watch?v=JBWKGij9Y5A#t=26s">speaking to certain pundits</a>.</p><p>Now that we’ve established xG, the goal (<em>no pun intended</em>) of this project is to determine how well teams have performed in the 2019/20 Premier League season, relative to their final position- <em>specifically,</em> if Liverpool were deserving winners. We’re going to need a few things for this:</p><ol><li><strong>xG data from matches in the Premier League this season</strong></li><li><strong>A football model for outcome probabilities (home win, draw, away win)</strong></li><li><strong>Fancy charts</strong></li></ol><h3>Scrapy</h3><p>First off, let’s get the xG data. <a href="https://fbref.com/en/comps/9/schedule/Premier-League-Scores-and-Fixtures">FbRef</a> are a fantastic open source site for this, and they are powered by <a href="https://statsbomb.com/">StatsBomb’s</a> model (who many consider as one of the best in the industry). There are two ways of getting the xG data in the link above, the first being the method below which uses Scrapy in Python. In xg_spider.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02296ddb278109da9e413bfa6e4bec73/href">https://medium.com/media/02296ddb278109da9e413bfa6e4bec73/href</a></iframe><p>Now type this into the terminal:</p><pre>scrapy crawl expectedGoals --output exG.csv</pre><p>Let’s clean up the data in R (I <em>know</em> we could do this all in Python, but I already had a Scrapy scraper ready and most of my models were already in R):</p><pre>install.packages(&quot;tidyr&quot;)</pre><pre>prem1920&lt;-read.csv(&quot;exG.csv&quot;)</pre><pre>#get rid of empty rows<br>prem1920&lt;-prem1920[rowSums(is.na(prem1920)) == 0,] </pre><pre>#separate delimiter by hyphen into two columns<br>tidyr::separate(prem1920, score, into = c(&quot;homeScore&quot;, &quot;awayScore&quot;)) </pre><p>Et voila, you now have a csv with the Premier League 2019/20 xG data!</p><p>Or… you could just have easily used Microsoft Excel to copy and paste those tables and clean the data into a csv manually.</p><h3>Football Model</h3><p>Right, here’s where it starts to get interesting. Football scores can be approximated using a Poisson distribution. I don’t want to go into detail as there’s plenty of literature online, and if you want to check out code in Python or R that describes the approximation process, <a href="https://dashee87.github.io/data%20science/football/r/predicting-football-results-with-statistical-modelling/">this is a great site for it</a>.</p><p>Anyway, we can use R’s in built <a href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/Poisson.html">Poisson package</a> to calculate the correct score of a football match, given the scoring rate of either team. Open up a file called FootballMatchResult.R:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f418ef224bc4ec5c203039153a94e5d9/href">https://medium.com/media/f418ef224bc4ec5c203039153a94e5d9/href</a></iframe><p>This simple Poisson model doesn’t actually fit the data as well as you would like because the low scores and draw probabilities are much more likely than the model makes them but… in the interest of time, let’s leave that for another day.</p><p>Using this model, we can now derive a team’s expected points (xPts) in a match. In the first match (Liverpool v Norwich City) for instance, Liverpool had 1.9 xG and Norwich City were assigned 1.0- now given a team gets 3 points for a win and 1 for a draw, we may derive the match outcome probabilities by typing</p><pre>FootballMatchResult(1.9,1.0)</pre><p>into the R console, which would output the home win, draw, and away in probabilities in a vector:</p><pre>[1] 0.5840664 0.2210540 0.1948797</pre><p>So if we wanted to compute Liverpool’s xPts, we would multiply the first entry by 3 and add the middle entry. Same goes for Norwich City, but in their case, it would be multiplying the final entry by 3 and adding the middle one.</p><h3>The League Table Does Not Lie</h3><p>Let’s compute each match from the prem1920 data frame into an xPts table to see how well the teams performed based on their xG in a match. We’ll sum up three attributes and sort them into a league table. The attributes are: expected points (xPts), expected goals scored (xG_For) and expected goals against (xG_Against). Here’s the code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5fa1676b41f65f231cc51854297deb/href">https://medium.com/media/9d5fa1676b41f65f231cc51854297deb/href</a></iframe><p>With the magic of <a href="https://rstudio.com/">RStudio</a>, fire off</p><pre>xPts&lt;-ExpectedPointsTable(prem1920)</pre><p>into the terminal. We’re now able to derive this xPts table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*l-O8JI6Q5HnvPoW15mybGw.png" /><figcaption>2019/20 Premier League xPts Table</figcaption></figure><p>Contrast that with the actual, final league table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*OIa7yexy56hi227ejgLvOg.png" /><figcaption>2019/20 Premier League Final Table</figcaption></figure><h3>It’s Coming Home</h3><p>Right, where do we even begin? Let’s first of all answer the question if Liverpool deserved to win the league this year. Sadly for the mighty Reds, according to the xPts table the answer is a resounding <em>no</em>. They didn’t even come 2nd in the table based on xPts- Chelsea were expected to finish ahead of them based on xG!</p><p>Manchester City absolutely blew everybody away this year on performance, scoring 102 goals against 93.1 xG and letting in pretty much the number of goals they were expected to concede (35 against an xG of 35.2). Their xPts was pretty accurate as well, 81.89 against an actual tally of 81. That’s more than 10 xPts ahead of 2nd place! Pep Guardiola can consider his team extremely unlucky this year- but hey, they got their UEFA Champions League ban overturned, so swings and roundabouts.</p><p>The top four teams were, well, the top four teams- except that Manchester United should probably have finished in fourth instead of third place. However, the xPts table projected that they had the second best defence in the league after their city rivals, so <a href="https://www.youtube.com/watch?v=bsAl0JjFvU8">maybe David de Gea and Harry Maguire aren’t that bad after all</a>…</p><p>Despite Leicester City’s disappointment at missing out on a Champions League spot on the final day of the season, the xPts table suggests that they had a great year and ultimately finished where they should have. The same can’t be said of Spurs, unfortunately. They finished sixth, but the xPts table suggests that they weren’t even a top half team! Jose Mourinho seemingly has a lot to do to improve his team (as well as his own reputation)…</p><h3>Better Lucky Than Good</h3><p>Now we’re discussing the bottom teams. Watford surely must feel particularly hard done by- they did more than enough to stay clear of the bottom three spots. Bournemouth were another team who might feel like they deserved to stay up this year according to the xPts table.</p><p>Norwich City’s performances probably warranted a bit more as well, although perhaps not enough to survive another year in the Premier League. If I were a coach or a staff member on the books of the recruitment team at Aston Villa, Crystal Palace, or West Ham, I would be looking over my shoulder, somewhat worried about my team’s prospects next season if nothing changes during the summer break.</p><p>Yet none of them should be as worried as Newcastle United. Although they pretty much matched their projected goals numbers, they finished rock bottom in the xPts table with the lowest projected xG. Somehow Steve Bruce’s side managed to nab 8 points more than they deserved, which was enough to pull them clear into safety. Just goes to show how fine the margins are between staying up and being relegated!</p><p>There’s one final trick left in the book. We can use R to simulate 1,000 seasons based on the xPts table (code not included, as I <em>swear</em> the lights in my home must’ve started flickering due to the power required to run the sims off my boilerplate code). Here’s the final position heatmap based on 1,000 season simulations (V1 = first place, V2 = second place, and so on). The more pink the colour, the more times a team finished in that particular position:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*DmBHHfQt9z4caz7sy0-sLg.png" /><figcaption>Premier League Simulated Positions Heat Map</figcaption></figure><p>Manchester City have basically cemented first place, with few challengers (Liverpool and Chelsea were the closest to dethroning them). It looks like Manchester United have become Arsenal during Wenger’s middle years at the club, whilst Arsenal have become… the Spurs of the early 2000s. At the other end of the table, Newcastle United were firmly anchored to the bottom places, rarely making it out of the final 4 or 5 positions.</p><p>Really makes you think…</p><h3>Caveat</h3><p>While xG has become one of the analytics industry’s standard indicators to forecast team performance, it’s probably wise to discuss its limitations now- as well as those of this project.</p><p>The first is that there are several ways of defining an xG- none of the firms seem to agree on the best way to compute it. Some analysts might add more weight to an xG based on the angle of the chance, whereas some might penalise a long shot more than others, and so on. Think about it this way- everybody knows what a goal is. The same goes for a yellow card, or a corner. They’re all well-defined, tangible statistics. But what is an xG? Until this is standardised, it will continue to be an issue.</p><p>Next- every model has limitations, and our naive Poisson football model is no exception. It assumes independence between goals in a match- for instance, if a goal has been scored, it does not influence the outcome. In reality, this is just nonsense- if you’re a player, you would change approach if there has been a goal in your game. As a result, a team chasing a match where they are 1–0 down will behave differently than one with a two goal cushion. There needs to be some computation for dependency in the model for it to be more useful. Just remember the classic football cliche- <em>goals change games</em>.</p><p>Finally, is xG <em>really</em> that great an indicator of a team’s performance? Amongst other limitations, the metric does not account for individual players (or their relative skills). At the end of the day, most xG models are built off a database of thousands of shots and chances- the final output will be an average, not specific to the player. For argument’s sake, just think that a striker, in general, should have a much better finishing rate than a defender in certain positions. Then there might be some players who are <a href="https://www.youtube.com/watch?v=BC-WGSeynp8">much better at taking certain types of chances than others</a>. This is where the metric starts to break down, and understanding this is key to getting the most out of xG.</p><p>So… did Liverpool deserve to win? Who cares really- it still happened. At the end of the day, despite everything, the only thing that matters is still the result.</p><h3>Other Articles</h3><ul><li><a href="https://towardsdatascience.com/randomness-in-sport-6e60c6132838">Randomness in Sport</a></li><li><a href="https://towardsdatascience.com/making-up-the-odds-73fbc509ee7f">Making up the Odds</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eda7a4e1b9ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/did-liverpool-deserve-to-win-the-premier-league-eda7a4e1b9ca">Did Liverpool Deserve to Win the Premier League?</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[Making up the Odds]]></title>
            <link>https://medium.com/data-science/making-up-the-odds-73fbc509ee7f?source=rss-4d1657156354------2</link>
            <guid isPermaLink="false">https://medium.com/p/73fbc509ee7f</guid>
            <category><![CDATA[history]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[sports-betting]]></category>
            <dc:creator><![CDATA[Andy Lee]]></dc:creator>
            <pubDate>Tue, 21 Jul 2020 08:38:49 GMT</pubDate>
            <atom:updated>2020-09-01T12:38:45.912Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>From Bayes to Betfair: A Short History</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3GXQyxdKNrNbD-S34vaYA.jpeg" /><figcaption>Photo by Richard Boyle (<a href="https://unsplash.com/@hellorich">hellorich</a>) from <a href="https://unsplash.com/photos/wu7oy6XhAoU">Unsplash</a></figcaption></figure><p><strong><em>Note from the editors:</em></strong><em> This article is for educational and entertainment purposes only. If you want to use the presented model for real bets, do so at your own risk. Please make sure that this is in alignment with the terms and conditions of your bookmaker.</em></p><h3>When Saturday Comes</h3><p>It’s quarter-to-three on a Saturday afternoon. You’ve given up your ticket to the football match this weekend, deciding not to follow your dad to the ground as you have another appointment later in the evening (at least that’s what you’ve told him- the <em>truth</em> is, you can’t be bothered to watch your team play rubbish again).</p><p>Still one thing to do before kick-off though. Whipping out your mobile, you open up the *<em>insert favourite bookies’ name here</em>* app to view what the bookie makes your team’s odds to win this weekend. <em>Relentlessly</em>, you scroll through the betting coupons, looking at the match odds of many a team across the land. All of a sudden, you experience one of those inquisitive moments, wondering (not for the first time) “<em>why these odds are what they are</em>”. It would be nice to know a little more about the thoughts and processes that go into pricing these matches, given that you’re always trying to pick winners every weekend.</p><p>Anyway, you select your three teams for the accumulator. £10 on at 15/2. <em>This is the one</em>.</p><p>5 p.m arrives, and the results are in- two of the teams win, and the third comes away with an unlucky draw. Your acca lay in ruins. Seething, you put your phone away to prepare for your evening appointment. Your housemate, sensing the disappointment, reminds you “two out of three isn’t too bad”. You try to distract yourself for the rest of the day from the bad result. Right now, you couldn’t care less about those bloody odds.</p><h3>Meet Your Maker</h3><p>While the above plot reads more like a responsible gambling advert than the start of a post on probability concepts, there are two things I mentioned that actually tie in with the rest of this story. The first is that many people are curious about how the odds of sporting, political and entertainment outcomes are generated- they’re constantly being told that the bookies always win, and you bet against them at your peril. The second is the phrase “what the bookie makes your team’s odds to win”. S<em>urely</em> a multi-billion pound industry doesn’t rely on employees simply “making up the odds”? To answer this, we need to look at some probability history and theory (I’m absolutely aware that this is where I start to lose most readers to cat videos on social media).</p><p>Let’s begin with a simple coin toss. Assuming the coin is fair, how does one go about deriving the probability of heads or tails? It’s 50/50 classic pick’em heads or tails, right?</p><p>You’re right of course, but perhaps not in the way you think. What we all know as a 50/50 shot in a coin toss is actually its <em>theoretical </em>probability. Given a fair coin, we assume that there are two equally likely ways for the coin to land, and only one way to get heads or tails. The only way to prove this is to run a large number of independent trials of coin tosses, obtain the results of heads and tails from those outcomes, and then- by the <a href="https://en.wikipedia.org/wiki/Law_of_large_numbers">law of large numbers</a>- we estimate the true probability of heads or tails to be 50%. Simple enough right?</p><p>The idea of an event’s probability being equal to its relative frequency after repeating a similar process a large number of times is actually known as the <a href="https://en.wikipedia.org/wiki/Frequentist_probability"><em>frequentist</em></a> interpretation of probability. This way of thinking by <a href="https://en.wikipedia.org/wiki/John_Venn">mathematicians</a> came about in the 1800s, primarily motivated by <a href="https://en.wikipedia.org/wiki/Classical_definition_of_probability#Criticism">problems and paradoxes</a> from past experiments and treatises on games of chance. Its roots lay even deeper than the nineteenth century though- you can dig out a quote from <a href="https://www.amazon.co.uk/Art-Rhetoric-Collins-Classics/dp/0007920695/ref=sr_1_3?crid=26W8N6XM2KE6Z&amp;dchild=1&amp;keywords=rhetoric+aristotle&amp;qid=1595132337&amp;sprefix=rhetoric%2Caps%2C329&amp;sr=8-3">Aristotle</a> where he mentions that</p><blockquote>…the probable is that which for the most part happens…</blockquote><p>Difficult to argue with a who’s who of mathematics and philosophy really. However, there is one issue, mainly that probabilities are discussed by frequentists <em>only</em> when dealing with well-defined random experiments.</p><h3>As Sure as Night Follows Day</h3><p>Here’s where the bookmakers start to lick their lips. Consider the <a href="https://en.wikipedia.org/wiki/Sunrise_problem">sunrise problem</a>: “What is the probability that the sun will rise tomorrow?” One has no access to experiments now. This is <em>pieces</em> for us isn’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULjisWzcWGEKPJNUbbVHiQ.jpeg" /><figcaption>Photo by James Peacock (<a href="https://unsplash.com/@jimmyp9751">jimmyp9751</a>) from <a href="https://unsplash.com/photos/AxYOB1v9TsU">Unpslash</a></figcaption></figure><p>Thankfully, two mathematicians (well, one mathematician and one… clergyman) contributed to this solution. First, <a href="https://en.wikipedia.org/wiki/Pierre-Simon_Laplace">Pierre Simon-Laplace</a> answered this in two parts. The first part is what we now know as the principle of indifference, or principle of insufficient reason. For argument’s sake, let’s say you’ve woken up at noon one day, two thousand years in the past. After a lovely afternoon meal and coffee, you watch the sun go down- thanks for today. Will it come back? We haven’t seen the sun rise, and there isn’t a particular reason to believe it will or won’t. So, we consider the two probabilities (will the sun rise yes/no) equally likely- that is, one-half that the sun rises again, and one-half that it won’t.</p><p>Now on to the second part of Laplace’s answer. If the past is any guide to the future, every day that the sun rises increases our confidence that it will continue to do so. Hence, after two thousand years, the probability that the sun will rise tomorrow should be very close to one, but not quite, as we can’t be completely certain. Laplace derives the <a href="https://en.wikipedia.org/wiki/Rule_of_succession">rule of succession</a> from this thought experiment, estimating that the probability the sun will rise again having risen <em>n</em> times as</p><figure><img alt="Laplace’s rule of succession" src="https://cdn-images-1.medium.com/max/76/1*bLdU6Ac_wIcG7A44t8Z9lg.png" /></figure><p>When <em>n </em>is zero, this is just one-half, and as <em>n </em>increases to infinity, the probability approaches one. A bit more detailed than the coin toss example, but still quite straightforward.</p><p>Or is it?</p><p>Did you notice how we came up with the initial probability of one-half that the sun would rise again?</p><p>It was plucked out of thin air. No experiments were run. No outcomes were counted from as a whole. <strong><em>We made it up</em></strong>. It could have been one-third, three-quarters, anything between zero and one in fact. Such practice is acceptable due to the mathematical writings of Thomas Bayes, an English Presbyterian minister (!) from the eighteenth century. He described probability not as a frequency, but rather as a <em>degree of belief</em>. It’s up to you what you make the prior probability of an outcome, as via Bayesian inference, you’re allowed to update your existing beliefs when new evidence arises to obtain your posterior beliefs (much like the example of the sun rising above).</p><p>Bayes actually died without publishing <a href="https://en.wikipedia.org/wiki/Bayes%27_theorem">the theorem that made him famous</a>, but enough of his disciples dug out his writings which helped to benefit entire industries over the next two hundred years. It’s even been used to solve practical questions that have changed history- the defenders of <a href="https://en.wikipedia.org/wiki/Dreyfus_affair">Captain Dreyfus</a> used it to prove his innocence, whilst <a href="https://en.wikipedia.org/wiki/Alan_Turing">Alan Turing</a> used it to decode the enigma machine during the Second World War. Bayes is highly revered, so much so that “Bayesianism” has garnered an almost religious following amongst its members in the community of mathematics and science.</p><h3>Let’s All Meet up in the Year 2000</h3><p>Anyway, now that we’ve brought meaning to the phrase “an educated guess”, we come back to the question of how bookmakers price up events and outcomes. When the industry hires “traders” for a particular event, what they really mean is to employ somebody with extensive domain knowledge on a subject or sport, whose opinions hopefully count for more than the general population. In short (and I’m not belittling the profession at all), traders are<em> </em>really<em> professional guessers</em>. How likely are Liverpool to win against Bournemouth this weekend? Eight to one-on, they’re really good and the other team aren’t. Who wins the Champion Chase this year? Probably Sprinter Sacre at three to one-on, he’s got form. Who’s going to be the next President of the United States? Donald Trump is two-to-one, for some reason or another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jy0ogoC5i02x2XwxHfjgFg.jpeg" /><figcaption>York Racecourse. Photo by Chris Kendall (<a href="https://unsplash.com/@chriskendall">chriskendall</a>) from <a href="https://unsplash.com/photos/4vetVkqmj90">Unsplash</a></figcaption></figure><p>As a trader, you’re hoping your knowledge gives you an edge over the rest of betting market when pricing up an event. When you change the odds for whatever reason, you’re actually making use of <em>Bayesian inference</em> to update an initial hypothesis as more information comes in (mainly “following the weight of money”, another phrase that often comes up whenever bookmaking is discussed). But what if a trader isn’t confident enough in his or her odds of an event?</p><p>If you know, you know, and if you don’t, well.. short of a P45, the answer is to let someone <em>shrewder </em>make up the odds. In June 2000, a betting exchange called Betfair was launched with the idea of making betting fairer for customers, but also partly with this goal in mind. Anyone could now request a market (football match result, next Prime Minister of the United Kingdom, Bitcoin’s price at the end of the year) that didn’t already exist, make up their own odds, and stake commensurately given their confidence that an event will occur (e.g. £100 at 5/1 represents a bigger belief in something occurring than £2 at 5/1). It’s then up to somebody else to take the other side of that bet, and once a significant sum of money had exchanged hands between thousands (if not millions) of speculators, you suddenly have very good probability estimates of a certain outcome. Whether bookmakers or bettors knew it or not, they all began engaging in a huge proof-of-concept of Bayes’ theorem overnight.</p><p>A final aside, but Betfair actually received a lot of negative publicity when they first launched, as traditional bookmakers weren’t best pleased with their <a href="https://www.theguardian.com/sport/2002/jan/13/horseracing.tonypaley">choice of slogan</a> and lobbied to get exchanges banned- citing all sorts of excuses, from cheating to money laundering. Nowadays, there are three or four large betting exchanges, and many high street bookmakers wait for their odds before committing to anything. Funny how things turn out sometimes.</p><h3>#RequestABet</h3><p>Every history piece normally ends with some sort of review of what we’ve learnt and forecast for the future. Well, we’ve just discussed Bayes and I haven’t got a clue what’s going to happen next. Our mate Laplace would probably request a market on what will happen in the next ten years on Betfair, stake some cash on the selections he feels most likely, and log back in periodically until 2030 to find out whether he was correct or not. That really would be excellent for me- I’ll enjoy that much more than having to guess an outcome myself to conclude a blog post.</p><h3>Other Articles</h3><ul><li><a href="https://towardsdatascience.com/randomness-in-sport-6e60c6132838">Randomness in Sport</a></li><li><a href="https://towardsdatascience.com/forecasting-football-scores-with-ggplot2-949de7c1cb52">Forecasting Football Scores With GgPlot2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73fbc509ee7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/making-up-the-odds-73fbc509ee7f">Making up the Odds</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[Optimisation in Python to Reduce Mean Squared Error]]></title>
            <link>https://medium.com/analytics-vidhya/solving-our-python-basketball-model-d89edfb83f79?source=rss-4d1657156354------2</link>
            <guid isPermaLink="false">https://medium.com/p/d89edfb83f79</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sports-betting]]></category>
            <dc:creator><![CDATA[Andy Lee]]></dc:creator>
            <pubDate>Wed, 15 Jul 2020 05:29:19 GMT</pubDate>
            <atom:updated>2020-09-01T12:47:16.664Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revision</h3><p>Right, what state did we leave <a href="https://medium.com/analytics-vidhya/predicting-basketball-results-using-python-and-docker-9630d7c3be56">our model</a> in?</p><figure><img alt="Lebron James" src="https://cdn-images-1.medium.com/max/900/0*HI77BHVzPYOXcexF" /><figcaption><strong>Where were we, indeed?</strong></figcaption></figure><p>If you recall, we were using bookmaker spread inputs for basketball matches to forecast teams’ winning probabilities. After an intense Docker build that left a carbon footprint ten times larger than Greta Thunberg’s worst enemies combined, we built a basic basketball model based on <a href="https://www.amazon.co.uk/Mathletics-Gamblers-Enthusiasts-Mathematics-Basketball/dp/0691154589/ref=sr_1_2?dchild=1&amp;keywords=mathletics&amp;qid=1594744092&amp;sr=8-2">Wayne Winston’s Mathletics</a>. From there we deduced that our model’s four-match Chinese Basketball League forecast had a mean-squared error (MSE) of 2.13 compared to the actual market output.</p><p>I glossed over the MSE metric in my previous post because it was off-topic, but in this post I’m going to go through some of its concepts.</p><h3>What Is This MSE You Speak Of</h3><p>As always, Wikipedia puts the <a href="https://en.wikipedia.org/wiki/Mean_squared_error">definition of MSE</a> into words far more efficiently than I would be able to. MSE is a <a href="https://en.wikipedia.org/wiki/Loss_function#Expected_loss">risk function</a>, computing the average of the squares of errors between an estimate and its actual values.</p><p><em>Alright mate, care to explain that in plain English though please?</em></p><p>…so we have our Python Basketball model, which we are using to forecast the win probabilities off the initial spreads. This is our <em>estimator. </em>The win probabilities that we obtained from the betting markets (in our case, Pinnacle Sports) are our <em>observed values</em>, in other words, values which are taken to be true (now, they may or may not be “true” but… let’s not worry too much about that at the moment).</p><p>Now stop and think about this for a second. How do we know that our estimator is actually, well, accurate? It’s easy enough to confirm accuracy if a model produces values that are no different to those observed. While true, this is basically saying that somebody’s built a model that perfectly captures reality. Is that really possible? Pretty unlikely I’d say. Much more realistic would be an acceptance that there are some costs- for instance assumptions that were too simple (or completely wrong)- associated with a model. And that’s what a risk function is- it computes this specific loss of information in the form of a single value to the user. The MSE is just a special case of this.</p><h3>Make y=M<em>x</em>+C Great Again</h3><figure><img alt="Graph illustrating observed and expected values" src="https://cdn-images-1.medium.com/max/581/0*SV41mV2WoPexVcKh" /><figcaption><strong>Graph illustrating observed and expected values</strong></figcaption></figure><p>Let’s generalise a little. I was too lazy to derive my own graph from a charting library so I nicked this example from the excellent <a href="https://www.freecodecamp.org/news/machine-learning-mean-squared-error-regression-line-c7dde9a26b93/">Free Code Camp</a>. This is the infamous <strong><em>y=Mx+C</em></strong>. Hopefully you might have seen this in school, but in case you weren’t paying attention (or in case you dropped out to pursue a career much more successful than some bloke writing about MSE) then this is what’s represented in the graph:</p><ul><li><strong>Purple dots</strong> are points on the graph, each point has an x and y coordinate. These are your observed values</li><li><strong>Blue line </strong>is the prediction line, covering the estimated values of the model</li><li>The <strong>red line</strong> between each purple point and the prediction line are the <strong>errors. </strong>Each error is the distance from the point to its predicted point.</li></ul><p>And now let’s have a look at the MSE formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*tnSFGMEsrpnb753jc_ha6Q.png" /><figcaption><strong>uhm…</strong></figcaption></figure><p>It seems like we’ve gone on a tangent to a foreign language now, which is exactly what the strange “E” is in the above image- it’s the Greek symbol for sigma. This represents the sum of the sequence of all numbers from the first (<em>i=1</em>) to the last (<em>i=n</em>) . At each data point <em>x</em> (these would be the purple dots on the graph, and in our case, the Pinnacle win probabilities for each basketball match), we subtract its corresponding value <em>x’</em> on our line (which are the model’s estimates of the win probabilities- note that the graph of our basketball model’s expected values isn’t a straight line, but don’t worry about this), and then square it. The MSE is a result of the sum of all these squares.</p><p>And that’s it for our GCSE refresher!</p><p>Alright, we’ve established that MSE computes the loss of information between actual and estimated value of a model. In an ideal world, our model would perfectly mimic real life, right? I know I said it wasn’t very likely earlier, but… given fair or sound enough assumptions, it is possible to <em>minimise</em> the MSE. We can get this value by way of solving for a model’s parameters, such that the MSE is as close as possible to zero.</p><p>So how do we go about implementing this solver? We won’t have to innit, cuz somebody has already done it for us in Python- which really <em>is </em>excellent.</p><h3>Cheating</h3><p>Finally! Time to dust off our code editor and get back to our model. You’ll be glad to know that we don’t need to change any of our <strong>Dockerfile</strong> build, as the <a href="https://hub.docker.com/_/python">python:3 image</a> from Docker Hub that we used from my initial post is sufficient. Thankfully lower carbon emissions this time.</p><p>I’ve also refactored the API call from my last post (there was more boilerplate in there than a 1940s newspaper business). Don’t worry about that though, you’ll always be able to nick my <a href="https://github.com/ourandy/python-basketball">GitHub code</a> and do it better if I’ve written something disgraceful.</p><p>Here are the two new imports required for our solver:</p><ol><li><a href="https://numpy.org/"><strong><em>Numpy</em></strong></a><strong><em>, </em></strong>a Python library which adds support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.</li><li><a href="https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html"><strong><em>Optimize</em></strong></a><strong><em>, </em></strong>a SciPy sub-package which provides several commonly used optimization algorithms.</li></ol><p>Let’s get straight into the <strong>__init__.py </strong>file<strong> </strong>once more and add these two lines to the top:</p><pre>import numpy as np<br>from scipy import stats, optimize</pre><p>We’ve setup the API with Flask in the previous post so all we need to do is to code up the endpoint and implement the solver.</p><pre>class Minimize(Resource):</pre><pre>   def solve(self, spread, expected, std_dev):<br>       spread = np.array(spread)<br>       expected = np.array(expected)</pre><pre>       def mse(s):<br>           estimated = stats.norm.sf(0.5, spread, scale=s)<br>           mse = np.sum(np.power((estimated - expected), 2)) / spread.size<br>           return mse<br>       optimal_solution = optimize.minimize(mse, std_dev, method = &#39;BFGS&#39;)</pre><pre>       return optimal_solution</pre><p>Whoa whoa, what’s going on here? As per the Flask framework, we’re creating a class called <strong>Minimize </strong>for this endpoint. But why <strong>np.array </strong>instead of a normal Python list? Well, NumPy arrays take significantly less amount of memory as compared to Python lists. It also provides a mechanism of specifying the data types of the contents, which allows further optimisation of the code.</p><p>Now we’re getting to the bit that matters. Remember our model’s inputs? The first was a list of spreads from Pinnacle (which we can’t change), and the second and only variable we have is the standard deviation, which we specified as 12.0. This value of 12.0 actually gave us an MSE of 0.00213 (right, I know I said 2.13 in the original post- I multiplied them by 100 to make things simpler), so we want to know if it’s possible to make the MSE smaller by changing this value. This is what <strong>optimize.minimize</strong> does for us- it’s solving for an optimal standard deviation. We’re using the <a href="https://en.wikipedia.org/wiki/Broyden%E2%80%93Fletcher%E2%80%93Goldfarb%E2%80%93Shanno_algorithm">BFGS</a> algorithm, which I believe is <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize">the default if not selected</a>.</p><figure><img alt="Heavy industrial work" src="https://cdn-images-1.medium.com/max/1024/1*7A4Bn84JfPfrUYz8yZYDmQ.jpeg" /><figcaption><strong>My machine’s memory at work every time I run a Docker build for a Python image</strong></figcaption></figure><p>Cool, time to code up the POST request. We’ve defined three inputs that need to go in:</p><ol><li>The array of spreads</li><li>The array of actual win probabilities</li><li>Standard Deviation (any floating value will do, this will be the value that is optimised)</li></ol><p>Add this bit within the <strong>Minimize </strong>class:</p><pre>def post(self):</pre><pre>    parser = reqparse.RequestParser()<br>    parser.add_argument(&#39;spread&#39;, action=&#39;append&#39;, type=float, required=True)<br>    parser.add_argument(&#39;expected&#39;, action=&#39;append&#39;, type=float, required=True)<br>    parser.add_argument(&#39;std_dev&#39;, type=float, required=True)<br>    args = parser.parse_args()<br>    res = self.solve(**args)</pre><pre>    return {&quot;optimum&quot;: res.x[0],&quot;fun&quot;: res.fun,&quot;message&quot;: res.message}, HTTPStatus.OK</pre><pre>api.add_resource(Minimize, &#39;/minimize&#39;)</pre><p>Everything looks cool except maybe the “return”<strong> </strong>bit. Have a look at the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.OptimizeResult.html#scipy.optimize.OptimizeResult"><strong>OptimizeResult</strong></a> object in the SciPy documentation. There are plenty of attributes in the object, but essentially the results that matter to us are:</p><ol><li>The optimised standard deviation, which is the solution of the optimization. This is our “optimum”.</li><li>Value of the objective function, which is basically the minimised MSE value. This is the “fun”.</li><li>The “message” to confirm whether or not the operation terminated successfully.</li></ol><p>Great! Let’s POST to the endpoint http://localhost:5000/minimize with the following inputs from our matches as the body:</p><pre>{</pre><pre>&quot;expected&quot;:[0.8091, 0.7785, 0.7708, 0.7692],</pre><pre>&quot;spread&quot;:[10.5, 9.5, 10, 8.5],</pre><pre>&quot;std_dev&quot;:12.0</pre><pre>}</pre><p>And then let’s have a look at the response…</p><pre>{</pre><pre>&quot;optimum&quot;: 11.708226529461706,</pre><pre>&quot;fun&quot;: 0.00018173060393236452,</pre><pre>&quot;message&quot;: &quot;Optimization terminated successfully.&quot;</pre><pre>}</pre><p>Nice! So we’ve reduced MSE from 0.00213 to 0.00018, which is quite a substantial decrease. In the process, we’ve found the optimal standard deviation for our dataset to be 11.71. Speaking in layman’s terms, it means that the bookmaker spreads that we are using as predictors for the win probabilities work best when we input a standard deviation of 11.71.</p><p>So this is great, right? We can now go around grabbing spreads from bookmakers for our model, plugging 11.71 as a standard deviation and deriving the win probabilities from them, making ourselves rich in the process, right?</p><h3>Stop Right Now, Thank You Very Much</h3><p>Nah, we can’t really do that. Remember at the start of this post I alluded to a model “perfectly capturing reality”? Well, we have to ask ourselves a few questions about what “reality” means. First off, is the Chinese Basketball League a fair representation of the sport of basketball in general? Even if we compare it to the NBA alone, there are numerous rule differences and player standards. This immediately casts some doubt when blindly overfitting our model to match these data points. And this doesn’t even go into the fact that, as I mentioned in my first post, we only have 4 data points- and when you actually compare the estimates, the last two are significantly further from the observed values than the first two. It’s impossible to draw any concrete conclusions from such a small sample size!</p><p>Then we have another valid question. What makes Pinnacle’s win probabilities more acceptable as our model benchmark, as opposed to your mate down the pub’s opinions on the Chinese Basketball League- or anybody else for that matter? This is quite a complicated question, and the answer involves a <a href="https://en.wikipedia.org/wiki/Bayesian_probability">theory that has split mathematicians and their interpretation of probability since the 18th century</a>. In any case… it’s comforting to know that a substantial amount of the mathematics community absolutely does not agree with probability being interpreted as a degree of belief, hence rendering most of this work complete heresy!</p><figure><img alt="Andrew Gelman, American statistician" src="https://cdn-images-1.medium.com/max/250/0*o3c8K4-TUz3q-wQK.png" /><figcaption><strong>This bloke does <em>NOT</em> approve of your probability models</strong></figcaption></figure><p>There’s one final nail in the coffin to follow, and that’s the shortcomings of MSE itself. Like variance, MSE carries the disadvantage of heavily weighting outliers, a result of the squaring of each term. This effectively adds more weight to larger errors than smaller ones. Think of it along these lines: an error twice as big will be penalised four times as much. An error five times as big will be penalised twenty-five times as much. Not a desirable metric then really, is it?</p><h3>Silver Lining</h3><p>Don’t worry, you haven’t read this far for me to declare that the whole post was a waste (or at least, I hope it wasn’t). First off, MSE does indeed have its faults- but the truth is that there is no perfect error metric. The way you compute your loss of information when estimating a model’s values will depend on several things, most of them out of the scope of this post. If you are indeed interested to find out more about error estimates and the maths and theory behind them, and also which functions to use in specific cases, <a href="https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0">this post</a> is pretty good.</p><p>Secondly, I don’t want to be <em>that </em>guy, but… remember the quote that “all models are wrong, but some are useful”? With regards to the utility of a simple model like this, it really depends what your end goal is. If you want to beat the NBA Vegas money lines and spreads then you’ll be sorely disappointed- millions of dollars from professional gamblers go through every line, much of which represent some pretty shrewd opinion and information. You can’t expect some bloke’s open source Python code on Medium to be better than these punters!</p><p>On the other hand, if there are other derived betting markets likes outrights or futures which require win probability estimates, I don’t see why you couldn’t use this model (in his book, Winston does exactly that to forecast the San Antonio Spurs vs Cleveland Cavaliers playoff final in 2007). If anything, you could just play around with the standard deviation on any particular matchday to see if the market’s win probabilities tally with the bookmaker spreads, which might give you some information as to where bettors and bookmakers are placing themselves in the market.</p><p>Ultimately, what it comes down to is this- having a model in any field helps inform your decisions better than someone without one. It’s up to you what you make of it, and how to improve its estimates- or even how to build a better one. I’m hoping this post has helped a little with that decision process.</p><p>Cheers for today!</p><h3>Other Articles</h3><p><a href="https://medium.com/analytics-vidhya/predicting-basketball-results-using-python-and-docker-9630d7c3be56">Predicting Basketball Results Using Python and Docker</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d89edfb83f79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/solving-our-python-basketball-model-d89edfb83f79">Optimisation in Python to Reduce Mean Squared Error</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Basketball Results Using Python and Docker]]></title>
            <link>https://medium.com/analytics-vidhya/predicting-basketball-results-using-python-and-docker-9630d7c3be56?source=rss-4d1657156354------2</link>
            <guid isPermaLink="false">https://medium.com/p/9630d7c3be56</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[sports-betting]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[nba]]></category>
            <dc:creator><![CDATA[Andy Lee]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 14:53:11 GMT</pubDate>
            <atom:updated>2020-09-01T12:45:49.197Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>We’re going to build a basic predictive model in Python which calculates the winning probabilities between two teams in a basketball match. In order to verify its accuracy, we’ll be comparing the model’s output to actual bookmaker odds. This model is going to be a simple REST API which runs inside a Docker container (I mean, it <em>is </em>2020 after all).</p><p>Just in case you don’t already know, here’s an overview of the tech stack for this project, not at all nicked from Wikipedia:</p><p><strong><em>Python</em></strong> is an interpreted, high-level, general-purpose programming language. It’s designed to be easy to read and simple to implement.</p><p><strong><em>Docker</em> </strong>is a set of platform as a service (PaaS) products that uses OS-level virtualization to deliver software in packages called containers.</p><h4><strong>Docker Setup</strong></h4><p>Having the Docker engine on your machine is a prerequisite for this project, so if you haven’t already done so you’ll have to <a href="https://docs.docker.com/engine/install/">install and setup Docker</a> on your machine. The instructions will be slightly different depending on which operating system you’re running on, so do give the documentation a good read when going through the install and setup.</p><p>Once you’re done with the process, open your terminal and type</p><pre>docker --version</pre><p>and if it returns something other than your Docker version, well… you’ll have to go through the setup process again because something probably went wrong.</p><p>After Docker is installed, you’ll want to create your working directory. I’ve called mine ‘python-basketball’ but of course you can call it anything you want. Now in order for Docker to work, we need to create two files in this directory: a <strong>Dockerfile</strong> (note there is no file extension at the end) and <strong>docker-compose.yml</strong> file. I won’t go into too much detail on what these are, but essentially a Dockerfile is a simple text file that contains the commands a user could call to assemble an image whereas Docker Compose is a tool for defining and running multi-container Docker applications.</p><p>The <strong>Dockerfile</strong> setup is pretty simple, and we can assemble our image in the same way as the <a href="https://hub.docker.com/_/python?tab=description">official Python page</a> from the Docker Hub repository - just changing the name of the run script. The file should look like this:</p><pre>FROM python:3</pre><pre>WORKDIR /usr/src/app</pre><pre>COPY requirements.txt ./</pre><pre>RUN pip install — no-cache-dir -r requirements.txt</pre><pre>COPY . .</pre><pre>CMD [ “python”, “./run.py” ]</pre><p>Our <strong>docker-compose.yml </strong>will look like this:</p><pre>version: &#39;3.4&#39;<br>services:<br>  probability-calculator:<br>    build: .<br>    volumes:<br>      - &#39;.:/usr/src/app&#39;</pre><p>Finally, create a <strong>run.py</strong> file in the same directory with a simple hello world output:</p><pre>print(&quot;Hello World&quot;)</pre><p>Oldest trick in the book. Anyway, that’s all you actually need to run a Python program in Docker. If you go back to your terminal and type</p><pre>docker-compose up </pre><p>Et voila, you should get a lovely “Hello World” printed to your console!</p><p>You’ve managed to run an application inside of a Docker container, without the hassle of having to actually install Python (or any of its tools and dependencies), and minus the overheads of managing a virtual machine.</p><p>Cool innit?</p><h3>Let’s Actually Build The Model</h3><p>OK, let’s get started and actually write some code.</p><p>We’re going to be using a few packages to help us in this project:</p><ol><li><strong><em>Flask</em>,</strong> a micro-framework to help build web applications.</li><li><strong><em>SciPy</em></strong>, a Python-based ecosystem of open-source software for mathematics, science, and engineering.</li></ol><p>Normally we would need to use pip to install these packages manually in Python- however as we’re using Docker, all we need to do is add them as requirements and they’ll install automatically when the Docker image is built. Create a file called <strong>requirements.txt </strong>in your working directory. Add the following lines to the file:</p><pre>Flask==0.12.2<br>scipy==1.4.1<br>flask-restful==0.3.6</pre><p>Now we need to create a folder which represents the package holding our Python code for the model. I’ve called this folder ‘probability_calculator’. In order that Python knows that this is a package and not just a random folder, we need to create a file called <strong>__init__.py</strong>. To start off this file add the following:</p><pre>#import the SciPy framework<br>import scipy.stats as sp</pre><pre>#import the Flask framework<br>from flask import Flask, g<br>from flask_restful import Resource, Api, reqparse </pre><pre>#create an instance of Flask<br>app = Flask(__name__) </pre><pre>#create the API<br>api = Api(app)</pre><h4>The Model</h4><p>Right, now we’re getting into the meat of the code, which is building the actual model. This model is based on <a href="https://www.amazon.com/Mathletics-Gamblers-Enthusiasts-Mathematics-Basketball/dp/0691154589">Mathletics</a> by Wayne Winston- he explains that in the NBA, the historical standard deviation of match results about a prediction from a rating system is 12 points. In other words, the likelihood of the actual margin between two teams in any given match can be described by a bell-shaped probability distribution centred on the pre-match spread. Where would we get these spreads? Well, the online gambling boom means we’re able to get them fairly easily from online bookmakers.</p><p>Thanks to Covid-19, there are no NBA matches until the end of July. We’ll have to make do with the next best thing- the Chinese Basketball Association! Here are Pinnacle’s prices from Wednesday, 24th June 2020:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*nEGTCX4srOOE2UK73HAG5w.png" /><figcaption><strong>Pinnacle Odds for Chinese Basketball Association Matches</strong></figcaption></figure><p>We have four matches, all of which have spreads (the “Handicap”). Let’s take the first match as an example- In the first match, We have Shanghai Sharks and Liaoning Flying Leopards separated by a spread of 10.5 points, meaning the Flying Leopards need to beat the Sharks by 11 points or more for the bet to win.</p><p>The “Money Line” is the probability of either team winning. Given the 10.5 point spread in favour of the Flying Leopards above, Pinnacle have given the Sharks decimal odds of 4.92, which means they have a 20.3% chance of winning. The Flying Leopards have decimal odds 1.161, which translates to a 86.1% chance of winning.</p><p>Just a minute, these probabilities sum up to 106.3% - aren’t probabilities meant to sum to 100%? True, but bookmakers make their money off the <a href="https://en.wikipedia.org/wiki/Mathematics_of_bookmaking">overround</a>, which is basically the percentage they build into selections to make it worthwhile for them to lay a bet. Just to make it easy for us, we’re going to use secondary school maths to normalise these percentages by ratios. We’ll end up with the following win probabilities for each team:</p><p>Shanghai Sharks: 19.09%<br>Liaoning Flying Leopards: 80.91%</p><p><em>Phew, these Chinese names are a mouthful. Where’s a crisp NBA team name like the “Minnesota Timberwolves” when you need one?</em></p><h3><strong>Back To The Code</strong></h3><p>Now that we know the spread and winning probabilities that the bookmakers have given these two teams, it’s time to get back to work in Python.</p><p>We can hard-code the standard deviation to be 12.0 (it’s probably slightly different in the Chinese League than the NBA, but let’s leave that for another day). Next, we need to generate the winning probabilities. These will be based off a normal distribution (also known as a Gaussian Distribution) centred around the mean of the bookmaker’s spread, together with the given standard deviation. Get back to <strong>__init__.py</strong> and let’s write up the model:</p><pre>STD_DEV = 12.0</pre><pre>def calculate_probability(spread, std_dev):<br>    return sp.norm.sf(0.5,spread, std_dev)</pre><p>This function just returns the probability that a team wins by 1 or more points given the bookmaker spread and standard deviation. You can read up on this in <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html">SciPy’s documentation</a> on the normal distribution.</p><p>Next up, the actual model request. It’s going to be a HTTP POST request which makes use of flask-resftul, an extension of the Flask package which provides tools to build an API quickly. The way it works is this:</p><ol><li>User creates a class for each endpoint</li><li>User then creates a function for each method to be accepted</li></ol><p>With that in mind, here’s the request coded up with a 200 status code and message if successful:</p><pre>class WinProbability(Resource):</pre><pre>def post(self):<br>    parser = reqparse.RequestParser()<br>    parser.add_argument(&#39;spread&#39;, required=True, type=str)</pre><pre>    args = parser.parse_args()</pre><pre>    favourite_win = calculate_probability(float(args.spread),  <br>    STD_DEV)<br>    outsider_win = 1 - favourite_win</pre><pre>    return{&#39;message&#39;: &#39;POST really was excellent&#39;,    <br>    &#39;favouriteProbability&#39;: favourite_win, &#39;outsiderProbability&#39;:<br>    outsider_win}, 200</pre><p><em>That really is excellent.</em></p><p>Last bits before we test the model and response, don’t forget to add this resource at the end of the file:</p><pre>api.add_resource(WinProbability, &#39;/winProbability&#39;)</pre><p>And now let’s actually remove the “Hello World” child’s play from the <strong>run.py </strong>file and replace it with our application instead:</p><pre>from probability_calculator import app</pre><pre>app.run(host=&#39;0.0.0.0&#39;, port =80, debug=True)</pre><p>Finally let’s expose port 5000 for this application in <strong>docker-compose.yml </strong>at the end:</p><pre>ports:<br>  - &#39;5000:80&#39;</pre><p>And now we’re good to go!</p><h3><strong>Testing the Model</strong></h3><p>First off, we’ll need a <a href="https://www.slant.co/topics/7913/~rest-api-clients#2">REST client</a> to test our HTTP requests- I’m using Postman for this but you can use any that you like.</p><p>Enter the project directory, fire up the terminal, and type</p><pre>docker-compose up</pre><p>to start the app.</p><p>Now using our REST client let’s hit port 5000 with a POST request with content-type set to application/json and the body below:</p><pre>{&quot;spread&quot;: 10.5}</pre><p>If all goes well, you <em>should</em> get this response:</p><pre>{</pre><pre>&quot;message&quot;: &quot;POST really was excellent&quot;,</pre><pre>&quot;favouriteProbability&quot;: 0.7976716190363569,</pre><pre>&quot;outsiderProbability&quot;: 0.20232838096364314</pre><pre>}</pre><p>But how do we verify that these probabilities are, well, actually useful?</p><p>We’re going to compare them against Pinnacle’s match result market from earlier. Going back to the win probabilities we recorded earlier for the Shanghai Sharks and Lianoning Flying Tigers, we can see that we had the Sharks at 19.09% and Flying Tigers at 80.91%. That’s not too far away from 20.2% and 79.8%. Nice! I guess we can start our own bookmaking business now, right?</p><p>Not so fast. First of all we need to quantify how far away from the expected probabilities our model’s outputs actually are. There are several ways to do this, but a nice way would be to use the <a href="https://en.wikipedia.org/wiki/Mean_squared_error">mean squared error</a> (MSE) of the sample data. In the interest of time and as it is slightly off-topic, the sum of squared errors (SSE) is exactly that- the square of all the model’s errors when compared to actual data, summed. When you divide that sum by the amount of data points, you get the MSE. For this example, the squared error would be</p><p><strong><em>Match 1 squared error = (19.09 - 20.24)² = 1.3225</em></strong></p><p>We’ll have to run a our model against all four matches to compare the results and obtain the MSE. Now we could write another Python module for this, or we could do what the non-masochists would by this point and crack out an Excel spreadsheet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLoF-5USk9k6CagvtFb8cQ.png" /><figcaption><strong>SSE and MSE of Model Outputs</strong></figcaption></figure><p><em>Note we only need to take four data points as the model was only run four times for the favourite’s probability. The outsider’s probability is just the complement, i.e. 1-Probability that favourite wins.</em></p><p>MSE from the dataset is 2.13- maybe we’re not quite ready to launch our own sportsbook business just yet.</p><h3>Conclusion</h3><p>Phew. We’ve come a long way from setting up Docker on our OS- we now have a basketball model built in Python, running on its own Docker container! That really is excellent.</p><p>Now the question is what can be done to improve the model? I can think of a few things already:</p><ol><li>Standard deviation of the dataset might not necessarily be 12.0</li><li>There’s no way that a sample data of 4 is enough to justify any model</li><li>Initial assumptions might be too simple- can you really predict basketball results off a Gaussian distribution? Might there be better ways of modelling basketball outcomes?</li><li>Code error handling is non-existent (but also, life is short)</li></ol><p>Otherwise, I think this is a good attempt at predictive modelling for basketball. If my blog post was rubbish and you would rather just rip my code, feel free to do so at my <a href="https://github.com/ourandy/python-basketball">Github repository</a>.</p><p>Thanks for today!</p><h3>Other Articles</h3><p><a href="https://medium.com/analytics-vidhya/solving-our-python-basketball-model-d89edfb83f79">Optimisation in Python to Reduce Mean Squared Error</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9630d7c3be56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/predicting-basketball-results-using-python-and-docker-9630d7c3be56">Predicting Basketball Results Using Python and Docker</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>