<?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 Oui Wein Jien on Medium]]></title>
        <description><![CDATA[Stories by Oui Wein Jien on Medium]]></description>
        <link>https://medium.com/@weinjien99?source=rss-f7a33d5ac63a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-sFrXgaNtyQPNPCt4qqhTQ.jpeg</url>
            <title>Stories by Oui Wein Jien on Medium</title>
            <link>https://medium.com/@weinjien99?source=rss-f7a33d5ac63a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 18:24:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@weinjien99/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[Detecting Trends in Time Series Data using Python]]></title>
            <link>https://medium.com/vortechsa/detecting-trends-in-time-series-data-using-python-2752be7d1172?source=rss-f7a33d5ac63a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2752be7d1172</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[trend-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[oil-and-gas]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Oui Wein Jien]]></dc:creator>
            <pubDate>Fri, 19 May 2023 15:30:44 GMT</pubDate>
            <atom:updated>2023-05-19T15:30:44.648Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unleashing Python’s Time Series Analysis: Uncover Hidden Trends Amidst the Data Deluge, Identifying Needles in the Haystack of Time Series.</h4><p>In this article, we will discuss how to detect trends in time series data using Python, which can help pick up interesting patterns among thousands of time series, especially in the sophisticated oil and gas market. However, with the power of Python, and the combined forces of Linear Regression and Kendall Tau statistics, we can navigate through the complexities and unlock valuable insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KSUPtEIFEx_88Acx" /><figcaption>Photo by <a href="https://unsplash.com/@moneyphotos?utm_source=medium&amp;utm_medium=referral">regularguy.eth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Time series analysis is an important topic in data analytics, as it is used to study and predict patterns in data that vary over time. One of the most useful patterns that can be found in time series data is a trend. A trend is a gradual change in the data over time, and detecting trends can be helpful for making trading decisions.</p><p>However, analyzing data for each flow in the oil and gas market can be a tedious and time-consuming process, as there are thousands of possible combinations of origin, destination, and product to consider. As a result, an automated way to detect trends could be immensely helpful in saving time and reducing the workload. By leveraging the power of data analysis tools and statistical methods, we can quickly identify trends and patterns that would be difficult to detect manually. This can help oil and gas companies make better decisions and stay competitive in the market.</p><h3>Data Preparation</h3><h4>Part 1. Extract data from VortexaSDK</h4><p>In this article, we will be using Vortexa data as our data source.</p><p>Russia has been active in engaging STS activity and has been a market spotlight since last year. In this article, we will analyze the recent trends in Russian STS activity as our case study.</p><p>We will be utilizing Vortexa Cargo Movements data to extract the trends in STS activity. The code below is used to download diesel cargoes loading from Russia between 1 December 2022 and 31 March 2023, extract movements containing STS events, and group them by the month in which the STS took place.</p><pre># Extract data from CargoMovement Endpoint<br>df1 = v.CargoMovements().search(<br>    filter_activity= &#39;loading_end&#39;,<br>    filter_time_min = datetime(2022,12,1),<br>    filter_time_max = datetime(2023,3,31,23,59,59),<br>    filter_products = diesel,<br>    filter_origins = russia<br>    ).to_df(columns = &#39;all&#39;)<br><br># Filter for CargoMovements that engage in STS<br>df1_sts = df1[df1[&#39;events.cargo_sts_event.0.from_vessel_id&#39;] != “”]<br><br># Group by STS start date in a monthly basis<br>df_ts =df1_sts.set_index(&#39;events.cargo_sts_event.0.start_timestamp&#39;)\<br>  .groupby([pd.Grouper(freq=&#39;MS&#39;),<br>  &#39;events.cargo_sts_event.0.location.sts_zone.label&#39;<br>  ])\<br>  .agg({&#39;quantity&#39;:&#39;sum&#39;})\<br>  .unstack(level=1).fillna(0).stack().reset_index()<br><br># Analyze trend before end of Mar 23<br>df_ts_filter = df_ts[<br>  df_ts[&#39;transit_month&#39;]&lt;datetime(2023,3,31,23,59,tzinfo=timezone.utc)<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*NvMyfQs1t63sy4v972N7Ng.png" /><figcaption>Fig 1. Transiting quantity for different sts zones (df_ts_filter)</figcaption></figure><h4>Part 2. Data Cleaning to analyze top STS location</h4><p>Assuming we are only interested in the top STS locations, we will remove STS zones that have only one STS event. The following code identifies the top STS zones of interest.</p><pre># Filter for top 7 STS locations<br>top_7=df_ts_filter.groupby(&#39;sts_zone&#39;)\<br>  .agg({&#39;quantity&#39;:&#39;sum&#39;})\<br>  .sort_values(&#39;quantity&#39;,ascending = False)\<br>  .index[:7].tolist()<br><br># Filter out sts zones which has only one STS event (exclude list)<br>top_7 = list(set(top_7) - set(exclude_list))</pre><h3><strong>Detecting Time Series</strong></h3><h4>Method 1. Linear Regression</h4><p>To detect an increasing trend using linear regression, you can fit a linear regression model to the time series data and perform a statistical test on the estimated coefficient (slope). If the coefficient is significantly positive, it indicates that the time series has an increasing trend. On the other hand, if the coefficient is significantly negative, it indicates a decreasing trend.</p><p>Linear Regression generally works well even in smaller datasets (such as in monthly time series). Here is an example code that demonstrates this approach:</p><p>*Code for linear regression see Appendix</p><pre># Perform Linear Regression and calculate the gradient/slope<br>lr_df = calculate_slope(df_ts_filter,location_col = &#39;sts_zone&#39;,quantity_col = &#39;quantity&#39;, location_list = top_location)<br><br># Visualizing the output<br>lr_df[[&#39;r2_score&#39;]].style.bar(subset = &#39;r2_score&#39;,align=&#39;left&#39;, color=[&#39;#d65f5f&#39;, &#39;#5fba7d&#39;])<br>lr_df[[&#39;mape&#39;]].style.bar(subset = &#39;mape&#39;,align=&#39;right&#39;, color=[&#39;#d65f5f&#39;, &#39;#5fba7d&#39;])<br>lr_df[[&#39;gradient&#39;]].style.bar(subset = &#39;gradient&#39;,align=&#39;mid&#39;, color=[&#39;#d65f5f&#39;, &#39;#5fba7d&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*n0x7iG3C41XcHciOK_Nj6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*s352pTs5_TPiNutayCLMmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*pVWp_CM9AQEM9ZmQoAX2_g.png" /><figcaption>Fig 2. r2 score, MAPE and gradient of each STS zones</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*m57AwYjE71quR9RHvh9bxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*nBUFAZpJaMymLoWUOYXyoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*mqHRzNrYnBhFuO0m6lT39A.png" /><figcaption>Fig 3. Fitted lines of Linear Regression on Top STS zones</figcaption></figure><p>To validate the result, we first look at R² score and MAPE of the result of our fitted regression.The R² score measures how well the linear regression model fits the data. It represents the proportion of variance in the dependent variable that can be explained by the independent variables in the model.</p><blockquote><em>A higher R² score indicates a better fit between the model and the data.</em></blockquote><p>The MAPE measures the accuracy of the model’s predictions. It represents the average percentage difference between the actual values and the predicted values.</p><blockquote><em>A lower MAPE indicates that the model is more accurate in its predictions.</em></blockquote><p>In our case, Kalamata STS, Augusta STS, and Taman STS have both high R² score and low MAPE, thus the regression result has higher confidence.</p><p>From the slope/gradient results above, it shows that we have Kalamata STS [GR] becoming the hottest STS locations recently, followed by Augusta STS zone, and lastly Taman STS [RU], as they all have high gradients.</p><h4>Method 2. <strong>Kendall Tau Statistics</strong></h4><p>Kendall tau measures the strength of the association between two variables by comparing the number of concordant and discordant pairs of observations. In the context of time series data, this means comparing the order of the values for the variable being measured at different points in time.</p><p>A pair of observations is considered concordant if the value of the variable being measured increases as time increases, or if the value of the variable decreases as time decreases. A pair of observations is considered discordant if the value of the variable being measured increases as time decreases, or if the value of the variable decreases as time increases.</p><p>To use Kendall tau to detect trends in time series, we would first calculate the Kendall tau coefficient between time and the variable being measured. This involves counting the number of concordant and discordant pairs of observations. By doing so, Kendall tau coefficient can determine the direction and strength of the association between time and the variable being measured. <a href="https://towardsdatascience.com/test-for-existence-of-a-trend-in-a-time-series-3a44f242c329#:~:text=And%20time%20series%20is%20sequential,correlated%2C%20an%20increasing%20trend%20exists"><em>See detailed step-by-step guide on computing Kendall tau coefficient</em></a></p><p>If there are more concordant pairs than discordant pairs, this indicates a positive association between time and the variable being measured, suggesting a positive trend. Conversely, if there are more discordant pairs than concordant pairs, this indicates a negative association between time and the variable being measured, suggesting a negative trend.</p><p>It’s important to note that Kendall tau is a non-parametric method, meaning it doesn’t assume any specific distribution of the data. This makes it useful for detecting trends in time series data that may not follow a normal distribution or may have outliers. However, it’s important to use Kendall tau in conjunction with other methods, such as visual inspection or linear regression, to get a more complete picture of the trend in the data.</p><p>*Code for Relative Order Testing see Appendix</p><pre># Compute Tau statistics<br>tau_df = calculate_tau(df_ts_filter,location_col = &#39;sts_zone&#39;,quantity_col = &#39;quantity&#39;, location_list = top_location)<br><br># Visualizing the output<br>tau_df[[&#39;pvalue&#39;]].style.bar(subset = &#39;pvalue&#39;,align=&#39;right&#39;, color=[&#39;#d65f5f&#39;, &#39;#5fba7d&#39;])<br>tau_df[[&#39;tau&#39;]].style.bar(subset = &#39;tau&#39;,align=&#39;mid&#39;, color=[&#39;#d65f5f&#39;, &#39;#5fba7d&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*y9q3AnFkKiJMxtnzF9wOnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*gG9VptSX0LQaHAHEIP2OsQ.png" /><figcaption>Fig 4. p-value and tau-statistics of each STS locations</figcaption></figure><p>We need to choose a threshold (alpha) for the p-values returned by Kendall tau. If the p-value is smaller than our chosen alpha, we reject the null hypothesis and accept the alternative hypothesis — that a significant trend exists in the series. By increasing the alpha level, we are essentially allowing for a greater chance of committing a Type I error — in other words, of detecting a trend that does not in fact exist.. However, we will use an alpha level of 0.1 as we do not wish to miss any interesting trends.</p><p>Kendall tau p-values (Fig. 4) suggest that there are significant trends in Augusta STS [IT], Taman STS [RU], and Kalamata STS [GR]. By looking at their tau-statistics (Fig. 4), all of them are approaching 1, meaning that all three STS zones are experiencing increasing trends.</p><h3><strong>Validation of results</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7htYVUZcTSS_MeUSe_PSQ.png" /><figcaption>Fig 5. Actual Trends in STS locations derived by 2 methods</figcaption></figure><p>The chart above shows that all these three STS locations derived by 2 methods above have in fact an obvious increasing trend. By checking other sts zones, none of them has a more obvious increasing trend than these three. This has helped to verify the capability of these two methods in detecting trends in time series. However, there are some parameters that you may need to consider such as the significance level (alpha) and MAPE threshold to reduce the risk of detecting spurious trends.</p><h3><strong>Conclusion</strong></h3><p>Using two different methods — Linear Regression and Kendall Tau test, we have successfully shown the existence of a recent trend in STS activity in three STS zones and also obtained the magnitude of the trend. Our results were validated by examining the R2 value and MAPE value of the linear regression model and the Kendall tau coefficient, all of which are indicative of a significant trend in the time series data. The methods above can significantly save analysts’ time by automatically detecting significant trends in the energy world as there are millions of combinations of routes and products in this market.</p><h3>Appendix</h3><p><strong>Linear Regression</strong></p><pre>import pandas as pd<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_absolute_error, r2_score<br><br>def calculate_slope(df,location_col,quantity_col,location_list):<br>    &#39;&#39;&#39;<br>        This function will loop through the location list and calculate slope of best fit of linear regression.<br>        <br>    Parameters:<br>    df: time series dataframe<br>    location_col: the group by location column name<br>    quantity_col: aggregated quantity column name by certain frequency<br>    location_list: Location to loop through<br>    <br>    &#39;&#39;&#39;<br>    location_dict = {}<br>    for location in location_list:<br>        df2 = df[df[location_col] ==  location].reset_index(drop = True)<br>        df2[quantity_col] = df2[quantity_col].replace(&#39;&#39;,0)<br>        # Extract the time values and reshape them to a 2D array<br>        X = df2.index.values.reshape(-1, 1)<br><br>        # Extract the time series values and reshape them to a 1D array<br>        y = df2[quantity_col].values.reshape(-1, 1)<br>        <br>        # Fit a linear regression model to the data<br>        reg = LinearRegression().fit(X, y)<br><br>        # Get the prediction<br>        y_pred = reg.predict(X)<br>        <br>        # Get the fitting metrics<br>        mape = mean_absolute_error(y, y_pred)<br>        r2 = r2_score(y,y_pred)<br>        <br>        # Get the slope of the trend line<br>        slope = reg.coef_[0][0]<br>        <br>        mean = np.mean(y)<br>        <br>        # Store each location - gradient pairs into dictionary<br>        location_dict[location] = (slope,mape,mean,r2)<br>        lr_df = pd.DataFrame(location_dict).transpose()<br>        lr_df = lr_df.rename(columns = {0:&#39;gradient&#39;,1:&#39;mae&#39;,2:&#39;mean&#39;,3:&#39;r2_score&#39;})<br>        lr_df[&#39;mape&#39;] = lr_df[&#39;mae&#39;]/lr_df[&#39;mean&#39;]<br>    return lr_df<br><br>def visualize_location_gradient(df):<br>    &#39;&#39;&#39;<br>    Take location - gradient pairs and give bar chart visualization.<br>    &#39;&#39;&#39;<br>    df = df.sort_values(&#39;gradient&#39;,ascending = False)<br>    fig = px.bar(df,x = df.index, y = &#39;gradient&#39;, title = &#39;Gradient for each location&#39;)<br>    fig.show()</pre><p><strong>Kendall Tau statistics</strong></p><pre>import scipy.stats as stats<br><br>def calculate_tau(df,location_col,quantity_col,location_list):<br>    &#39;&#39;&#39;<br>        This function will loop through the location list and compute tau statistics for each zone.<br>        <br>    Parameters:<br>    df: time series dataframe<br>    location_col: the group by location column name<br>    quantity_col: aggregated quantity column name by certain frequency<br>    location_list: Location to loop through<br>    <br>    &#39;&#39;&#39;<br>    location_pvalue_dict = {}<br>    for location in location_list:<br>        df2 = df[df[location_col] ==  location].reset_index(drop = True)<br>        df2[quantity_col] = df2[quantity_col].replace(&#39;&#39;,0)<br>        # Extract the time values and reshape them to a 2D array<br>        X = df2.index.values.reshape(-1, 1)<br><br>        # Extract the time series values and reshape them to a 1D array<br>        y = df2[quantity_col].values.reshape(-1, 1)<br>        <br>        # Compute tau statistics<br>        tau, p_value = stats.kendalltau(X, y)<br>        <br>        # Store each location - gradient pairs into dictionary<br>        location_pvalue_dict[location] = (tau, p_value)<br>        tau_df = pd.DataFrame(location_pvalue_dict).transpose()<br>        tau_df = tau_df.rename(columns = {0:&#39;tau&#39;,1:&#39;pvalue&#39;})<br>    return tau_df</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2752be7d1172" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vortechsa/detecting-trends-in-time-series-data-using-python-2752be7d1172">Detecting Trends in Time Series Data using Python</a> was originally published in <a href="https://medium.com/vortechsa">VorTECHsa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prediction model for NBA championship by Machine Learning]]></title>
            <link>https://medium.com/@weinjien99/prediction-model-for-nba-championship-by-machine-learning-8e8884ea72c8?source=rss-f7a33d5ac63a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e8884ea72c8</guid>
            <category><![CDATA[nba]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Oui Wein Jien]]></dc:creator>
            <pubDate>Thu, 09 Sep 2021 02:58:04 GMT</pubDate>
            <atom:updated>2021-09-09T02:58:04.560Z</atom:updated>
            <content:encoded><![CDATA[<p>Leveraging NBA teams statistics in regular season to predict performances of every teams in playoff as well as to predict NBA Champion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RItpfHsPaeQ5PqmL" /><figcaption>Photo by <a href="https://unsplash.com/@andredantan19?utm_source=medium&amp;utm_medium=referral">Andre Tan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>After every NBA regular season ends, it will be an exciting times for all NBA fans especially the fans who are supporting the NBA playoff teams. Everyone is curious about who is going to win the championship this year. Seeing all of the NBA players playing hard in every single game in playoffs is really passionate and motivating. Therefore, me as a NBA fan, I am excited to utilise my data science skills to predict NBA Championship.</p><p>Before the playoff games start, the best data that we can use to make such prediction is to leverage their performance in regular season. Here we have made an assumption that the performance of every teams in the playoff is the same as the regular season.</p><p>Below are the steps that will be explained details:</p><ol><li>Data Collection</li><li>Machine Learning Model Selection</li><li>Hyperparameter tuning</li><li>Features importance</li><li>Prediction in Playoff Wins and Championship 2021</li></ol><h3>Data Collection</h3><p>The dataset that will be used in this machine learning model is the teams statistics in regular season. This can be easily found in NBA official website. Link and snapshot on the website are given below:</p><p><a href="https://www.nba.com/stats/teams/traditional/">Teams Traditional</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBXS2JiowwYHCpJB8yxcRg.png" /><figcaption>Example of team stats in NBA regular season 2021 (latest)</figcaption></figure><p>I had combined all of the data from 2007–2021 into an excel file. Reason being to use this small range of dataset is that it is unfair to evaluate and predict a performance for a player by using the performance by players from another era. We all know that players in NBA from different era plays differently. This is similar to it is difficult for us to tell whether LeBron James or Michael Jordan is the real G.O.A.T. Therefore, I only used 14 years data to train the model.</p><p>From the table above, the features that will be used in this machine learning model are:</p><ul><li>GP — Games Played</li><li>W-Wins</li><li>L — Losses</li><li>WIN% — Win Percentage</li><li>MIN — Minutes Played</li><li>FGM — Field Goalds Made</li><li>FGA — Field Goals Attempted</li><li>FG% — Field Goal Percentage</li><li>3PM — 3 Point Field Goals Made</li><li>3PA — 3 Point Field Goals Attempted</li><li>3P% — 3 Point Field Goals Percentage</li><li>FTM — Free Throws Made</li><li>FTA — Free Throws Attempted</li><li>FT% — Free Throw Percentage</li><li>OREB — Offensive Rebounds</li><li>DREB — Defensive Rebounds</li><li>REB — Rebounds</li><li>AST — Assists</li><li>TOV — Turnovers</li><li>STL — Steals</li><li>BLK — Blocks</li><li>BLKA — Blocked Field Goal Attempts</li><li>PF — Personal Fouls</li><li>PFD — Personal Fouls Drawn</li><li>PTS — Points</li><li>+/- — Plus Minus</li><li>Rank</li></ul><p>The target variable here is playoff wins of each team. This also can be found in NBA official website. The reason that I’m not using NBA Champion as my target variable is because this will skew the dataset too much. Furthermore, it provides more information for us if we treat playoff wins as our target variable. Therefore, in this case, the team which owns the highest playoff wins will be the champion.</p><h3>Machine Learning Model Selection</h3><p>To begin with model selection, I first proposed some machine learning models that can be used in solving regression problems, which are Linear Regression, Support Vector Machine and Random Forest Regression.</p><p>Fortunately, scikit-learn library had made things so much easier. All we have to do is just import cross_val_score from sklearn in order to choose the best model among the models we have.The scoring metric used here is mean absolute error. However, sklearn only has this scoring metric in a negative form (for some reasons), so we can simply multiply the values by -1 to obtain the positive mean absolute error. The code is as below:</p><pre>from sklearn.model_selection import cross_val_score<br>from sklearn.linear_model import LinearRegression<br>from sklearn.ensemble import RandomForestRegressor<br>from sklearn import svm<br>from sklearn.metrics import mean_squared_error</pre><pre>reg1 = svm.SVC()<br>reg2 = LinearRegression()<br>reg3 = RandomForestRegressor()<br>score1 = cross_val_score(reg1,X,y,cv = 5, scoring = &#39;neg_mean_absolute_error&#39;)<br>score2 = cross_val_score(reg2,X,y,cv = 5, scoring = &#39;neg_mean_absolute_error&#39;)<br>score3 = cross_val_score(reg3,X,y,cv = 5, scoring = &#39;neg_mean_absolute_error&#39;)<br>print(&#39;SVM mean absolute error: &#39;,np.mean(-1*score1))<br>print(&#39;Linear Regression mean absolute error: &#39;,np.mean(-1*score2))<br>print(&#39;Random Forest mean absolute error: &#39;,np.mean(-1*score3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DacKBImwMiua8EcVJDBU8g.png" /><figcaption>Mean absolute errors for three different models (Linear Regression, Support Vector Machine, Random Forest)</figcaption></figure><p>Since random forest regression gives us the lowest mean absolute error. Therefore, random forest regression will be used as our machine learning model. This also agrees with our expectation intuitively because the problem here is definitely not a linear problem and we expect random forest, a non-linear classifier to do the best job here.</p><h3>Hyperparameter Tuning</h3><p>Since Random Forest Regression gives the lowest mean absolute error, this machine learning model will be used. In order to find which best values for all hyperparameters available, we could use Randomized Search CV to do that.</p><p>The rationale behind Randomized Search CV is that given a set of hyperparameter values, random combinations of the hyperparameters values will be used to train the model and it will return the set of hyperparameter values which performs the best. Comparing to Grid Search CV, this allows you to explicitly control the number of parameter combinations that are attempted. The number of search iterations is set based on time or resources. Scikit Learn offers the RandomizedSearchCV function for this process.</p><p>What we have to do is just to select a range for each of the hyperparameters used in random forest, and run the RandomizedSearchCV. Then, the best hyperparameters can be obtained by using best_params attributes. The code is as below:</p><pre>from sklearn.model_selection import RandomizedSearchCV<br># Number of trees in random forest<br>n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]<br># Number of features to consider at every split<br>max_features = [&#39;auto&#39;, &#39;sqrt&#39;]<br># Maximum number of levels in tree<br>max_depth = [int(x) for x in np.linspace(10, 110, num = 11)]<br>max_depth.append(None)<br># Minimum number of samples required to split a node<br>min_samples_split = [2, 5, 10]<br># Minimum number of samples required at each leaf node<br>min_samples_leaf = [1, 2, 4]<br># Method of selecting samples for training each tree<br>bootstrap = [True, False]<br># Create the random grid<br>random_grid = {&#39;n_estimators&#39;: n_estimators,<br>               &#39;max_features&#39;: max_features,<br>               &#39;max_depth&#39;: max_depth,<br>               &#39;min_samples_split&#39;: min_samples_split,<br>               &#39;min_samples_leaf&#39;: min_samples_leaf,<br>               &#39;bootstrap&#39;: bootstrap}</pre><pre># Use the random grid to search for best hyperparameters<br># First create the base model to tune<br>rf = RandomForestRegressor()<br># Random search of parameters, using 3 fold cross validation, <br># search across 100 different combinations, and use all available cores<br>rf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1, scoring = &#39;neg_mean_absolute_error&#39;)<br># Fit the random search model<br>rf_random.fit(X, y)<br>rf_random.best_params_</pre><h3>Random Forest Model</h3><p>Here, we had already obtained the best hyperparameters for our random forest model. We could then observe the improvement made by the processs of hyperparameters tuning compared to basic random forest model.</p><pre>best_rf = RandomForestRegressor(n_estimators = 600,min_samples_split = 2,min_samples_leaf = 4,max_features = &#39;auto&#39;,max_depth = 40,bootstrap = True)<br>base_rf = RandomForestRegressor()<br>best_model = best_rf.fit(X_train,y_train)<br>base_model = base_rf.fit(X_train,y_train)</pre><pre>def mae(test,pred):<br>    err = np.mean(abs(test-pred))<br>    return err<br>y_pred_base = base_model.predict(X_test)<br>y_pred_best = best_model.predict(X_test)</pre><pre>print(&#39;Mean absolute error (base rf model): {} &#39;.format(mae(y_test,y_pred_base)))<br>print(&#39;Mean absolute error (best rf model): {} &#39;.format(mae(y_test,y_pred_best)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*4zFTnedFOaJlAez8ctmuBg.png" /></figure><p>We can see that the mean absolute error has improved 0.13 unit, which reduces 8% in terms of original mean absolute error.</p><h3>Features Importances</h3><p>As a NBA fan, I am also interested in looking the keys to win in a playoff games. Fortunately, this can be found by looking at the features importances. In Random Forest, it naturally helps to rank the features. The features importances can be obtained by using features_importances_ in sklearn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*s7QjHOAnyTTXvbwxJMA3qw.png" /><figcaption>Features Importances by Random Forest</figcaption></figure><p>In the graph above, we can easily see that the important features are WIN% and RANK. However, if we take a deeper look into other features (excluding these top two features), the result is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*InovAZqQoojS9xD5a4IoTQ.png" /><figcaption>Features importances (excl. win% and rank)</figcaption></figure><p>Among all these features excluding WIN% and RANK, the top features are FT%, OREB, TOV, +/-. The most surprising features here will be FT%, and the importances shown here is even higher than steal, block, and field goals made.</p><h3>Prediction in Playoff Wins and Championship 2021</h3><p>After we have our trained machine learning model with the best parameters, we can now treat the playoff performance in year 2021 as our test set, and our training set will be all data from the beginning of data until 2020.</p><p>By using the same methodology, we can compare our prediction to what is really happening in real world. The result is then shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*JYXgLnVs6OF6HzO5AXTHAw.png" /><figcaption>Prediction vs Real playoff wins</figcaption></figure><p>We can see that, for those teams who have fewer wins is closer to our predictions. Meanwhile, for those teams which have higher wins are far from our predictions. This implies that our machine learning model is not sufficient to make accurate predictions for teams that are advanced to conference finals or finals.</p><p>It’s also interesting for us to find that which teams have surprising performance in playoff, and which teams have disappointing performance. Obviously, Atlanta Hawks is really surprising as the model has predicted them to stopped at the first round of playoff, but eventually they had reached another milestone, which is advanced to conference finals in six years time.</p><p>The champion selected by our machine learning model will be the team which owns the highest predicted playoff wins. In this case, the predicted champion in 2021 will be Phoenix Suns. If we were to predict all of the champions from 2007 to 2021, the following confusion matrix can be obtained:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*K6F_x4hrtsYqbn09av-BDA.png" /><figcaption>Confusion Matrix</figcaption></figure><p>In this confusion matrix, it is unfair for us to use accuracy to evaluate the performance of our machine learning model. This is due to the fact that our dataset is in fact a skewed dataset here. However, precision, recall, and f1 score can be calculated:</p><blockquote>Precision: 0.40, Recall: 0.86, F1-score: 0.55</blockquote><p>In overall, our machine learning did a fair job in this classification problem.</p><h3>Learning and Takeaways</h3><p>Throughout the process in building this machine learning model to predict NBA Champion, this has led several takeaways for me:</p><ul><li>Evaluated the performance for different machine learning models and understood the reasons and rationale behind each of the machine learning model.</li><li>Implement Hyperparamter tuning for a non-linear classifier, which is random forest by randomized search cv function in python.</li><li>Implemented machine learning on a skewed dataset, and learnt about the differences in handling a skewed dataset and an usual dataset, such as the scoring metric, and the evaluation of the performance.</li></ul><h3>Future Improvements</h3><ul><li>Apply another machine learning model for teams that are advanced to semi-finals or finals by taking more considerations such as number of all star players, the historical data between two teams and so on.</li><li>Take into account that the difficulty for each team in every round is different, i.e. 8th team will probably will have the highest difficulties in the first round.</li><li>Try filtering out those teams which are not qualified for playoff and implement machine learning on the dataset.</li></ul><h3>References</h3><ol><li><a href="https://towardsdatascience.com/why-how-and-when-to-apply-feature-selection-e9c69adfabf2">Why, How and When to apply Feature Selection, by Sudharsan Asaithambi</a></li><li><a href="https://towardsdatascience.com/hyperparameter-tuning-the-random-forest-in-python-using-scikit-learn-28d2aa77dd74">Hyperparameter Tuning the Random Forest in Python, by Will Koehrsen</a></li></ol><p><em>If you enjoy reading this article and find this article helpful, please like and share to your friends.</em></p><p><em>If you have any thoughts or comments, feel free to connect me on </em><a href="https://www.linkedin.com/in/oui-wein-jien-2301221a4/"><em>LinkedIn</em></a><em> here.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e8884ea72c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>