<?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 Joao Thomaz Lemos on Medium]]></title>
        <description><![CDATA[Stories by Joao Thomaz Lemos on Medium]]></description>
        <link>https://medium.com/@joaothomazlemos?source=rss-7bb2f0a2c77f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WHD-OESJ9UMGfpp-S0hGLA.jpeg</url>
            <title>Stories by Joao Thomaz Lemos on Medium</title>
            <link>https://medium.com/@joaothomazlemos?source=rss-7bb2f0a2c77f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:02:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joaothomazlemos/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[NBA Games Outcome Project — Model Development]]></title>
            <link>https://medium.com/better-programming/nba-games-outcome-project-model-development-a6ee5d6b046b?source=rss-7bb2f0a2c77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6ee5d6b046b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nba]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Joao Thomaz Lemos]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 11:22:16 GMT</pubDate>
            <atom:updated>2023-06-06T20:54:13.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>NBA Games Outcome Project — Model Development</h3><h4>Part 3 of 3</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GFEFow2dbLcZyk9M" /><figcaption>Photo by <a href="https://unsplash.com/@mariuschristensen?utm_source=medium&amp;utm_medium=referral">Marius Christensen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! This is part three of a series where I build an end-to-end application that primarily aims to predict the game outcome between two chosen teams in a pool of 30 NBA professional teams. I am doing this series mainly to show the key aspects of what helped me create this project, as I learned a lot in the process, and I believe that knowledge should always be shared.</p><h4><strong>Objective</strong></h4><p>The main goal of this article is to feature the main concepts I used in the process of getting a working model and how you could apply them in your own projects. Here, we will try to train a machine-learning model that can beat the prediction model&#39;s, NBA Oracle [1], performance. This project works with unseen data, and I took inspiration from it. The author says their project even beat the experts’ opinions, and the results are shown in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*JEFr1lt3vh4rkM9xNURZBA.png" /><figcaption>Table by [1].</figcaption></figure><h4>Setting up our reference metric</h4><p>Initially, we want to see how a basic classification model performs on our ready-to-train data, and we are going to call it the baseline model. It will be our first reference, and we will aim to improve from it. Our r data from the 2021 and 2022 seasons has 1,200 game samples at the time of writing. So first, we will load our data with pandas and remove the existing columns to organize it. For example, the game date and season. We also allocate the column with the game&#39;s outcome to the target vector and define it as y. The features column related to the matrix will be defined as x.</p><p>From now on, we will heavily use the library scikit-learn, which is the most popular library for machine learning in Python. With this tool in our hands, we can now train data from test data separately and train our baseline model, a Logistic Regression. We only need to adjust the max_iter parameter to a large number so it can converge on our data. We can visualize our results with a nice ConfusionMatrixDisplay method from sklearn; this will show our confusion matrix, as seen below. You have to plug in your model, the test features, and the test target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*mCpwRLdPKH32ChxomFsodA.png" /><figcaption>Image by author</figcaption></figure><p>With the train and test split method from scikit-learn, we get a nice accuracy of 72.6% on the test set! Cross-validation is a nice way to test the models&#39; predictions as it separates the data in batches and train-tests multiple times, where each fraction of the data is used as training and also as a test eventually. You can get more information from the <a href="https://scikit-learn.org/stable/modules/cross_validation.html">sklearn page</a> if you want to know the details.</p><p>Using cross-validation scores with five batches, we get a superior accuracy of 74.3%! For me, this is a lesson of why quality data matters and why it is worth investing the time to get to it, as we already surpassed the reference we had to beat and could go home from here — just kidding. Because we have our new reference now, let&#39;s see what we can do to improve it!</p><h4>Developing new models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IRdR1V1ILataa3jL" /><figcaption>Photo by <a href="https://unsplash.com/@santesson89?utm_source=medium&amp;utm_medium=referral">Andrea De Santis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We are going to try four models, all through Scikit-learn. The first will be Logistic Regression; this is good to analyze first because of its simplicity and efficiency. Then we go with Support Vector Machines (SVMs), which are good for high-dimension data because of their kernel and our dataset’s hundreds of features.</p><p>Finally, we will try the ensemble models of random forest and gradient boosting classifier, which require more parameters, are built on top of decision trees, and allow us to capture complex patterns within the data that would be impossible otherwise.</p><p>Initially, the data for training the models will be the same as we used for the baseline model. To maintain the code cleaner and reusability, we create a Python class, ModelParams, to hold the range of parameters for each model. For example, we custom-made it to have a set of penalty parameters for logistic regression, namely l1, l2, and elasticnet (the mix of l1 and l2).</p><p>This class will also have the data scaler attributes, the Standard Scaler for the linear models, and the MinMax Scaler for the ensembles. The ensemble models work without the need to scale data because of how the decision trees choose the features that cause the most impact on the target variable. So, when calling this class, we instantiate a pipeline object with the model we want — with or without a scaler — and all the set of parameters associated with this model. It will also have a method that allows us to visualize the model, scaler, and parameter ranges after instantiation.</p><p>We create a second class, ModelDevelopment, that can take in the pipeline we made previously, as well as the features X and target y data, to be first instantiated. Two methods give the training functionality of the class: one is used to train the model against all the sets of tuning parameters, named grid_search, and the other is used to train against random parameters within the passed group. We named this random_search. It also has methods we can use to analyze the metrics and AUC ROC curve of a method after training.</p><p>The grid_search method uses the GridSearchCV from scikit-learn. It’s responsible for training our model n*folders times (brute force). n is the combined result when using all the features of the set we passed, and the folders are the cross-validation split. It also has the option to choose the scoring metric that goes into the train. The method returns the best model, best parameters, and best score for this best model. It has the attributes of all scores, too, if we wish to access it. We will use this method to find the optimal parameters of the linear models, as they have fewer parameters to combine and are faster to train when compared with more complex models.</p><p>The random_search method uses the RandomizedSearchCV from scikit-learn. It does everything grid_search does, with the exception that it will train our model z*folders times. z is a subset of random tuning parameters of the n set. We will train our ensemble models as we can set the number of training steps. The drawback of many parameters is that we have to tune them, and the model complexity increases the training time compared with the linear models.</p><p>As for validation analysis, the class has a method named model_metric to see the scores related to accuracy, precision, recall, f1, and auc. It also has a method that plots the auc roc curve, and it is named roc_curve. A third method is used to plot the confusion matrix of the model, and it’s named plot_confusion_matrix. After using the training functions, these methods will take in the optimal parameters as class attributes of the chosen model, so they don&#39;t need arguments passed.</p><p>Now, we plug everything in and see what parameters we get for each model. Using the x and y train and test, the results are around 72% — 76% for the gradient boosting classifier model.</p><p>As we can see, they are close to the baseline model, which was 72.6%. It implies that we did our best to tune the models, but it only improves our accuracy slightly. What can we do to try and improve this? The answer is the classic: let&#39;s play with our data!</p><h4>Improving data quality with feature selection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U4YXt22_CfHfJrnY" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Our training data began with 269 features, which is a lot. We will narrow it so only the features that cause the higher variance in our model are part of the final training data.</p><p>We will perform feature selection in three ways: First, through exhaustive feature selection using the SequentialFeatureSelector from sklearn. Then through analytical selection using SHAP, a Python library that is very popular in visualizing features’ importance and how they impact the model. Finally, we will use the Principal Component Analysis (PCA) technique to select the best features for the model.</p><p>The first method trains the model with one subset of features at a time. It goes through each feature, and we can choose if it moves from one feature to all features (direction = forward)… or if it starts from all features and ends at one feature (direction = backward). Hence the exhaustive concept. We must pass the model, direction, number of features, and metric score as arguments to the SequentialFeatureSelector method. Below we can see the code snippet that’s been customized for this task:</p><pre>from sklearn.feature_selection import SequentialFeatureSelector<br>from time import time<br>import os<br><br>def select_nBest_features(model, n_features):<br>    &quot;&quot;&quot; Info:<br>     Choose a model and a number of features to select the best features among this number, saving the results in a csv file,<br>     plots the top n_best_features and returns a dataframe with the feature importance.<br>     As the method dont return the importances, just the most important features, we need to get to that after the selection. <br>      -----------------------------------------------------------------------------------------------------------------<br>       Input:<br>        model: The model to be used.<br>        n_features: The number of best features to select<br>        -----------------------------------------------------------------------------------------------------------------<br>            Output:<br>                Best features for the chosen model.<br>                <br>            &quot;&quot;&quot;<br>    #verifies if the model is saved already to proceed with the selection<br>    if not os.path.isfile(f&#39;best_features/{model[-1].__class__.__name__}_{n_features}.csv&#39;): # model[-1] is the model itself in the pipeline<br>        start = time()<br>        sfs = SequentialFeatureSelector(model[-1], n_features_to_select=n_features, direction=&#39;backward&#39;, scoring=&#39;accuracy&#39;, cv=5, n_jobs=-1)<br>        sfs.fit(X, y)<br>        end = time()<br>        print(f&quot;Features selected by forward sequential selection: {X.columns[sfs.get_support()]}&quot;) #feature names for the best features<br>        print(f&#39;Minutes elapsed: {round((end - start)/60)}&#39;) #time in minutes<br>        #saving the best features to csv<br>        pd.Series(X.columns[sfs.get_support()]).to_csv(f&#39;best_features/{model[-1]}_{n_features}.csv&#39;, index=False)<br>    else:<br>        print(f&#39;Best {n_features} features for {model[-1].__class__.__name__} already saved.&#39;)<br><br>    #loading the best features for plotting<br>    return pd.read_csv(f&#39;best_features/{model[-1].__class__.__name__}_{n_features}.csv&#39;, header=None) </pre><p>The second method is about the SHAP, so we can get the visuals based on JavaScript. Being able to see the features&#39; contributions will help us see how much each explains the model’s variance.</p><p><strong>Note</strong>: we need to pass the data scaled for the SHAP because we can&#39;t pass the pipelined model. We can only use the model contained in the last step of the previous pipe (scaler + model). For example, if we want to see what the top 10 most impactful features of the random forest model are, we could do something like this:</p><pre># Create SHAP explainer<br>explainer = shap.TreeExplainer(RF[-1], X_scaled, seed=42)<br>shap_values = explainer.shap_values(X_scaled)<br><br>plt.figure(figsize=(10, 10))<br>shap.summary_plot(shap_values, X_scaled, max_display=10, plot_type=&#39;bar&#39;)<br>plt.tight_layout()<br>plt.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*uUEdYBviYi9-RplV82djqQ.png" /><figcaption>Image by author</figcaption></figure><p>This way, we can get insights into how many features we choose. In this example, we could try only the first four features to train our ensembled models.</p><p>The last method is the use of PCA to get the dimensionality reduction. So basically, we want PCA to transform n data features into m principal components, where m&lt;n. The components are orthogonal vectors that approximate the data with least squares, extracting the most important aspects underlining. For this, we must pass our data scaled first by subtracting the mean and getting data points around the unit variance. To understand the intuition behind PCA, I recommend <a href="https://www.sartorius.com/en/knowledge/science-snippets/what-is-principal-component-analysis-pca-and-how-it-is-used-507186#:~:text=Principal%20component%20analysis%2C%20or%20PCA,more%20easily%20visualized%20and%20analyzed.">this link</a>.</p><p>We will get a sense of how much of our 269 features are explained with the principal components by studying the graph below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dlUcLkklOccqLJPxYxfsQ.png" /><figcaption>Image by author</figcaption></figure><p>Nice. We can see that the first 100 principal components can explain around 95% of our data variation. What we can do now is transform our data features into 100 principal components and see if we can increase the accuracy and other metrics given by the sklearn method using classification_report.</p><pre>from sklearn.decomposition import PCA<br><br>def pca_metrics(model, X_train=X_train_scaled, X_test=X_test_scaled, y_train=y_train, y_test=y_test, n_components=0.95):<br>    &quot;&quot;&quot; Info:<br>     This function takes a model and returns the metrics reports of the model with the PCA.<br>      -----------------------------------------------------------------------------------------------------------------<br>       Input:<br>        model: The model to be used.<br>        X_train: The training set.<br>        X_test: The testing set.<br>        y_train: The training target.<br>        y_test: The testing target.<br>        n_components: The number of components to be used in the PCA.<br>        -----------------------------------------------------------------------------------------------------------------<br>        Output:<br>         classification_report: The classification report of the model with the PCA.<br>        &quot;&quot;&quot;<br>    pca = PCA(n_components=n_components)<br>    X_train_pca = pca.fit_transform(X_train)<br>    X_test_pca = pca.transform(X_test)<br>    model.fit(X_train_pca, y_train)<br>    y_pred = model.predict(X_test_pca)<br>    #get the number of components<br>    n_components = pca.n_components_<br><br>    return classification_report(y_test, y_pred), n_components</pre><pre># using 100 principal components to train and test our models<br>models = [lr, svm, rf, gbc]<br><br>for model in models:<br>    print(&#39;{}\n&#39;.format(model[1]), pca_metrics(model, n_components=100)[0])<br>    print(&#39;Principal components used: {}\n&#39;.format(pca_metrics(model, n_components=100)[1]))</pre><p>Still, with PCA, we could also use it to select the best features without transformation. For example, we could select the top 10 features that are most correlated with the first principal component. You can see how this works in the following code:</p><pre>plt.figure(figsize=(10, 20))<br><br>loadings = pd.DataFrame(<br>    data=pca.components_.T * np.sqrt(pca.explained_variance_), #type: ignore<br>    columns=[f&#39;PC{i}&#39; for i in range(1, len(X_train.columns) + 1)], #type: ignore<br>    index=X_train.columns #type: ignore<br>)<br>loadings[&#39;PC1&#39;] = abs(loadings[&#39;PC1&#39;])<br>#picking the 100 best featues accordnly to PCA 1<br>pca_best_features = loadings[&#39;PC1&#39;].sort_values(ascending=False).head(100)<br><br>pca_best_features[::-1].plot(kind=&#39;barh&#39;, color=&#39;#087E8B&#39;)<br>plt.title(&#39;PC1 loadings&#39;, size=20)<br>plt.ylabel(&#39;Features&#39;, size=15)<br>plt.xlabel(&#39;Absolute Correlation&#39;, size=15)<br><br>#drawing a line at 0.5<br>plt.axvline(x=0.5, color=&#39;red&#39;, linestyle=&#39;--&#39;)<br><br>pca_best_features.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*CqaGqXup0Yg0xvSm7HpbaQ.png" /><figcaption>Image by author</figcaption></figure><p>Well, let&#39;s recap what we did:</p><ul><li>Trained and tested the models against data with a specific set of features</li><li>Selected the best hyperparameters</li><li>Selected the best data features with the models with their hyperparameters from before</li></ul><p>The next phase involves repeating these steps. We can keep iterating until we are satisfied with our results.</p><h3>Results</h3><p>By doing this process, we find out that the best model was the random forest, with about 82.5% accuracy and 81.8% AUC. It was trained on data with the 50 best features selected by the exhaust feature selection technique, so that&#39;s the one we are going to use. Some of the model stats follow:</p><pre>{&#39;randomforestclassifier__n_estimators&#39;: 1000,<br> &#39;randomforestclassifier__min_weight_fraction_leaf&#39;: 0.0,<br> &#39;randomforestclassifier__min_samples_split&#39;: 10,<br> &#39;randomforestclassifier__min_samples_leaf&#39;: 2,<br> &#39;randomforestclassifier__min_impurity_decrease&#39;: 0.0,<br> &#39;randomforestclassifier__max_leaf_nodes&#39;: 31,<br> &#39;randomforestclassifier__max_features&#39;: &#39;sqrt&#39;,<br> &#39;randomforestclassifier__max_depth&#39;: 7,<br> &#39;randomforestclassifier__criterion&#39;: &#39;entropy&#39;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*F1wRT1-iM7UfHWMAifD4yg.png" /><figcaption>Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*iVsNeLGPJNUdCbp5qkleng.png" /><figcaption>Image by the author.</figcaption></figure><h3><strong>Final Thoughts</strong></h3><p>I want to wrap it up by stating that we should not pursue the perfect model. As data changes, the metrics will also change, and this is relevant when we talk about basketball games — where the weaker team could win against all odds. There will always be a way to improve the ML pipeline, which will mostly happen on the data quality. I presented some ways you could use to get a proper and decent model running, so try some of these depending on your project&#39;s needs.</p><p>On my GitHub, this analysis’s <a href="https://github.com/joaothomazlemos/NBA-game-outcome/tree/master/Data%20Analysis">notebooks</a> are documented, organized, and, hopefully, educational! The final step will be a wrap-up of everything and a chance to see this project deployed in the cloud. And yes, the data will be fed automatically!</p><ul><li><a href="https://medium.com/@joaothomazlemos/nba-web-scraping-with-python-22c76cfd1d4f">Chapter 1: Web Scraping</a></li><li><a href="https://medium.com/@joaothomazlemos/nba-games-outcome-project-data-development-3a6913658c5">Chapter 2: Data Development</a></li></ul><pre><strong>Want to Connect?<br></strong><br>If you want, please contact me on my <a href="https://www.linkedin.com/in/joaothomazlemos/">LinkedIn</a> for any feedback or questions.<br>I will be happy to answer.</pre><h3>References</h3><p>[1] M. Beckler, H. Wang, M. Papamichael. ‘NBA Oracle,’ Pittsburgh, 2013.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6ee5d6b046b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/nba-games-outcome-project-model-development-a6ee5d6b046b">NBA Games Outcome Project — Model Development</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NBA Games Outcome Project — Data Development]]></title>
            <link>https://medium.com/better-programming/nba-games-outcome-project-data-development-3a6913658c5?source=rss-7bb2f0a2c77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a6913658c5</guid>
            <category><![CDATA[nba]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Joao Thomaz Lemos]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 11:22:38 GMT</pubDate>
            <atom:updated>2023-06-06T19:52:26.101Z</atom:updated>
            <content:encoded><![CDATA[<h3>NBA Games Outcome Project — Data Development</h3><h4>Part 2 of 3</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hSsFd_S_4hVoIqS6" /><figcaption>Photo by <a href="https://unsplash.com/@echaparro?utm_source=medium&amp;utm_medium=referral">Edgar Chaparro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! This is part two of a series where I build an end-to-end application that mainly aims to predict the game outcome between two chosen teams in a pool of 30 NBA professional teams. I’m doing this series mainly to show the key aspects of what helped me in creating this project, as I learned a lot in the process, and I believe that knowledge should always be shared.</p><h3>Objective</h3><p>This article shows the most important aspects I used to prepare the data through exploration and manipulation. Later, it will be ready to train a machine-learning model. Data will not be available in the traditional way — input features in the trained model will output a prediction. We can&#39;t do that directly because, as you might have guessed, the input features for future games that we wanna predict will exist after the game! So, we will need to come up with a solution for that, and I consider the process to achieve this the main takeaway of this article.</p><h4>The methods</h4><p>As we have a complete SQL database of games stats per team stored, we will read it to a Pandas data frame using SQLalquemy to create an SQL engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1RjzXkwGHwhJZ-_p" /><figcaption>Photo by <a href="https://unsplash.com/@chriscurry92?utm_source=medium&amp;utm_medium=referral">Chris Curry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data exploration and cleaning time with Pandas! Note that as the dataset is highly dimensional, with hundreds of features, we will not do a feature-by-feature analysis right now, so the process is simplified. We first drop any duplicated rows and redundant columns like opponent_mp, which stands for minutes played by the opponent team, then check for missing values and the feature mp, which stands for minutes played. This is because some games go overtime (e.g., those not within the 240 regular minutes per team), causing some stats to be higher than usual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*uCtSiVk1R2JKqN14Zr5zRg.png" /><figcaption>Image by author</figcaption></figure><p>Making the math, the number of games that go overtime is about 5% over the thousands of games we have stored from actual and past seasons, as we can see with the help of Seaborn and Matplotlib visuals. As a rule of thumb, if the number of overtime games is at most 15% of all games, we can safely cut it out of our dataset.</p><p>With this step, the dataset here will be considered clean, and we can store it in a pickle file, which we will call production_df.pkl, as it is ready to be used to feed a machine-learning model and make some new predictions in production mode when the project ends.</p><p>Here is my thought process about new predictions: Say we want to predict the match result between team A and team B. With this first input, we will consult our production_df, get the mean stats of the last n games of team A, then the mean stats last n games for team B, and finally, concatenate this in a single row. This will be our input to feed an ML model, so we get our prediction results! Of course, this is still not perfect as a traditional dataset, as the stats of a game could be very different from the estimates for some games, but overall it seems to be a reliable strategy.</p><p>OK, now it&#39;s time to transform this dataset, so it can be used to train an ML model. The training data has to match our idea of how our model will make future predictions. So, each row will be the mean of the last few games for each team, using the ‘rolling function’ of pandas, which I found to be very handy in these situations! <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html">This is the link</a> to the function documentation if you want to know the details. Note that as we are taking the last n games per team, considering the season and home stats, will lose some information in this way.</p><p>If we roll with the n games window, only the information with n+1 appears as a row. It means we lose 2*n rows per team, as each team is grouped by home or away also. Maybe it can sound a bit confusing when hearing for the first time the way I said, so here goes an example with the code below:</p><ul><li>For n = 6 games, with a season having 30 teams, we lose 2 * 6* 30 = 360 rows per season because each row only computes if there are at least six games prior. But, as we have almost 2,500 games in a regular season, it is still worth trying numbers like 5 &lt; n &lt; 15 and seeing what works better for you. At the moment of this publication, six games worked best for me, as I didn&#39;t lose so many games and also captured how the team was performing in the recent games with enough information.</li></ul><pre>def team_avg(grouped_df, last_n_games=6):<br>    &quot;&quot;&quot; Info:<br>        This function calculates the rolling average of<br>         the features of the team<br><br>         Input:<br>            last_n_games: number of games a team played to calculate<br>             the rolling average <br>            grouped_df: dataframe grouped by team, season, and home status<br><br>             Output:<br>                rolling: dataframe with the rolling average of the features &quot;&quot;&quot;<br>    <br>    rolling = grouped_df.rolling(last_n_games).mean()<br>    return rolling<br><br># creating our list of feature cols for ML<br>info_cols = [&#39;date&#39;, &#39;Team&#39;, &#39;opponent_Team&#39;, &#39;season&#39;, &#39;home&#39;, &#39;WIN&#39;]<br>model_cols = df.columns[~df.columns.isin(info_cols)] # Training features<br><br>#df for rolling is the df with the top valuable features for training plus<br>#the columns that we need for the group by.<br># Note that these are columns from the information cols.<br>df_to_roll = df[list(model_cols) + [&#39;Team&#39;,&#39;season&#39;, &#39;home&#39;]]<br>df_rolling = df_to_roll.groupby([&#39;Team&#39;,&#39;season&#39;, &#39;home&#39;], group_keys=False)<br>.apply(team_avg)</pre><p>When we transform the data as we did, it&#39;s important to leave the columns concerning identification, like the team column, so we group by these columns, then merge them with the original dataset and have a new data frame as we planned. This will create a row of a game that happened but with the stats of the n games before that game.</p><p>The image below illustrates the result of this combination, where the columns represent the date the game happened, if the team played at home or not, and the season ID. The rolling_pts, rolling_opponent_pts are two of hundreds of training features that do not represent the points made on that day but the mean of prior games. The game&#39;s outcome is the only training feature representing the actual day stat. Our target column, WIN, where one represents that the team won.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*vi3VBtpEToaEQ1mib2pJ9Q.png" /><figcaption>Image by author</figcaption></figure><p>After cleaning the N/A rows left by the rolling function we just used, we need to combine the columns from the home and away teams that played each other, so it results in exactly the same row that an ML model would be fed when the project is done. We mostly use the prefix home and away to differentiate the teams, using the home feature and concatenating.</p><p><strong>Results</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*OCBvXab-kfuKHP-tpuB-bw.png" /><figcaption>Image by author</figcaption></figure><p>The image above is representative of our full dataframe used for training, which has 269 features. To explain what is happening, let&#39;s see what&#39;s going on in the first row. We have Cleveland Cavaliers (CLE) that played at home, versus Atlanta Hawks (ATL), in 2017–11–05. In the last n games of the CLE at home, say n = 6, their mean scoring points were about 105. ATL scored 100 points on average in the last six games playing away from home.</p><p>The opponents that CLE played against in these last games were about 113, while the opponents of ATL scored 109 on average. The actual game between CLE and ATL ended with a victory for ATL, given that our target home_win = 0.</p><h3><strong>Final Thoughts</strong></h3><p>It took some planning and reflection to do what would become a training dataset that matches our idea of prediction, given that we do not have the actual stats of the game we want to predict, but we did it! This data can fully train a classification ML model as we wanted. If you find yourself curious about the details, all the code for this step can be found in the <a href="https://github.com/joaothomazlemos/NBA-game-outcome/blob/master/Data%20Analysis/01_data_base_development.ipynb">notebook</a> I uploaded to my GitHub. I hope you enjoyed reading it.</p><p>Next on the menu will be that juicy ML development, so stay tuned for the next series chapter!</p><pre><strong>Want to Connect?</strong><br><br>If you have any feedback, don&#39;t be afraid to contact me through <a href="https://www.linkedin.com/in/joaothomazlemos/">LinkedIn</a>.</pre><ul><li><a href="https://medium.com/@joaothomazlemos/nba-web-scraping-with-python-22c76cfd1d4f">Chapter 1: Web Scraping</a></li><li><a href="https://medium.com/@joaothomazlemos/nba-games-outcome-project-model-development-a6ee5d6b046b">Chapter 3: Model Development</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a6913658c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/nba-games-outcome-project-data-development-3a6913658c5">NBA Games Outcome Project — Data Development</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NBA Games Outcome Project — Web Scraping With Python]]></title>
            <link>https://medium.com/better-programming/nba-web-scraping-with-python-22c76cfd1d4f?source=rss-7bb2f0a2c77f------2</link>
            <guid isPermaLink="false">https://medium.com/p/22c76cfd1d4f</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nba]]></category>
            <dc:creator><![CDATA[Joao Thomaz Lemos]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 11:30:25 GMT</pubDate>
            <atom:updated>2023-06-06T16:27:17.608Z</atom:updated>
            <content:encoded><![CDATA[<h3>NBA Games Outcome Project — Web Scraping With Python</h3><h4>How to get data from the NBA seasons’ games and store them for practical use</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*ri83RPJ4FAAiCnloNgvfuw.png" /><figcaption>Photo by <a href="https://unsplash.com/@deanbennett?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dean Bennett</a> on <a href="https://unsplash.com/pt-br/fotografias/nFjLHE4vmn4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Motivation</h3><p>Hello! As I became a big fan of the NBA scene recently and knew my friends and I would be happy knowing the results of previous games, I immediately started thinking of an NBA data science project.</p><p>Also, I thought it would be nice to challenge myself to learn something new, and that&#39;s when web scraping came to mind. It has the bonus of giving this project a ‘start completely from zero aspect,’ which is excellent since the project would be more robust, thus, helping me in my journey to becoming a data scientist.</p><p>This is the first chapter of a series where I build an end-to-end application whose main purpose is to predict the game outcome between two chosen teams in the pool of 30 NBA professional teams. I am doing this series mainly to show the key aspects of what helped me in doing this project, as I learned a lot in the process, and I believe that knowledge should always be shared.</p><h3>The Place To Explore and the Relevant Tools I Used</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*cUgeOCgHscCYhGWRitzKVw.png" /><figcaption>Image by <a href="https://www.basketball-reference.com/">https://www.basketball-reference.com/</a></figcaption></figure><p>The first step toward this goal was to decide which tools we needed to get the data and where we would explore.</p><p>I explored <a href="https://www.basketball-reference.com/">https://www.basketball-reference.com</a>, a great public access domain with NBA seasons’ data ranging from the year 1946! The data I needed was within the boxscores. It contained the basic and advanced stats of a single game.</p><p>Python is a great language and has lots of libraries. Even for scraping, we have many options. For this project, I used playwright to go through the seasons’ HTML data.</p><p>Playwright supports all modern rendering engines, including Chromium, WebKit, and Firefox. Besides, it can be run on Windows, Linux, and macOS. With this library, I could open the web page and select the exact tab I needed for that domain.</p><p>I also used the library BeautifulSoup and some basic frontend knowledge to pull data from the HTML I obtained from playwright. To deal with the HTML files we stored locally, I used the Zipfile library to compress data. It lets you quickly compress and extract your data.</p><p>To parse the stored data, I used Regex, a great library to get exactly what you need to work on a text, and mostly, the almighty Pandas, one of the most famous Python libraries for data analysis/manipulation. Finally, I used SQLite to store the data because it efficiently deals with lots of data.</p><h3>Objective</h3><p>This process aims to store a dataframe where the columns would contain the basic and advanced stats for each team (the last row of tables shown in the images below). It also showed the opponents’ stats that played against the former, located in their respective boxscores. Additionally, I added these columns for the best individual stats for each team as new columns, but this was entirely optional. So each row would display the full stats of each team per game. Last but not least, I added a column representing whether the team won or not.</p><p>Pheww, that&#39;s a lot of variables!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*paWbE-pPC3c1O0N4rT6RpQ.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*XcOVZ0aUE3fb3zno0FVFWA.png" /><figcaption>Image by author</figcaption></figure><h3>The Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YNII7irCSpjzWrMO" /><figcaption>Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=medium&amp;utm_medium=referral">Thought Catalog</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>First, I got the HTML data files for each season’s month. With playwright, this came with hyperlinks of all boxscores using, and I pulled the data out with BeautifulSoup and stored it locally.</p><p>If you are on Mac or Linux, you could code everything in Jupyter Notebooks using the async_api class from playwright. You can do this because the events would run asynchronously, and async allows the code after it to execute immediately. But for Windows, we need to use the sync_api class on a .py file and run it synchronously. Otherwise, it causes errors.</p><p>For this, I manually specified the seasons I wanted to scrap. Then, I used the same method again to store all the HTML files of each boxscore, but this time, using the URLs in the files I previously stored.</p><p>I could go with the scraping process just once, but I did it this way because it guarantees we will get the right URLs for each box. This makes the process less error-prone and saves the list of paths we already downloaded, so we do not need to get all the data again if the process fails or we want more data from other seasons.</p><p>With the boxscores files in hand, the final step was to parse the data with Pandas. This step would ensure the data was ready for the project&#39;s next step. I wanted each feature row to have complete stats per team, so each row needed basic and advanced stats, per team totals, and best individual stats. It also had all those stats from the team&#39;s opponent.</p><p>In this process, I also used Regex to get the seasons associated with each boxscore on the HTML file. This step also tracked the data we had already parsed, so we didn’t need to parse everything again if we ran the notebook for new data.</p><p>Finally, as the file is complete with all the game stats of the seasons I chose, I stored it in an SQLite database. Besides getting our data in and out quickly, we can append new data if we scrap seasons. For instance, if we wanted to erase data, we wouldn’t have to store it all again.</p><h3>Results</h3><figure><img alt="A dataframe showing full stats per team in each row" src="https://cdn-images-1.medium.com/max/1024/1*mBMNgRYTW5TQZaMGY_HpfA.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhCd4eA28c609mXNWxG9QQ.png" /><figcaption>Image by author</figcaption></figure><p>As the images show, we end up with 152 columns, our features. Each scraped boxscore adds two rows containing data from one game but played by two teams. As the recent regular seasons go from October to April, and about fifteen games are played every two days overall, you can imagine these tables have the potential for dozens of thousands of rows, which is awesome!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tVvCjdLVKpX0V2D4" /><figcaption>Photo by <a href="https://unsplash.com/@mrthetrain?utm_source=medium&amp;utm_medium=referral">Joshua Hoehne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Final Thoughts</h3><p>This project was a lot of fun! I knew it would be challenging initially, but I couldn’t have imagined that I’d learn so much during the process — and handle all the little details that came with it. It was a very rewarding feeling to now have the power to scrap data directly with programming. Even more so on the rich data of NBA stats! The next step would be to explore and analyze this data to get some predictions going.</p><p>All the code is explained, and the associated libraries are in my <a href="https://github.com/joaothomazlemos/NBA-game-outcome/tree/master/Web%20Scraping">GitHub project folder</a>. Any suggestions are welcome.</p><p>Thanks for reading!</p><pre><strong>Want to Connect?</strong><br><br>Feel free to reach me anytime through my <a href="https://www.linkedin.com/in/joaothomazlemos/">LinkedIn</a>.</pre><ul><li><a href="https://medium.com/@joaothomazlemos/nba-games-outcome-project-data-development-3a6913658c5">Chapter 2 — Data Development</a></li><li><a href="https://medium.com/@joaothomazlemos/nba-games-outcome-project-model-development-a6ee5d6b046b">Chapter 3 — Model Development</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22c76cfd1d4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/nba-web-scraping-with-python-22c76cfd1d4f">NBA Games Outcome Project — Web Scraping With Python</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>