<?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 Oscar Sanchez on Medium]]></title>
        <description><![CDATA[Stories by Oscar Sanchez on Medium]]></description>
        <link>https://medium.com/@osanchez2323?source=rss-d09022cdc09d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Eq19FOZKIP6wkpLWVJh9Og.png</url>
            <title>Stories by Oscar Sanchez on Medium</title>
            <link>https://medium.com/@osanchez2323?source=rss-d09022cdc09d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:51:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@osanchez2323/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[Web Scraping NBA Stats]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@osanchez2323/web-scraping-nba-stats-4b4f8c525994?source=rss-d09022cdc09d------2"><img src="https://cdn-images-1.medium.com/max/2600/0*PXjAd7v7y5LOwZrE" width="3543"></a></p><p class="medium-feed-snippet">No data set? No problem. A quick overview on how to scrape data using Python to create your own data set.</p><p class="medium-feed-link"><a href="https://medium.com/@osanchez2323/web-scraping-nba-stats-4b4f8c525994?source=rss-d09022cdc09d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@osanchez2323/web-scraping-nba-stats-4b4f8c525994?source=rss-d09022cdc09d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b4f8c525994</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Oscar Sanchez]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 15:05:28 GMT</pubDate>
            <atom:updated>2019-03-18T21:18:17.718Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Basketball Analytics: Predicting Win Shares]]></title>
            <link>https://medium.com/data-science/basketball-analytics-predicting-win-shares-7c155651e7cc?source=rss-d09022cdc09d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c155651e7cc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[nba]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Oscar Sanchez]]></dc:creator>
            <pubDate>Thu, 14 Feb 2019 20:16:49 GMT</pubDate>
            <atom:updated>2019-02-15T18:02:42.529Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Machine Learning to Predict the Individual Win Shares of Top NBA Players</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1FqCbbDVyu6fYl0_s_6GA.jpeg" /></figure><p>Recently, Daryl Morey made the claim that LeBron James is the greatest basketball of all time. And apparently, it’s not even close. Morey is the current general manager of the NBA’s Houston Rockets. For all you baseball fans out there, Morey is the Billy Beane of basketball. For all you movie lovers, Morey is the basketball equivalent to the guy Brad Pitt played in <em>Moneyball</em>. And if you didn’t understand the previous two sentences, then you might need to do some<a href="https://en.wikipedia.org/wiki/Daryl_Morey"> research</a>. To put it short, Morey is a huge analytics guy. So when he talks about LeBron James’ achievements, it means that in basketball analytics, or <em>Moreyball</em>, terms, LeBron is the greatest to ever do it (try telling that to Skip Bayless).</p><p>The biggest question I drew from Morey’s remarks: how does he measure which player is better than the next? Is it success? Impact? Efficiency? (Morey loves efficiency more than Billy Beane loves<a href="https://www.youtube.com/watch?v=DtumWOsgFXc"> on-base percentage</a>).</p><p>Today, there are plenty of new basketball metrics used by fans and analyst worldwide to compare and measure players. For example, there is Player Efficiency Rating (PER)<strong><em> </em></strong>which takes into account accomplishments, such as field goals, free throws, 3-pointers, assists, rebounds, blocks and steals, and negative results, such as missed shots, turnovers and personal fouls.</p><p>Some of these advanced basketball metrics, such as PER, are great to measure how efficient a player can be in a basketball game. But does that tell us that the player will bring success to their team? Maybe. But the only way a player can be seen as successful is by winning.</p><p>Win shares is a great start to show how much overall success a player brings to their team. According to<a href="https://www.basketball-reference.com/about/ws.html"> Basketball-Reference</a>, win shares is a metric that estimates the number of wins a player produces for his team throughout the season. To put that into perspective, Kareem Abdul-Jabbar is both the single season leader in win shares with 25.4 win shares and all-time career leader in win shares with 273.4 win shares. So, I’m sure you understand this measure could potentially be a good indicator of how much success a player contributes to their team.</p><p><strong>NOTE</strong>: All code used for this post can be found on GitHub, organized on this<a href="https://github.com/osanchez2323/Portfolio/blob/master/Basketball%20Analytics%20-%20Machine%20Learning%20to%20Predict%20Win%20Shares/Basketball%20Analytics%20-%20Using%20Machine%20Learning%20to%20Predict%20Win%20Shares.ipynb"> notebook</a>.</p><h3>Analysis</h3><p><strong>Objective: Can we predict individual win shares of NBA players using other basketball metrics?</strong></p><p>The data used for this analysis is from the 2016–17 and 2017–2018 NBA Season, using<a href="https://www.basketball-reference.com/"> Basketball-Reference</a>. Essentially, I used data from the 2016–2017 NBA season to create our model and stats from the most recent season to predict win shares. I performed a <strong>supervised regression</strong> machine learning analysis:</p><ul><li><strong>Supervised</strong>: The data had win shares and all other basketball metrics included to train and test the models</li><li><strong>Regression</strong>: Win Shares is a continuous variable</li></ul><p>Today, there are plenty of new basketball metrics used by fans and analysts worldwide to compare and measure players. In order to predict Win Shares, I used a mix of basic and advanced NBA stats:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*fmRTNr_oSGBeZ8bgpOPdTA.png" /></figure><h3>Exploratory Data Analysis</h3><ul><li><strong>What did the distribution of win shares originally look like?</strong></li></ul><p>Before continuing the analysis, I used basic EDA to see what our data can tell us first hand. First, I took a quick look at the distribution win shares:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*0d-Q2PkrkaW0Vl58ANqWYA.png" /></figure><p>Right away, we see that the distribution of win shares is skewed to the right. The majority of NBA players during the 2016–2017 NBA season had win shares of less than 5. This makes sense since only a selected few, mostly composed of NBA All Stars, will have very high win shares. For example, the win shares leader of the 2016–2017 NBA season was James Harden,the runner-up for MVP, with 15 win shares. So, it’s an elite status to have a high win shares.</p><p>The odd takeaway from the distribution is the number of players with 0 win shares. After further analysis, I was able to find that there was a high number of players that barely played at all. Although these players are on NBA rosters, that doesn’t mean they will not have significant impact to both the team and their own individual stats. Therefore, I updated the data to only include players that had played at least 30 games and averaged at least 25 minutes of playing time per game. Here’s what the distribution of win shares looks like after cleaning out the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*ArjsQhlKVD6YWJlq2U_HgA.png" /></figure><p>There’s a lot less players with 0 win shares now! The distribution of win shares is still right-skewed, but looks a bit more normally distributed.</p><ul><li><strong>Were all the features I chose good predictors of win shares?</strong></li></ul><p>I analyzed this question by using the Pearson Correlation Coefficient, which measures the linear correlation between the features and target (win shares). It has a value between -1 and +1, where a value close to -1 represents a negatively strong relationship and a value close to +1 represents a positively strong relationship:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*bsNum5u7697JzEbRhC-ojg.png" /></figure><p>This discovery was surprising! Of the 13 basketball metrics I originally chose to predict win shares, 4 of them did not have a strong enough correlation (strong = greater than 0.5 &amp; less than -0.5). Therefore, I excluded those metrics from my model.</p><p>I was stunned to see 3-Point percentage (3P%) have not only a weak correlation, but also a negative correlation. In today’s NBA, almost every team and player relies heavily on the 3P, so I assumed 3P% would play an important part in the analysis. Another interesting finding was the weak relationship between games played (G) and win shares. One would assume that the more games a player is involved in, the higher their win shares would be. However, just because a player is involved in a game, doesn’t mean they will have success. Assists (AST) was another metric that I assumed would have a strong relationship with win shares.</p><ul><li><strong>Were the remaining features highly correlation with one another?</strong></li></ul><p>For the next part of the analysis, I wanted to see whether the features were strongly correlated with one another, or multicollinearity.<a href="http://www.statisticshowto.com/multicollinearity"> Multicollinearity</a> generally occurs when there are high correlations between two or more predictor variables. Remember, features having a strong correlation with win shares is good, but features being strongly correlated with other features might not be that helpful. It can even make it tougher to interpret the models we will be creating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiNPfv7zhRUGiR-NBjGqRA.png" /></figure><p>Based on the PairPlot above, I found some issues between the features:</p><ul><li><strong>VORP vs BPM:</strong> has a very strong positive relationship (correlation of 0.98).<a href="https://www.basketball-reference.com/about/bpm.html"> Box Plus Minus (BPM)</a> is a player’s contribution per 100 possesions over the league average when the player was on the court. Value Over Replacement Player (VORP) takes BPM and translates it into minutes based contribution to a team. In order to calculate VORP, you need to use BPM. Therefore, they are highly correlated.</li><li><strong>Shooting Percentage Metrics:</strong> We had three shooting percentage metrics left in the analysis. Field goal percentage (FG%) is a ratio of field goals made to field goals attempted. Effective field goal percentage (eFG%) adjusts field goal percentage to account for the fact that three-point field goals count for three points while field goals only count for two points. True shooting percentage (TS%) measures a player’s shooting efficiency by calculating two- and three-point field goals and free throws. I felt that these metrics were closely related (TS% and eFG% had a correlation of 0.90). Therefore, I decided to only use TS% since it had the highest correlation with win shares.</li></ul><p>After exploring the data, I was left with the following basketball metrics as the features that were used for creating the models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*48Jhc0MZEeUeBeTUsSC-Mw.png" /></figure><h3>Model Selection and Testing</h3><p>Since this was a supervised regression machine learning analysis, I created three regression models:</p><ul><li>Linear Regression</li><li>Support Vector Regression</li><li>k-Nearest Neighbors Regression</li></ul><p>Making the test set 25% of the data (the rest of the data to train the model), here were the results of the models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*wEWTP90cM8lNQ56Q7ZI1DA.png" /></figure><p>And, the clear winner of these models: linear regression. The linear regression model had a lower mean squared error (lower is better), mean squared error (lower is better), and a higher variance score (higher is better). This is not to say that the other two models, support vector and k-nearest Neighbors regression, should not be ignore! They still have very impressive results, just not as strong as the linear regression model.</p><h3>Predictions</h3><p>As stated above, I used all features of the 2017–2018 NBA season to predict win shares using our models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cu2-13uoPLGRKn3rBDkl5Q.png" /><figcaption>Win Share Predictions Using Linear Regression Model</figcaption></figure><p>Based on the predictions from the linear regression model, LeBron “LABron” James came out on top! The model predicted him leading the NBA in win shares with 14.81 win shares. However, in reality, LeBron (14 win shares) came in second to 2017–2018 NBA MVP James Harden (15.4 win shares), who was second in the prediction. Not a bad prediction! Karl-Anthony Towns and Anthony Davis were 3rd and 4th, respectively, on both the linear regression prediction and the recent NBA season.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IBcdFFSDAUVPL1tJPQGJw.png" /><figcaption>Win Share Predictions Using Support Vector Regression Model</figcaption></figure><p>The support vector regression model had some unusual results. Based on the predictions from this model, LeBron (15.5 win shares) came out on top again, with Harden a close second (15.4 wins). The most exciting outcome of this was that the model accurately predicted Harden’s win shares! He led the 2017–2018 NBA season with 15.4 win shares, the same as the predicted value. Andre Drummond, who was not among the top 10 players in predicted win shares using the linear regression model, was 3rd in win shares using the support vector regression model. Towns and Davis dropped down on the prediction list, and Stephen Curry and Kevin Durant didn’t even make the top 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wzfn0Cj6vWSWb9zOcP5okw.png" /><figcaption>Win Share Predictions Using k-Nearest Neighbors Regression Model</figcaption></figure><p>The win share predictions using the k-Nearest Neighbors were a lot less than the predictions of the previous models. For this model, Harden’s predicted win shares was the highest at only 12.3 win shares. Another weird outcome of the predicted values was that LeBron, Russell Westbrook, Giannis Antetokounmpo, and Davis were tied with 12.24 win shares!</p><h3>Conclusion</h3><p>Here were some of the things I learned from this analysis:</p><ul><li>Using mean absolute error as a measure, one of the models we created was able to predict the individual win shares of an NBA player to within 0.761 points.</li><li>Value Over Replacement Player (VORP) was the most significant factor for predicting win shares. 3-Point % (3P%), games played (G) , and Assists (AST) did not have strong relationships with win shares.</li><li>Lebron James is still KING! Well not exactly, but he’s 33 years old and still producing!</li></ul><p>Although the best model did a great job at predicting win shares of NBA players, there were some issues that I learned along the way that could help me out in future projects:</p><ul><li>More data could have helped. To train the models, I only used data from the 2016–17 NBA season. I could have used data from past seasons but I wanted the predictions to be true to today’s NBA. The NBA is not what is was a few years ago. Like I stated in the analysis, 3-Point shooting has taken over. More teams rely on shooting the long ball. In fact, last seasons’ semi-finalists — the Golden State Warriors, the Cleveland Cavilers, the Houston Rockets, and the Boston Celtics — were among the leaders in most 3-Point attempts. Initially, I was afraid of including data from previous seasons because it would not accurately predict today’s NBA. However, it could have actually helped, given that 3-Point shooting is not as important as I assumed.</li><li>Stat padding doesn’t necessarily mean success. Russell Westbrook is the king of the<a href="http://www.sportingcharts.com/dictionary/nba/triple-double.aspx"> Triple Double,</a> when a player performs double-digit totals in three different metrics. In fact, he finished the previous two seasons averaging a triple double! Westbrook was in the top 10 in all win shares predictions I made using the models, but he was not even top 10 in the past season. Since his stats were so great, his win shares predictions were a lot higher than they should have been.</li><li>Win shares might not be the best stat to measure individual success. Basketball is a team sport, and measuring individual performances isn’t that easy. James Harden was MVP for his amazing offensive production, but his defense?<a href="https://www.youtube.com/watch?v=KMKavKEKX2Q"> NON-EXISTENT</a>. His teammates helped pick up many of his defensive inabilities. But what if they didn’t? Or what if the defensive strategy wasn’t a good fit? Harden would still produce great offensive numbers, but if his team lacked in defense his win shares would drop.</li></ul><p>Overall, I learned that, yes, one can use basketball metrics to predict win shares. However, win shares might not be a great metric to measure individual success, since it takes a whole team to win in basketball, not just one player. Unless your Lebron. GO LAKERS!!!</p><p><em>Please feel free to give feedback or constructive criticism! :) Also, follow me on my personal </em><a href="http://themodernrant.com/"><em>blog</em></a><em> or Twitter</em><a href="https://twitter.com/dataosanch"><em> @dataosanch</em></a><em>. </em>All code used for this post can be found on GitHub, organized on this<a href="https://github.com/osanchez2323/Portfolio/blob/master/Basketball%20Analytics%20-%20Machine%20Learning%20to%20Predict%20Win%20Shares/Basketball%20Analytics%20-%20Using%20Machine%20Learning%20to%20Predict%20Win%20Shares.ipynb"> notebook</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c155651e7cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/basketball-analytics-predicting-win-shares-7c155651e7cc">Basketball Analytics: Predicting Win Shares</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[Data Science Takes on Public Education]]></title>
            <link>https://medium.com/data-science/data-science-takes-on-public-education-f432910ea9f0?source=rss-d09022cdc09d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f432910ea9f0</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Oscar Sanchez]]></dc:creator>
            <pubDate>Mon, 10 Sep 2018 21:07:42 GMT</pubDate>
            <atom:updated>2018-09-11T12:46:07.841Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using machine learning to help analyze an education problem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UtgDisZ4s7BNm9kq" /><figcaption>“high-angle photography of group of people sitting at chairs” by <a href="https://unsplash.com/@mikael_k?utm_source=medium&amp;utm_medium=referral">Mikael Kristenson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>“Education is the most powerful weapon which you can use to change the world” — Nelson Mandela</blockquote><h4>Introduction</h4><p>Nelson Mandela was right. Education is a powerful weapon as well as one of life’s greatest gifts. In the United States, there are various educational program options for children such as public schools, charter schools and private schools. Although there are several education pathways to choose from, do they all aim at the same goal of achieving student success?</p><h4>Problem</h4><p>I came across a challenge on Kaggle called <a href="https://www.kaggle.com/passnyc/data-science-for-good/home">PASSNYC: Data Science for Good</a>. The challenge was created by PASSNYC, a not-for-profit organization that aims to help public school students in New York City, to assess the needs of students by using publicly available data to quantify the challenges they face at school and how to encourage students to take the <strong>Specialized High School Admissions Test (SHSAT)</strong>. PASSNYC wants to find what schools are need of help to increase the number of students that take the tests. Although this challenge was interesting in its own matter, I wanted to solve a different problem using a machine learning approach: how can we help increase the student success of public schools?</p><p><strong>Objective: Can we predict the student achievement rating of public schools?</strong></p><p>In the data, there was a field that rates the achievement of students for each school that I used to determine whether the school was reaching the target of student success. Student achievement rating had 4 different levels: <em>Not Meeting Target, Approaching Target, Meeting Target,</em> and <em>Exceeding Target</em>. This would make our analysis a <strong>supervised multi-classification</strong> machine learning task:</p><p><strong>Supervised</strong>: We were given the target data for the training data</p><p><strong>Multi-class Classification</strong>: the target data has 4 different categorical values (which I later turned into 3 to increase the performance of the models)</p><h4>Exploratory Data Analysis</h4><p>The first approach, as with any data science project, was to understand the data. There were 160 features/columns in the data set consisting of both numerical and categorical values. Based on the features, I was able to discover 4 different types of groups: economic, race, education ratings, and tests. For example, the features that belonged to the economic group consisted of School Income Estimate (numerical) and Economic Need Index (numerical), which are used to identify the economic status of the public school.</p><p>The group of features that I ended up removing most in the final models was tests. These features included the total number of students that took the <strong>Specialized High School Admissions Test (SHSAT). </strong>During the first analysis, I included all of these features but would later discover that they were not integral to helping us solve the problem nor improving the performance of the models. I would only include the average scores of the test (both ELA and Math tests), but not the amount of students take the test.</p><ul><li><strong>What did the distribution of student achievement rating originally look like?</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*al4meQTa8dQPorSTAr71Vg.png" /></figure><p>By looking at the distribution of student achievement rating, I realized that there would be some cleaning to do. There were only 6 schools in the data that were <em>Not Meeting Target</em> of student achievement, compared to over 600 schools that were <em>Meeting Target</em>. Since there were only a few schools that were <em>Not Meeting Target</em>, it would be difficult for the models to make predictions. Therefore, I decided to change the value of <em>Not Meeting Target</em> to <em>Approaching Target</em>, since in reality, they are both: A) not meeting the target of student achievement, and B) trying to meet the target (well, at least I hope they are). There were other features that had the 4 rating levels as well (<em>Not Meeting Target, Approaching Target, Meeting Target,</em> and <em>Exceeding Target), </em>so the changes were also made for those values. After making the changes, the distribution of student achievement looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*HW2eViXiohLpC9u3Lg82SQ.png" /></figure><p><strong>Relationships between Target and Features</strong></p><p>The next step in the analysis was to look for any relationships bewteen the target and features. To do this, I created a few density plots. By coloring the density curves by the target (student achievement rating), this showed how the distribution changes based on the rating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*P3AevGH0hmFtxLOD-81n0w.png" /></figure><p>The relationship between economic need index and student achievement were, in my honest opinion, as expected. The value for economic need index is between 0 and 1, with values closer to 1 meaning the school is in more economic need. Here, there are more public schools that have a high economic need index value are rated as <em>Approaching Target</em>, than the other ratings. Here, many of the public schools that had a high economic value index (more than 0.8) had a student achievement rating of <em>Approaching Target. </em>In other words, schools in need of economic support did not have a good student achievement rating<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*SwGqS2Vktz6VENloNw8qLQ.png" /></figure><p>The relationship between school income estimate and student achievement were the same as economic need index. Many of the public schools that had a lower estimated income (less than $50,000) had a student achievement rating of <em>Approaching Target.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAZhHGqw6SG25QUFb_DvIA.png" /></figure><p>After looking into it a bit more, I discovered that public schools with more than $100,000 in estimated school income, were all either <em>Meeting Target </em>or<em> Exceeding Target</em>. Based on these observations, I speculated that income/economic status of the school would play an important role in the analysis.</p><h4>Feature Engineering / Selection</h4><p>The next step in the process was to make changes to the features to optimize the performance of the models. The columns that had percentage values were changed from numerical to ordinal values using <a href="https://hackernoon.com/what-is-one-hot-encoding-why-and-when-do-you-have-to-use-it-e3c6186d008f">one hot encoding</a>, from 0 to 3. For example, an observation that had a value of 23% (0.23) for the feature <em>Percent Hispanic</em>, was updated to a an ordinal value of 1, while an observation that had a value of 88% (0.88) for the same feature was updated to a value of 3. Doing this to all the features that had a percentage (numerical) value improved the accuracy of the models!</p><p>For the features that had the rating values<em>,</em> I also used one hot encoding: <em>Approaching Target: 1, Meeting Target: 2,</em> and <em>Exceeding Target: 3. </em>This procedure also included the target, student achievement rating.</p><p>Another part of the analysis was looking at relationships between the features. The relationship between economic need index and race showed a significant pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CP194h6qDUrsHqgSaYRdtA.png" /></figure><p>Here, I noticed that the economic need index varies by schools that consisted of a certain race. For example, public schools with a high Hispanic demographic (value of 3), were considered more in need of financial assistance. On the other side, public schools with a high White demographic (value of 3), did not seem to be in a significant need of financial assistance.</p><h4>Model Selection and Testing</h4><p>Since this was a supervised multi-classification machine learning analysis, I created four classification models:</p><ul><li>Random Forest Classifier (RF)</li><li>Linear Support Vector Classification (LSVC)</li><li>Gaussian Naive Bayes (GNB)</li><li>Linear Discriminant Analysis (LDA)</li></ul><p><strong>Metric</strong></p><p>To evaluate the predictions of the models, I used the <strong>Micro F1 Score</strong>. Since this was a multi-class problem, I had to average the F1 scores for each class. while also taking into account label imbalances. The <em>micro </em>averaging computes the total number of false positives, false negatives, and true positives over all classes, and then computes precision, recall, and f-score<br>using these counts.</p><p>Using 10-fold cross validation on the data, which trained and tested the models 10 times, here were the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*CbIwydvSFXyY15eTRei1cg.png" /></figure><p>The <strong>Linear Discriminant Analysis (LDA)</strong> model had the highest micro F1 score with 0.66 (higher is better) using 10-fold cross validation. The Random Forest (RF) model came in second with a score of 0.62. The model that (surprisingly) did not perform well was the Gaussian Naive Bayes (GNB), which scored drastically lower than the other models.</p><p>Using the random forest model, I ranked the feature importances to see how helpful the top features were in the analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*-p0fMKdjLcYrKH9NMRd6xA.png" /></figure><p>The average test scores of both ELA and Math tests were the most important features. This makes sense because with a higher average test store of a school, the school will most likely have a higher student achievement rating. One take from the feature importance was the high ranking of the two economic based features: economic need index and school income estimate. The race features were important in the analysis but not as important as I thought they would be.</p><h4>Conclusion</h4><p>Here are some of the things I learned from the analysis:</p><ul><li>Schools that have lower income levels seem to be in need of improvement. If PASSNYC wants to provide funds/aid to schools, they should look at schools in economic need and schools with a higher percentage of minorities (Black / Hispanic)</li><li>The economic status of a school plays an important part on the achievement of its students: the more economic need a school needs, the lower achievement rate the school has</li><li>Economic status of the school varies by the dominated race of the schools: The more minority (Black / Hispanic) students a school has, the more economic need it has</li><li>The Linear Discriminant Analysis (LDA) scored well in this multi-class machine learning analysis compared to the other models.</li></ul><p>Although the best model did a great job at predicting the student achievement rating of NYC public schools, there were some issues that I learned along the way that could help me out in future projects:</p><ul><li>It’s always great to go update the model selection / engineering! Although this advice is recommended in almost every data science related material, I fully understood its value. The data provided by Kaggle had over 100 features that I used on my first couple of models, but then after going back to the selection / engineering process, I eliminated most of them. Just because the features are available does not mean they will be useful.</li><li>More (non-redundant) features. The data that was provided could have had more useful features like size of school or student-to-teacher ratio. This type of data could have potentially increased the accuracy of our models.</li></ul><blockquote><em>Please feel free to give feedback or constructive criticism! :) Also, follow me on </em><a href="https://twitter.com/dataosanch"><em>Twitter</em></a><em> and </em><a href="https://towardsdatascience.com/@osanchez2323"><em>Medium</em></a><em> !</em></blockquote><p>All code used for this post can be found on GitHub, organized on this <a href="https://github.com/osanchez2323/Portfolio/blob/master/Data%20Science%20Takes%20on%20Education/Data%20Science%20Takes%20on%20Education.ipynb">notebook</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f432910ea9f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-science-takes-on-public-education-f432910ea9f0">Data Science Takes on Public Education</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[Basketball Analytics: The Best Draft Class]]></title>
            <link>https://medium.com/data-science/basketball-analytics-the-best-draft-class-13a6eac0cdb5?source=rss-d09022cdc09d------2</link>
            <guid isPermaLink="false">https://medium.com/p/13a6eac0cdb5</guid>
            <category><![CDATA[basketball]]></category>
            <category><![CDATA[nba]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Oscar Sanchez]]></dc:creator>
            <pubDate>Fri, 17 Aug 2018 19:32:23 GMT</pubDate>
            <atom:updated>2018-08-18T21:10:05.469Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Python to Create Data Visualization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jA_UGKlWXf6xt1hL" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=medium&amp;utm_medium=referral">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p><a href="https://www.youtube.com/watch?v=b5bajuLqZ28">Inside the NBA</a> is the best show on TV. Well, it’s the best show if you love basketball. The Emmy Award-winning program follows the pre-game and post-game analysis of some of the NBA’s biggest games of the year. Hosted by Ernie Johnson, the show covers a variety of NBA topics including the critical analysis of the other studio analysts: former NBA champions Shaquille “Shaq” O’Neal and Kenny “The Jet” Smith. Oh, and some guy named Charles “Chuck” Barkley. What makes this show so compelling for basketball fans is the chemistry between the analysts. The show consists of 70% basketball talk, 25% talking non-sense (mostly trash talk) and 5% is simply Ernie trying to get everyone to stay on topic. One second the crew will be talking about Game 2 of the Western Conference Finals, then switch over to talking about how often you should fill up your <a href="https://www.youtube.com/watch?v=ItU3_AQa4g4">gas tank</a>. Seriously, they spent over 2 minutes talking about that!</p><p>One of the ongoing topics the Inside the NBA crew bring up constantly is the debate of old school vs new school. Shaq, Kenny, and Chuck will go on for days talking about how NBA players of their era were better and tougher, as well as more competitive. Now, I’m going to test that debate with some data visualization. What better way to settle this debate with some Python! Okay, it might not sound like much fun, but I’ll try to make this analysis worth the time.</p><p>To conduct this analysis, I will focus on a more specific set of players by only looking at the 3 best NBA draft classes (not debatable): 1984, 1996, and 2003. Why? Well, they each have some of the greatest players of all time. 1984 has Hakeem Abdul Olajuwon, Charles Barkley, and of course, Michael “GOAT” Jordan (debatable? Maybe). 1996 has Allen Iverson, Steve Nash, and Kobe Bryant. 2003 has Dwayne Wade, Chris Bosh, and LeBron “LABron” James (yes, I’m a Lakers fan). Aside from being the best draft classes ever, these draft classes each represent different era’s of the NBA.</p><p>The data for the analysis comes from <a href="https://www.basketball-reference.com/">Basketball Reference</a>. Basketball Reference provides stats for fans and analysts from their website, which means all stats are official. It also includes the fact that the Golden State Warriors blew a 3–1 lead to the Cleveland Cavaliers in the <a href="https://www.youtube.com/watch?v=wgVOgGLtPtc">2016 NBA Finals</a>. But that discussion is for another time.</p><p>NOTE: All code used for this post can be found on GitHub, organized on this <a href="https://github.com/osanchez2323/Portfolio/blob/master/NBA%20Draft%20Analysis/NBA%20Draft%20Analysis.ipynb">notebook</a>.</p><h4>Data Cleaning</h4><p>We start our analysis by organizing the data.</p><p>The first data set has all NBA player stats from the past 68 years, starting with the 1949–50 season and ending with the 2016–17 season.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre>seasons = pd.read_csv(&#39;Seasons_Stats.csv&#39;)<br>seasons.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4sTCXUoRFZybg9X94-inw.png" /></figure><p>Right away, there is a lot of data that will not be used. The analysis will focus on players from the 1980s and beyond. Therefore, I will only include player stats from that time period.</p><pre>years = list(range(1980,2018))<br>seasons = seasons[seasons[&#39;Year&#39;].isin(years)]<br>seasons.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7UJ6_mcQZ2x-qBD-_K2VAQ.png" /></figure><p>There are different types of players during an NBA season. There are All Star caliber players, role players, and bench warmers. The latter is not really that important (unless you have <a href="https://www.youtube.com/watch?v=NxVuySQT-eY">Robert Sacre</a> on your team). For this analysis, I want to focus on players that had some sort of impact. Therefore, I will include players that played at least 20 minutes per game during the NBA season. To do this, I need to create a new column for minutes per game (MPG).</p><pre>seasons[&#39;MPG&#39;] = round(seasons[&#39;MP&#39;] / seasons[&#39;G&#39;], 1)</pre><pre>seasons = seasons[seasons[&#39;MPG&#39;] &gt;= 20]<br>seasons.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNtZxcnlGDO4uHXIQ9czKA.png" /></figure><p>Another aspect that I will need to exclude from our analysis is season totals. Whenever a player plays for 2 or more teams during an NBA season via trade or buyouts, a new row is added to show the players season totals. For example, in 2013 Jonathan Clay Redick, also known as J.J. Redick (you probably had no idea his name was Jonathan), was traded from the Orlando Magic to the Milwaukee Bucks right before the trade deadline. Therefore, the data shows multiple entries for the same seasons (including a totals entry).</p><pre>seasons[(seasons[&#39;Player&#39;] == &#39;J.J. Redick&#39;) &amp; (seasons[&#39;Year&#39;] &gt;= 2013)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GAbnu7HiUfBufCoybeRK1w.png" /></figure><p>I will remove these rows since we will be grouping the stats by player later in the analysis. Also, I will remove a special character that is included on some player names.</p><pre>seasons = seasons.drop_duplicates([&#39;Player&#39;,&#39;Year&#39;], keep = &#39;first&#39;)</pre><pre>seasons[(seasons[&#39;Player&#39;] == &#39;J.J. Redick&#39;)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_VyXrBaBch87uVkxhAZSg.png" /></figure><p>The second data set consists of player information, including the time period in which the player played in the NBA. For the analysis, I will include every player drafted in 1984, 1996, and 2003. Here, I chose the draft year by including each player’s rookie year. For example, Michael Jordan was drafted in 1984, but the data has his rookie year noted as 1985.</p><pre>players = pd.read_csv(&#39;player_data.csv&#39;)</pre><pre>years_draft = [1985, 1997, 2004]</pre><pre>players.columns = [&#39;Player&#39;, &#39;Rookie Year&#39;, &#39;Final Year&#39;,  &#39;Position&#39;, &#39;Height&#39;,&#39;Weight&#39;,&#39;DOB&#39;,&#39;College&#39;]</pre><pre>players = players[players[&#39;Rookie Year&#39;].isin(years_draft)]</pre><pre>players[&#39;Player&#39;] = players[&#39;Player&#39;].str.replace(&#39;*&#39;,&#39;&#39;) ### Remove special character</pre><p>For the last part of the data cleaning process, I will create a new data table that includes some of the stats we will be analyzing. Since I will be comparing career stats of NBA players by draft class, I will group the stats by draft class.</p><pre>data = seasons[[&#39;Year&#39;, &#39;Player&#39;,&#39;G&#39;,&#39;MP&#39;,&#39;PER&#39;, &#39;TS%&#39;, &#39;FG%&#39;, &#39;3P%&#39;,&#39;2P%&#39;, &#39;eFG%&#39;,&#39;OWS&#39;, &#39;DWS&#39;, &#39;WS&#39;, &#39;WS/48&#39;,<br>                &#39;USG%&#39;,&#39;OBPM&#39;, &#39;DBPM&#39;, &#39;BPM&#39;, &#39;VORP&#39;]]<br>data = data[data[&#39;Year&#39;].isin(years)]<br>data[&#39;Year&#39;] = data[&#39;Year&#39;].astype(object)</pre><pre>data_draft = players.merge(data, on = &#39;Player&#39;)</pre><pre>data_draft[&#39;Rookie Year&#39;] = data_draft[&#39;Rookie Year&#39;] - 1 ### Set the Year to the correct draft class</pre><pre>f = {&#39;G&#39;: [&#39;sum&#39;],&#39;MP&#39;: [&#39;sum&#39;],&#39;PER&#39;: [&#39;mean&#39;], &#39;TS%&#39;: [&#39;mean&#39;], &#39;FG%&#39;: [&#39;mean&#39;], &#39;3P%&#39;: [&#39;mean&#39;],&#39;2P%&#39;: [&#39;mean&#39;], <br>     &#39;eFG%&#39;: [&#39;mean&#39;],&#39;OWS&#39;: [&#39;mean&#39;], &#39;DWS&#39;: [&#39;mean&#39;], &#39;WS&#39;: [&#39;mean&#39;], &#39;WS/48&#39;: [&#39;mean&#39;],&#39;USG%&#39;: [&#39;mean&#39;],<br>     &#39;OBPM&#39;: [&#39;mean&#39;], &#39;DBPM&#39;: [&#39;mean&#39;], &#39;BPM&#39;: [&#39;mean&#39;], &#39;VORP&#39;: [&#39;mean&#39;]}</pre><pre>data_draft = data_draft.groupby([&#39;Rookie Year&#39;], as_index = False).agg(f)</pre><h4>Analysis</h4><p>How do we determine which draft class is the best? It’s easy to simply compare the career points, rebounds, and assists totals of players from each draft. Does that actually tell us that players from a certain draft class is better than the others? Probably not. To analyze the draft classes, I want to use stats that take into consideration other aspects of the game. These are the 3 best stats for the analysis: Player Efficiency Rating (PER), Value Over Replacement Player (VORP), and Win Shares Per 48 Minutes (WS/48).</p><p><strong><em>Player Efficiency Rating (PER)</em></strong></p><p><a href="https://www.basketball-reference.com/about/per.html">PER</a> is a stat created by John Hollinger that takes into account accomplishments, such as field goals, free throws, 3-pointers, assists, rebounds, blocks and steals, and negative results, such as missed shots, turnovers and personal fouls. As stated in the name, this stat rates how effective a player’s impact is on the floor. Just to put this into perspective, Michael Jordan and Lebron James are the career leaders in PER. So, it’s a solid indicator for this analysis.</p><pre>per = data_draft.sort_values([(&#39;PER&#39;,&#39;mean&#39;)], ascending = False).reset_index()<br>pos = list(range(len(per[&#39;PER&#39;,&#39;mean&#39;])))</pre><pre>plt.style.use(&#39;fivethirtyeight&#39;)<br>fig, ax = plt.subplots(figsize = (15,8))<br>plt.bar(pos, per[&#39;PER&#39;,&#39;mean&#39;], width = 0.75, alpha = 0.75, label = per[&#39;Rookie Year&#39;], edgecolor = &#39;gray&#39;, linewidth = 2)<br>for i in pos:<br>    plt.text(pos[i], 6, s = per[&#39;Rookie Year&#39;][i],ha=&#39;center&#39;, va=&#39;bottom&#39;, color = &#39;orange&#39;, size = 50)<br>plt.text(x = -0.68, y = 19.5, s = &#39;Total Career PER - 1984 Draft Class lead in efficiency&#39;,fontsize = 30, weight = &#39;bold&#39;, alpha = .75)<br>plt.text(x = -0.68, y = 18.3, s = &#39;Total Career PER for all NBA players drafted in 1984, 1996, and 2003&#39;,fontsize = 19, alpha = .85)<br>plt.text(x = -0.68, y = -1.5, s = &#39;National Basketball Association                                                                                       Source: Basketball-Reference.com &#39;, fontsize = 17,color = &#39;#f0f0f0&#39;, backgroundcolor = &#39;grey&#39;)<br>plt.xticks([],[])<br>ax.set_ylabel(&#39;PER&#39;, size = 25)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChqFExZSvu9V4h5E3nkBYw.png" /></figure><p><strong><em>Value Over Replacement Player (VORP)</em></strong></p><p><a href="https://www.basketball-reference.com/leaders/vorp_career.html">VORP</a> is a box score estimate of the points per 100 team possessions that a player contributed above a replacement level player, translated to an average team and prorated to an 82-game season. It is equivalent to WAR in baseball, where it indicates a players total contribution to their team.</p><pre>vorp = data_draft.sort_values([(&#39;VORP&#39;,&#39;mean&#39;)], ascending = False).reset_index()<br>pos1 = list(range(len(vorp[&#39;VORP&#39;,&#39;mean&#39;])))</pre><pre>plt.style.use(&#39;fivethirtyeight&#39;)<br>fig, ax = plt.subplots(figsize = (15,8))<br>plt.bar(pos1, vorp[&#39;VORP&#39;,&#39;mean&#39;], width = 0.75, alpha = 0.75, label = vorp[&#39;Rookie Year&#39;], edgecolor = &#39;gray&#39;, linewidth = 2)<br>for i in pos1:<br>    plt.text(pos1[i], .6, s = vorp[&#39;Rookie Year&#39;][i],ha=&#39;center&#39;, va=&#39;bottom&#39;, color = &#39;orange&#39;, size = 50)<br>plt.text(x = -0.68, y = 2.55, s = &#39;Total Career VORP - Jordan and friends keep dominating&#39;,fontsize = 30, weight = &#39;bold&#39;, alpha = .75)<br>plt.text(x = -0.68, y = 2.4, s = &#39;Total Career VORP for all NBA players drafted in 1984, 1996, and 2003&#39;,fontsize = 19, alpha = .85)<br>plt.text(x = -0.7, y = -.15, s = &#39;National Basketball Association                                                                                       Source: Basketball-Reference.com &#39;, fontsize = 17,color = &#39;#f0f0f0&#39;, backgroundcolor = &#39;grey&#39;)<br>plt.xticks([],[])<br>ax.set_ylabel(&#39;VORP&#39;, size = 25)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5FvnfL0G7-jbU8PmMpCWw.png" /></figure><p><strong><em>Win Shares Per 48 Minutes (WS/48)</em></strong></p><p><a href="https://www.basketball-reference.com/about/ws.html">WS/48</a> is a stat that simplifies the number of win shares a player produces every 48 minutes (equal to 1 NBA game). Like VORP, win shares calculates the overall contribution of a player to a team’s win. Since every player does not play the same amount of minutes, WS/48 adjusts the stat to help compare among players.</p><pre>ws = data_draft.sort_values([(&#39;WS/48&#39;,&#39;mean&#39;)], ascending = False).reset_index()<br>pos = list(range(len(ws[&#39;WS/48&#39;,&#39;mean&#39;])))</pre><pre>plt.style.use(&#39;fivethirtyeight&#39;)</pre><pre>fig, ax = plt.subplots(figsize = (15,8))<br>plt.bar(pos, ws[&#39;WS/48&#39;,&#39;mean&#39;], width = 0.75, alpha = 0.75, label = ws[&#39;Rookie Year&#39;], edgecolor = &#39;gray&#39;, linewidth = 2)<br>for i in pos:<br>    plt.text(pos[i], 0.045, s = ws[&#39;Rookie Year&#39;][i],ha=&#39;center&#39;, va=&#39;bottom&#39;, color = &#39;orange&#39;, size =50)</pre><pre>plt.text(x = -0.7, y = 0.145, s = &#39;Total Career WS/48 - We get it. 1984 is the best draft class&#39;,fontsize = 30, weight = &#39;bold&#39;, alpha = .75)<br>plt.text(x = -0.7, y = 0.135, s = &#39;Total Career WS/48 for all NBA players drafted in 1984, 1996, and 2003&#39;,fontsize = 19, alpha = .85)<br>plt.text(x = -0.71, y = -.012, s = &#39;National Basketball Association                                                                                       Source: Basketball-Reference.com &#39;, fontsize = 17,color = &#39;#f0f0f0&#39;, backgroundcolor = &#39;grey&#39;)<br>plt.xticks([],[])<br>ax.set_ylabel(&#39;WS/48&#39;, size = 25)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-uvQ5hRA8ZSq1n4erKhIrg.png" /></figure><h4>Conclusion</h4><p>Okay, Shaq, Kenny, and Charles could have a point when they say players from back in the day are better. Although my analysis shows that the draft class of 1984 was better in PER, VORP, and WS/48, there are some issues. First, some rules that are currently set forth in today’s NBA didn’t exist back in the day. For example, the three-point foul, clear path foul, and defensive 3 second rule were all <em>not</em> part of the NBA in the early 1990s. Each one of these rules lead to extra free throws, which can increase or decrease your PER (depending if the free throw is made).</p><p>Should I have brought these issues up before doing my analysis? Maybe. Yet, this justifies my whole point of this analysis: let’s stop comparing generations and enjoy the show! All these generations are different and that’s the best part about basketball. Magic and Bird were different. Jordan was different. Lebron is different. Steph Curry is different. Basketball shouldn’t focus too much on the past, but more on what’s ahead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13a6eac0cdb5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/basketball-analytics-the-best-draft-class-13a6eac0cdb5">Basketball Analytics: The Best Draft Class</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>
    </channel>
</rss>