<?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 Fakhri Azhar on Medium]]></title>
        <description><![CDATA[Stories by Fakhri Azhar on Medium]]></description>
        <link>https://medium.com/@aifakhri?source=rss-8fecd32f3b9e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3vsAP1AE12m4FrhCnfob1g.jpeg</url>
            <title>Stories by Fakhri Azhar on Medium</title>
            <link>https://medium.com/@aifakhri?source=rss-8fecd32f3b9e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:02:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aifakhri/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[Random Forest From Scratch]]></title>
            <link>https://medium.com/@aifakhri/random-forest-from-scratch-e6485ee3b583?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6485ee3b583</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 14:22:13 GMT</pubDate>
            <atom:updated>2024-03-09T14:22:13.392Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use Case: Customer Churn</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CM9qGlWPhHBRA8Sx" /><figcaption>Photo by <a href="https://unsplash.com/@willianjusten?utm_source=medium&amp;utm_medium=referral">Willian Justen de Vasconcellos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Ensemble methods are learning algorithms that construct a set of classifiers and then classify new data points by taking a (weighted) vote of their predictions[1]. Furthermore the ensemble methods can also be used to construct a regressor when the target or output variables are numerical (not in probability).</p><p>Bagging is one of several methods to construct an ensemble. Bagging presents the learning algorithm with a training set that consists of a sample of m training examples drawn randomly with replacement from the original training set of m items[1]. Bagging utilises the bootstrap technique, which is a resampling tool that samples data uniformly at random with replacement from the observations (data). Furthermore, the results of the bootstrap would be aggregated, hence, the name is Bootstrap Aggregation or Bagging[1].</p><p>However, Bagging yields performance issues due to a high correlation between predictions. From this problem Random Forest algorithm emerges to solve the high correlation issue in Bagging. Random Forest decorrelates the individual Decision Tree by randomly picking the features, hence, reducing the variance when the trees are averaged. Despite being randomly picked, the size of the feature can be controlled to provide more control towards</p><h3>Objectives</h3><p>The objective of this project is to apply the Random Forest algorithm to classify which customer would lead to churn. However,the main objectives of this projects are:</p><ol><li>Build Random Forest estimator from scratch from its pseudocode. However, we won’t build the CART-Algorithm from scratch. Instead, the scikit-learn for CART algorithm would be used.</li><li>Tuning the Random Forest Hyperparameters with cross validation technique before applying the best Random Forest model to the test data.</li><li>Evaluate the Random Forest with the following metrics: Precision.</li></ol><h3>Model Development</h3><p>Random Forest is built based on the Decision Tree algorithm and ensemble method with bootstrap aggregation (Bagging). Hence, those algorithms are part of the Random Forest’s component of learning. The Random algorithm itself enhances the Decision Tree and Bagging by randomly selecting the predictors of the data, hence, decorrelates each Decision Tree result on each bootstrap sample. The decorrelation of predictors improves the result of the algorithm.</p><p>The Random Forest algorithm was discovered by Leo Breiman [5], its research is summarized by Gerard Bieau and Erwan Scornet in their walkthrough about Random Forest [2]. Here is the pseudocode for the Random Forest algorithm.</p><figure><img alt="CART with Bagging Pseudocode" src="https://cdn-images-1.medium.com/max/586/0*eICdEohbRkLGaKJz" /><figcaption>CART with Bagging Pseudocode</figcaption></figure><p>From the pseudocode, above the Random Forest algorithm can be built into a code and fit the algorithm into a dataset, which has been explained in the previous section.</p><h3>Component of Learning</h3><p>As the pseudocode explain:</p><figure><img alt="Initialization of Random Forest Pseudocode" src="https://cdn-images-1.medium.com/max/554/0*qhkB-6XuFFcta2JV" /><figcaption>Initialization of Random Forest Pseudocode</figcaption></figure><p>We need to set the data, which has been done and the number of trees or the Decision Tree estimators. Here is the code to initialize the Random Forest algorithm:</p><figure><img alt="Initialization of Random Forest Pseudocode" src="https://cdn-images-1.medium.com/max/894/0*pnWXPbVFcFYbY42K" /><figcaption>Random Forest Classifier class code for initialization</figcaption></figure><p>Here the number of trees (M) are represented by the n_estimators attribute whilst the criterion, max_depth, min_sample_leaf, and min_impurity_decrease are the hyperparameter of the Decision Tree Classifier, which are represented on the pseudocode as the mtry, nodesize, and the x. The attribute that is specific to the Random Forest algorithm is max_features that indicates the number of random features that would be used during the bootstrap process.</p><p>The Decision Tree Classifier attributes are used because Random Forest utilizes Decision Tree as mentioned in the following pseudocode:</p><figure><img alt="CART algorithm pseudocode" src="https://cdn-images-1.medium.com/max/758/0*rOAFFXX38u4nc0Ia" /><figcaption>CART algorithm pseudocode</figcaption></figure><p>The Decision Tree (CART) algorithm is what has been explained in the pseudocode above. From the algorithm above, we iterate the number of trees (M), which means the number of Decision Tree estimators. Furthermore, for each estimator, we run the Decision Tree Algorithm until the stopping criteria is satisfied. In this case the min_sample_leaf and the max_depthh. One thing to note here is that on each estimator, the bootstrap sample (randomly selected data with replacement) is applied.</p><p>On the other hand, if the stopping criteria has not been satisfied, we need to grow the tree based on the CART-split criteria, and keep on growing the tree until the stopping criteria is satisfied.</p><p>In the code, the bootstrap sample is written in the BaseEnsembleclass, which is being inherited to the RandomForestClassifierclass above. The BaseEnsemble class is built on the ensemble method, which is a method of combining “building blocks” models in order to obtain a single and potentially very powerful model[3]. Furthermore, adding bootstrap to the ensemble would create a bootstrap aggregation algorithm that is the foundation of the RandomForestClassifier.</p><h3>Bootstrap Aggregation</h3><p>To build the bootstrap aggregation we could use the following pseudocode[6]:</p><figure><img alt="Bagging Pseudocode" src="https://cdn-images-1.medium.com/max/1024/0*Cll2TQV_14KfrkPf" /><figcaption>Bagging Pseudocode</figcaption></figure><p>From the pseudocode above, the BaseEnsemble would be initiated with the following code:</p><figure><img alt="RandomForestClassifier class initialization" src="https://cdn-images-1.medium.com/max/736/0*3nn7nAuTzz2Tx62v" /><figcaption>RandomForestClassifier class initialization</figcaption></figure><p>For the Random Forest algorithm, the estimator should be the Decision Tree, whilst the n_estimators represent the learning rounds, as per pseudocode.</p><p>The next step is to iterate through the n_estimators, if we have 100 estimators then we will iterate 100 times, and so on. For each iteration we will generate the bootstrap sample and train the estimator with the bootstrap sample. Here is the code for creating the estimator for each n_estimators:</p><figure><img alt="Building the base Decision Tree Classifier" src="https://cdn-images-1.medium.com/max/1024/0*CTrO8ZTwx6Cx_TsW" /><figcaption>Building the base Decision Tree Classifier</figcaption></figure><p>Then, we build the bootstrap sampling with the following code:</p><figure><img alt="Generating bootstrap samples" src="https://cdn-images-1.medium.com/max/1024/0*oxI5-lDR_FIAVTf1" /><figcaption>Generating bootstrap samples</figcaption></figure><p>From this sample, we could loop through for each n_estimators to train the estimator with the bootstrap sample. However, since the bootstrap would be used for the RandomForestClassifier we would define the number of features for each training of the estimator.</p><p>For the Random Forest algorithm, we could choose the number features or max_features based on these choice:</p><ol><li>Square Root</li><li>Log2</li></ol><p>However, we could specify any number as long as the max_featuresis less than the total features in the dataset. By default, in this code, the max_features would use the square root or the sqrt method to get the number of features:</p><figure><img alt="Max features selection for Random Forest" src="https://cdn-images-1.medium.com/max/998/0*z-xlgMnHVfA43kQe" /><figcaption>Max features selection for Random Forest</figcaption></figure><p>The code to select the features from the dataset:</p><figure><img alt="Randomly select the features for Random Forest" src="https://cdn-images-1.medium.com/max/998/0*MZ6eX9msBqA1I0XW" /><figcaption>Randomly select the features for Random Forest</figcaption></figure><p>When we already have the bootstrap sample and features we could start to train the estimators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/0*dhEusod_ZYuP2-9B" /></figure><h3>Predicting the Estimator Results</h3><p>From the above algorithm we could fit the training data and to predict unseen data, each estimator would be needed to generate results of the prediction. For each prediction, we need to aggregate the result of prediction as per Bagging and Random Forest pseudocode.</p><p>The code for the prediction can be seen as follow:</p><figure><img alt="Predict Random Forest, on the Ensemble" src="https://cdn-images-1.medium.com/max/1024/0*bLBhQuePlH3FMtHx" /><figcaption>Predict Random Forest, on the Ensemble</figcaption></figure><p>Where the aggregate ensemble is:</p><figure><img alt="Aggregating The Prediction" src="https://cdn-images-1.medium.com/max/1024/0*xOR-czyzW_rs6xga" /><figcaption>Aggregating The Prediction</figcaption></figure><h3>Code Experiment</h3><p>For experimenting with the code, we use a dataset from kaggle. For the feature description please refer to the Kaggle link. Furthermore, not all features would be used because not all features are useful. Here is the features that would be used:</p><figure><img alt="Dataset Overview" src="https://cdn-images-1.medium.com/max/1024/0*1R4h5D6SpWYPs1v3" /><figcaption>Dataset Overview</figcaption></figure><p>We are still interested in the ‘Gender’ feature, but since it is a categorical feature we label 1 for female and 0 for male. From this we could separate the input and the output of the data, where the output is defined as the customers who are churned (1) and customers who don’t (1) churn. These outputs would be crucial for the evaluation of the Random Forest model.</p><h3>Hyperparameter Tuning</h3><p>As mentioned, the Random Forest hyperparameters are the same as the Decision Tree Hyperparameter: , max_depth, min_sample_leaf, , splitting criterion, and min_impurity_decrease. The only difference is the number of features or the max_featuresthat would be used on each bootstrap, and also the number of Decision Tree estimators that would be aggregated. Hence, those features are the hyperparameters.</p><p>Since the task is a classification to predict whether customers would churn or not, we will check the proportion of the target parameters:</p><figure><img alt="Target variable proportion" src="https://cdn-images-1.medium.com/max/376/0*JjUS6-U0PoJaYkdw" /><figcaption>Target variable proportion</figcaption></figure><p>As we can see the proportion is slightly imbalanced with the customer churn (0) is less than the customers who don’t churn. Hence, the better evaluation for this is to check the precision, because the proportion shows that the customer rarely churned, hence to optimize the business we need to be able to predict the customers who are churned and they are actually churned. In this case, precision is a better metrics than any other metrics</p><p>We would run a GridSearchCV (built manually) for the precision score with the following hyperparameter configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*DgVMfuxhyDDtwPfX" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*IFoKivNL-Lfl-tOo" /></figure><p>With the above results, we would have 24 combinations of hyperparameters. Here is the GridSearchCV result for precision</p><figure><img alt="GridSearchCV results for precision score" src="https://cdn-images-1.medium.com/max/1024/0*3TTS9hll_RzXb9ai" /><figcaption>GridSearchCV results for precision score</figcaption></figure><p>The results are quite peculiar: the more the estimator, the higher the precision score. These results could mean that the result from the Decision Tree Classifier is very sensitive, causing the model too quickly to overfit or underfit. Hence, further investigation of the algorithm is needed.</p><h3>Testing The Model</h3><p>We will test both hyperparameters for precision score and compare with the cross validation score However, we won’t use the hyperparameters which are resulting the highest accuracy or precision score, instead we will evaluate the model from the hyperparameters that is just about to overfit (for the precision)</p><figure><img alt="Testing Result of the Random Forest Classifier" src="https://cdn-images-1.medium.com/max/1024/1*8rTe175OTszxYwiACqeZvQ.png" /><figcaption>Testing Result of the Random Forest Classifier</figcaption></figure><p>The result shows that the algorithm works well to predict churn at a bank that has high customer retention (not many customers churned).</p><h3>Conclusion</h3><ul><li>The result shows that the algorithm works well to predict churn at a bank that has high customer retention (not many customers churned).</li><li>The results are quite peculiar: the more the estimator, the higher the precision score. Hence, for better results, we might want to adjust the Decision Tree Classifier hyperparameter.</li></ul><p>Here is the <a href="https://github.com/aifakhri/customer-churn-model">Github </a>of this project.</p><h3>Reference</h3><ol><li>Dietterich, T. G. (2000). Ensemble methods in machine learning. In J. Kittler &amp; F. Roli (Eds.), <em>First International Workshop on Multiple Classifier Systems</em> (pp. 1–15). Springer Verlag.</li><li>Biau, G., &amp; Scornet, E. (2016). A random forest guided tour. <em>Test</em>, <em>25</em>, 197–227.</li><li>James, G., Witten, D., Hastie, T., Tibshirani, R., &amp; Taylor, J. (2023). <em>An introduction to statistical learning with applications in Python</em>. Springer.</li><li>Hastie, T., Tibshirani, R., &amp; Friedman, J. (2008). <em>The elements of statistical learning: Data mining, inference, and prediction</em>. Springer.</li><li>L. Breiman. Random forests. Machine Learning, 45:5–32, 2001</li><li>Zhou, Z. H., &amp; Zhou, Z. H. (2021). <em>Ensemble learning</em> (pp. 181–210). Springer Singapore.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6485ee3b583" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Impact of Page Likes and Facebook Ads to Facebook Lifetime Post Consumption Metric]]></title>
            <link>https://medium.com/@aifakhri/the-impact-of-page-likes-and-facebook-ads-to-facebook-lifetime-post-consumption-metric-efc8802125d0?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/efc8802125d0</guid>
            <category><![CDATA[regression-analysis]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[facebook-marketing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Sun, 28 May 2023 10:49:23 GMT</pubDate>
            <atom:updated>2023-07-19T04:25:58.988Z</atom:updated>
            <content:encoded><![CDATA[<h4>A case study: Analyzing Facebook’s Lifetime Post Consumption Metric through the brand’s number of page likes and Facebook Ads Usage using statistical analysis and linear regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o65RUheUHM_SRSne" /><figcaption>Photo by <a href="https://unsplash.com/@nordwood?utm_source=medium&amp;utm_medium=referral">NordWood Themes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Facebook is the most popular social media on the internet with monthly active users of 2.96 million users worldwide[2]. For businesses or brands, this is a promising opportunity to build brand awareness to a wide range of audiences.</p><p>Harnessing Facebook for brands is not rocket science but it is also not easy. Brands need to build engaging content, through a Facebook post, that would lead users to consume their post, whether by liking, commenting, sharing, clicking the post, commenting on other people’s comments, etc. Hence, the consumption of the post would be a good metric to measure for the brands.</p><p>Post consumption would also lead to users sharing the post with people who do not yet like the brands’ page. Hence, this activity would impact the growth of the brand’s user base.</p><p>Sharing asides, a growing user base can be obtained with the help of Facebook Ads, or in this case paying Facebook, which is an advertising platform provided by Facebook to help businesses or brands to target a specific group of an audience or expose the brands to a wider audience in the Facebook networks.</p><p>Furthermore, with the help of Facebook Ads brands might get a better number of user interactions to their Facebook posts compared to Facebook posts without the help of Facebook Ads. Hence, evaluating and understanding posts interaction could benefit a marketing manager to decide whether to use Facebook ads for their campaign or not.</p><h3>Objectives</h3><p>In this study would have the following objectives:.</p><ol><li>Testing the assumption of whether using Facebook Ads (paying Facebook) would generate more user consumption of a post.</li><li>Building a regression model to predict post consumption based on the company’s page total likes and whether the post is using Facebook Ads.</li><li>Investigating the relationship between the total likes of a brand page and whether their post is using Facebook Ads or not.</li></ol><h3>Data Source</h3><p>The data used for this study is obtained from <a href="https://archive.ics.uci.edu/ml/datasets/Facebook+metrics">UCI Machine Learning</a>, more specifically from the research that has been done by Sergio Moro, Paulo Rita, and Bernardo Vala in 2016[1] where they built a data mining model to predict the performance of Facebook metrics.</p><p>The data itself is related to Facebook posts that were published in 2014 by a renowned cosmetic brand. The dataset consists of 500 rows and 19 variables which have been gathered from January to December 2011. However, as per the objectives, only the following variables would be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cn3inhNhJk8skJN7445CQw.png" /><figcaption>Figure 1 — Used Variables</figcaption></figure><h3>Hypothesis Testing: Facebook Ads</h3><p>Here, I would like to understand whether using Facebook Ads would increase users’ post-consumption, considering that using Facebook Ads would reach more users, hence, might also increase the post-consumption.</p><p>With that in mind, we could create the following null hypothesis:</p><blockquote>The lifetime post consumptions that use Facebook Ads should be greater than the lifetime post consumption that don’t use Facebook Ads</blockquote><p>We could formalize the hypothesis in the below equation:</p><figure><img alt="Null hypothesis and alternative hypothesis equation" src="https://cdn-images-1.medium.com/max/232/1*OdXnYviW0B8AzaeY1HloGA.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*07XLb6PciVVCDsKnW3R2Sg.png" /></figure><p>From the hypothesis above we could define that:</p><ol><li>We would use a one-tail statistic test by using a t-test</li><li>The significance is 0,05 (use the most commonly used significance)</li></ol><p>We use Python’s statslib library to get the p-value and t-test statistics value. From the calculation, we get the following:</p><ul><li>t statistics value = 0.181</li><li>p-value = 0.428</li></ul><p>From the table above we could see that the p-value is 0.428 which is lower than the alpha, which is 0.05. From this information, we should <strong>fail to reject the Null Hypothesis.</strong></p><h3>Building the Regression Model</h3><p>To get better interpretation of the relationship between total page likes and Facebook Ads, we would model the regression line using interaction using statslib. Here is the result of the regression model with interaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpAqhT5yOIdz5g974enY8g.png" /><figcaption>Figure 2 — Regression Line with Interaction plot</figcaption></figure><p>From the graph, we could get the following regression equation:</p><figure><img alt="Linear Regression with Interaction Equation" src="https://cdn-images-1.medium.com/max/584/1*LwF9CzcDTSXUvM40o5FBlQ.png" /></figure><p>From the equation above we could derive the following relationship:</p><ol><li>When Paid = 0<br>The estimated difference between lifetime_post_consumptions that are not paid on Facebook but differs 1 point in page_total_likes is 0.011</li><li>When Paid = 1<br>The estimated difference between lifetime_post_consumptions that is using paid Facebook but differs 1 point in page_total_likes is 0.015</li></ol><p>Hence, we could say that there is no significant difference in whether the company pays Facebook or not to promote its campaign towards post-consumption. Hence, we could recommend to the company not pay Facebook to save its marketing cost.</p><h3>Model Evaluation</h3><p>Our result could be confirmed by evaluating the regression model we’ve developed through the residual of the model and the r-squared value. Here is the residual of the model:</p><figure><img alt="Figure 3 — Residual plot for Linear Regression with Interaction" src="https://cdn-images-1.medium.com/max/1024/1*5GY5meDJOK7uTFqfhDlIDA.png" /><figcaption>Figure 3 — Residual plot for Linear Regression with Interaction</figcaption></figure><p>From the residual plot, we could see that most of the data are centered around the 0 value, which indicates that the residual distribution is close to the normal distribution.</p><h3>Conclusion</h3><p>Analyzing the impact of total page likes and paid (use Facebook Ads or not) is useful for business especially for marketing managers, because they can make a data-driven conclusion about whether to focus on growing the number of page likes or paying Facebook to promote their posts, which would be related to the marketing budget.</p><p>From the hypothesis testing, we could conclude:</p><ol><li>The fewer total page likes the business has, the more posts made by the company would likely be reduced too.</li><li>By paying Facebook we would get more post interactions from users.</li></ol><p>From the regression model with interaction we could conclude:</p><ol><li>If paid is 0 (not paying Facebook), the estimated difference between lifetime post consumption that is not paying Facebook but differs by 1 point in page_total_likes is 0.011. The estimated average is 2342.98.</li><li>If paid is 1 (paying Facebook), the estimated difference between lifetime post consumption that pays Facebook but differs by 1 point in page_total_likes is 0.015. The estimated average is 2807.1</li></ol><p>Here we could see that if paid 0 or 1 and the page_toal_likes increased by 1 point, the estimated average would only rise by 0.011 and 0.015. Hence, not that significant.</p><p>I performed this analysis with Jupyter Notebook and stored it on <a href="https://github.com/aifakhri/statistics-facebook-metrics">my github</a> with additional Exploratory Data Analysis along with more regression analysis. Feel free to check it out.</p><h3>References</h3><ol><li><a href="http://dx.doi.org/10.1016/j.jbusres.2016.02.010">(Moro et al., 2016) Moro, S., Rita, P., &amp; Vala, B. (2016). Predicting social media performance metrics and evaluation of the impact on brand building: A data mining approach. Journal of Business Research, 69(9), 3341–3351.</a></li><li>Dixon, S 2023, most popular social networks worldwide as of January 2023, ranked by monthly active users. Statistia. &lt;<a href="https://www.statista.com/statistics/272014/global-social-networks-ranked-by-number-of-users/">https://www.statista.com/statistics/272014/global-social-networks-ranked-by-number-of-users/</a>&gt;</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efc8802125d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Call Success of Bank Telemarketing Campaign with Machine Learning]]></title>
            <link>https://medium.com/@aifakhri/predicting-call-success-of-bank-telemarketing-campaign-with-machine-learning-4db3cf604d0a?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4db3cf604d0a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 15:52:45 GMT</pubDate>
            <atom:updated>2023-02-12T15:52:45.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NBsjrIHHEv5nidXb" /><figcaption>Photo by <a href="https://unsplash.com/@homajob?utm_source=medium&amp;utm_medium=referral">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Telemarketing is the direct marketing of goods or services to potential customers over the telephone, internet or fax [2]. Although, telemarketing is commonly done over direct phone calls where the telemarketer persuades the potential users to subscribe to the company’s product. Hence, the success of telemarketing can be measured by calls that have been made.</p><p>Prioritizing, targeting and selecting potential customers with a certain characteristic to the offered products are one way to improve the success of the calls. However, the telemarketer or the company that holds the telemarketing campaign can’t figure out which customers are more likely to subscribe over other customers on their database.</p><p>A supervised machine learning model can be utilized to predict the success of the calls (or output) based on users general information (act as input) such as age, job type, income, etc. along with last contact information during the campaign and the attributes of social and economic conditions such as employment rate, consumer confidence index, etc.</p><h3>Related Work</h3><p>This project is derived from previous work/research [1], where the researchers used Decision Tree (DT), Logistic Regression, SVM and Neural Network as the machine learning models. For model evaluation, they use AUROC and LIFT analysis.</p><p>Those models are commonly used classifiers especially for SVM and Neural Network (NN) which are more complex models compared to Decision Tree and Logistic Regression. Although, SVM and NN are hard to explain when the model complexity is higher than complex DT and Logreg models.</p><p>In this study we would use the ML algorithm from the previous works (Decision Tree and SVM) except for NN due to insufficient computing power. Furthermore, we would also add the KNN which is a simple model that sometimes can produce a model that is surprisingly close to the Bayes classifier, which is an unattainable gold standard classifier [3]. Then we will use some of the ensemble methods algorithm: Random Forest, AdaBoost and Gradient Booster.</p><p>For model evaluation we are not going to use LIFT analysis, we would also use AUROC analysis. The AUC results of the previous work is 0.8 from the Neural Network algorithm. Hence, for this work we would try to match the AUC=0.8 performance.</p><p>Also, the dataset itself is imbalanced and the previous works were using the under-sampling method. In this work we will use the SMOTE algorithm to handle data imbalance.</p><p>Another evaluation metric that will be assessed is the recall value. We will focus on recall because for a company, falsely predicting a success call as a failed call is costly. Hence, we want to reduce false negatives as much as possible.</p><h3>Dataset &amp; Features</h3><p>The dataset itself is the telemarketing campaign data (last contact data) of a Portuguese banking institution and their clients data. There is also social economics data to be considered in this data given this data was taken from 2008 to 2012 when global recession had happened and economy had been shifting, hence might affect greatly to the marketing campaign result. You can find this <a href="https://archive.ics.uci.edu/ml/datasets/Bank+Marketing#">dataset in the UCI Machine Learning</a>.</p><p>The dataset consists of 1 output and 20 inputs (features) with a total of 41180 data points. As mentioned it is a combination of telemarketing metrics, clients data and socioeconomics data, and here are some samples of the feature for each combination:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*9AuAuiwZrJke_vefG_WgkQ.png" /><figcaption>Some dataset information</figcaption></figure><p>“Yes” or “No” indication whether the client subscribed to the bank product during the campaign</p><p>One thing to note in this dataset is that we will omit one feature called duration because as per recommendation of this feature might cause data leakage hence reduce the performance of the models.</p><h3>Machine Learning Models</h3><p>In this project we would explore some machine learning models from the simple ones like K-Nearest Neighbors, Decision Tree and (slightly complex) Logistic Regression will be used to get comparison to more complex models such as Support Vector Machine, Random Forest, Adaboost and XGBoost.</p><p><strong>K-Nearest Neighbors (KNN) </strong>can be considered as the simplest machine learning model due to its prediction mechanism: estimate the distance of a data point (observation) to its nearest neighbors (other data points or observations). The nearest neighbor is often called k-observations and the distance between an observation to its k-observation is commonly calculated with euclidean distance method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*6hTlFD4eBnAK1tNyPt23Eg.png" /><figcaption>Euclidean Distance Equation</figcaption></figure><p>There are other methods to calculate distance between two and more observations: Manhattan, KLM, etc.</p><p>Despite being considered as a simple model, KNN sometimes can produce a model that is surprisingly close to the Bayes classifier, which is an unattainable gold standard classifier [3].</p><p><strong>Decision Tree (DT)</strong> is a branching structure that represents a set of rules, distinguishing values in a hierarchical form [1], here is the example [3]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*696tsdGhyjkO0JJQ" /><figcaption>Decision Tree Example</figcaption></figure><p>The set of rules in the DT classifier is built based on the information gain which can be found from calculating entropy on a given observation.</p><p>Entropy calculates the impurity of the observations, the more impure the observations the better the impurity results. However, at the next split the impurity of the split should be less impure than the previous one. The total entropy calculation of each split is what we call information gain:</p><p>information gain = entropy(parent)-[average entropy(children)]</p><p><strong>Logistic regression</strong> is the most commonly used classifier, it has slightly more complex models than DT and KNN but it can be interpreted easily by humans. Logreg model is derived from linear regression model by “squashing” the linear function into logistic function[3]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/0*em9A0yIAYz1zAqyX" /><figcaption>Logistic Regression Illustration</figcaption></figure><p>The function that squashed the linear line is called the sigmoid function and it represents in this equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*Fqpw2B3Y1c7cOVNVXRzwsQ.png" /><figcaption>Sigmoid Function equation</figcaption></figure><h3>Ensemble Model</h3><p>Ensemble method is an approach that combines many simple “building block” models in order to obtain a single and potentially very powerful model [3]. More models would result in better model’s performance. There are some models that have been built on top of this method.</p><p><strong>Random Forest</strong> is a tree-based model that utilizes an ensemble method. Ensemble method works by using the Bootstrap technique: resampling with replacement multiple times (is called B-Bootstrapped) and models each “resample” to get the aggregated errors.</p><p>The purpose of creating a B-Boostrapped data is to get uncorrelated model results which can be used to further improve the error of the data. Random Forest is a way to produce more uncorrelated model results from the B-Bootstrapped data by adding features randomization on each B-Bootstrapped calculation. Hence, not all features on each B-Boostrapped calculation are used, instead only a subset of features.</p><p><strong>Adaboost (Adaptive Booster)</strong> is also derived from the ensemble method (and also uses Bootstrap). However, Adaboost run the least complex tree-based models, it is combining weak learners (a simple model), and correct the output error from the weak learner by weighting the error and retrain the weak learner to become a strong learner[4]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*W8m4dPFTQJ5myGWa" /></figure><p><strong>Gradient Boosting</strong> is very similar to Adaboosting, it is a boosting algorithm with a purpose to strengthen a weak learner into a strong learner. The major difference is that gradient boosting uses gradient descent to solve the loss function.</p><h3>Experiments/Result</h3><p>As mentioned our data is imbalanced:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*yMquj-Ys3u9jXtTI" /></figure><p>Also, we decode the “no” and “yes” into 0 and 1 respectively for easier calculation. Furthermore, SMOTE is used to balanced the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*YWfazOX5_HrSC7y8" /></figure><p>With “minority” as the sampling strategy, SMOTE will synthetically over-samples the minority class [7], in this case the “1” class or “yes” class. Since, smote will add more data, the data will be split into 30% for the test data and 70% for the train data. This to minimize the risk of train data to learn noise during the test.</p><p>To find the best parameters in each model, Cross Validation technique is used. The number of k-fold is 7 to get a better hyperparameter compared to the less k-fold. The GridSearcCV from the Sklearn library is used, and the n_jobs will be set to -1 to give more computational power and faster CV calculation result.</p><p>Here is hyperparameter selection consideration for each model</p><p><strong>K-Nearest Neighbor<br></strong>The calculation distance will be set to Manhattan because the dimension of the data is quite high. For the numbers of n_neighbors, we will pass the value from 3 to 17. A low number of neighbors is undesirable since it will lead to a more complex model and overfitting.</p><p><strong>Decision Tree<br></strong>For the decision tree we will use Gini index for faster computation[5]. For the max depth of the tree we will be decided through a cross validation process, the max depth 5–37 will be tested in the cross validation process.</p><p><strong>Logistic Regression<br></strong>We will use the liblinear solver so we can select whether the penalty should be L1 norm or L2 norm during the cross validation process. For the hyperparameter C will be defined with cross validation, the evaluation of c is from log(5) to log(-5).</p><p><strong>Adaboost<br></strong>For Adaboost, a simple decision tree with max depth of 2 will be created first as the weak learners. The number of estimators will be selected through a cross validation process. The value of the number of estimators is 300 to 800 estimators.</p><p><strong>Gradient Boost<br></strong>Most of the hyperparameters in gradient boost will be set to default since this algorithm is an improvement to adaboost. The only parameters that is used in the cross validation process is the n estimators, where the value of 300 to 800 estimators.</p><p><strong>Random Forest<br></strong>For random forest, we will set the criterion to gini for faster computing, and max features to the square root which is the recommended feature selection technique [8]. Only the number estimators will be used in the cross-validation process, the number of estimators are from 300 to 800 estimators.</p><p>Here are the best parameters after being processed within cross-validation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*DpZupYESiPw6czC_9JpFWg.png" /><figcaption>Best Hyperparameter</figcaption></figure><p>Then, the models are trained with these hyperparameters, respectively. Here the classification score for each trained mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*Qm3dQ_Mo8CxhO4H__PGMxw.png" /><figcaption>Classification score for training data</figcaption></figure><p>As mentioned, we will focus on the recall metrics due because we want a small false negative value. From the table above the recall value for each model is relatively high. With the exception of Logistic regression.</p><p>And here is the AUC from the ROC curve for all models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*LVSYg8qg_znY42Qt" /><figcaption>AUC ROC Curve for training Data</figcaption></figure><p>So far all models, except for logistic regression, have a good AUC score, however, Random Forest’s AUC value indicates an overfitting because its AUC is 1. Also, all of the Random Forest classification scores are near 1. This might be due to the high number of n_estimator.</p><p>We fit the model to the test data and here is the result of the classification score</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*dw6sUOPnWaLzpaEKpo4yqQ.png" /><figcaption>Classification score for test data</figcaption></figure><p>As we can see our models are not performing well for the recall score, and here is the AUC value from ROC curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*NGz1PPiQasGcKsiI" /><figcaption>ROC AUC Curve for test data</figcaption></figure><p>From the recall score and AUC score, only logistic regression that is performing well. For K-nearest and Decision Tree models, the AUC and recall seems reasonable since those are simple models. However, for the ensemble methods the AUC and recall should be questionable. Hence, the next experiment will focus on the boosting algorithm.</p><h3>Experiment with Boosting</h3><p>In theory adding more n-estimators to the models would cause overfitting. Hence this experiment would be conducted by reducing the number n-estimators, and for Adaboost and Gradient Boost we would also reduce the learning rate, so the model could make more iterations to find the minimum error, which can improve our models.</p><p>After running some experiments, only gradient boosting can make improvement by reducing the number of n-estimators to 100 and learning rate to 0.01. Here is the result of the classification score for the Gradient Boosting experiment.</p><p>Here is the training result for the experiment with Gradient Boosting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*0m4ATLNyTyeTZZOCMSFyOQ.png" /><figcaption>Classification score for the training data for when Experimenting with Gradient Boost</figcaption></figure><p>Here is the AUC ROC curve for the train data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*_E_5Qk4F3ZVAcGFw" /><figcaption>AUC ROC curve for the training data for when Experimenting with Gradient Boost</figcaption></figure><p>This is the classification score from test experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*Mkuo4dBBNzT17nq3VE1L2w.png" /><figcaption>Classification score for the test data for when Experimenting with Gradient Boost</figcaption></figure><p>This is the AUC ROC curve from the test experiment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*hG4Fk4toiKf_edD5" /><figcaption>AUC ROC for the test data for when Experimenting with Gradient Boost</figcaption></figure><p>The results are peculiar because instead of using the large n-estimators we could just use the small one, which at 100, additionally we reduce the learning rate to 0.01. Although we have tested for n-estimator of 150 and learning rate of 0.001, the result is still below the prior experiment.</p><h3>Conclusion and Future Works</h3><p>Most models we’ve developed are overfitting. We’ve assumed that the main culprit of this issue is the SMOTE algorithm. Despite its synthetic nature, there is too much additional data that is added to our dataset, hence causing more noise and making our model overfit.</p><p>The other reason we could think of this result is that the boosting hyperparameters for each model is too simple, resulting in an ineffective model. Hence, adding more hyperparameter attributes to the boosting model might improve the model.</p><p>Despite the bad result, the AUC and Recall result for the Logistic Regression model performs the best among the models we’ve developed. The AUC result also overcome the Logistic regression mode from the previous works.</p><p>Also, after some experiments, we could improve the Gradient Boost performance by reducing the number of n_estimators and the learning rate.</p><p>I have published the notebook on my Github Account, <a href="https://github.com/aifakhri/ml-model-bank-marketing">feel free to check it out</a>.</p><h3>Future Works</h3><p>This work is not performing well compared to the previous works, and based on the result the SMOTE algorithm can’t provide the best result for this type of data. Hence, using other workarounds for imbalance data such as weighting within the algorithm can be used, instead of SMOTE. We could also use XGBoost and Neural Network to get better results.</p><h3>References</h3><p>[1] S. Moro, P. Cortez and P. Rita. A Data-Driven Approach to Predict the Success of Bank Telemarketing. Decision Support Systems, Elsevier, 62:22–31, June 2014</p><p>[2] <a href="https://www.investopedia.com/contributors/53661/">W</a>ill Kenton. Telemarketing: Definition, What They Do, Example and Types. <a href="https://www.investopedia.com/terms/t/telemarketing.asp">https://www.investopedia.com/terms/t/telemarketing.asp</a></p><p>[3] G. James, D. Witten, T. Hastie and R. Tibshirani. An Introduction to Statistical Learning with Application in R, Second Edition.</p><p>[4] Team Pacmann, Intro to Machine Learning course material.</p><p>[5] <a href="https://quantdare.com/decision-trees-gini-vs-entropy/">Pablo Aznar, Decision Trees: Gini vs Entropy, Quantdare.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4db3cf604d0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paid Search Marketing Dashboard]]></title>
            <link>https://medium.com/@aifakhri/paid-search-marketing-dashboard-ad23e6bac36b?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad23e6bac36b</guid>
            <category><![CDATA[ppc-marketing]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 17:02:13 GMT</pubDate>
            <atom:updated>2023-02-11T17:05:41.176Z</atom:updated>
            <content:encoded><![CDATA[<h4>Developing easy and interactive dashboard for PPC campaign based on the online mall store data.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b49WMjrKYj3TGm0a" /><figcaption>Photo by <a href="https://unsplash.com/@hostreviews?utm_source=medium&amp;utm_medium=referral">Stephen Phillips - Hostreviews.co.uk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>According to <a href="https://www.wordstream.com/paid-search">wordstream.com</a>, paid search marketing is an inexpensive and scalable form of web marketing designed to connect the ads with searchers actively seeking what is provided by a company. PPC or Pay-Per-Click is one of the paid search marketing campaigns. PPC is worked by a company placing their ads in a search engine’s sponsored links for keywords related to the company’s business, then the search engine would show the ads on top of Search Engine Result Page (SERP), and lastly the company pays the search engine a fee for each click on the links.</p><p>Here is the example of paid search marketing with PPC on Google search:</p><figure><img alt="PPC Campaign on Google platform" src="https://cdn-images-1.medium.com/max/1024/0*MEpzegNOysN1gJP5" /><figcaption>PPC Campaign on Google platform</figcaption></figure><p>One thing to note is that for each user the query results (hence the ads) would be different due to Google algorithm.</p><p>PPC can be very lucrative but can also be expensive. The success of PPC depends on how businesses plan their campaign and understand the underlying metrics behind it. <a href="https://www.gartner.com/en/digital-markets/insights/measure-ppc-campaign-performance">Gartner defines</a> that paid search (PPC) metrics can be grouped into more focused KPI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*Sxvb3WAR9zKohV0y16bGfA.png" /><figcaption>PPC metrics per KPI — Gartner</figcaption></figure><h3>Problem Statement &amp; Goals</h3><p>The stakeholders in the marketing division such as marketing manager or marketing director should be able to quickly decide actionable strategies for the PPC campaign based on the revenue-cost metrics (CPC, ROAS, CPM, etc), conversion metrics (Conversion Rate, Conversion, Source of Conversion) and traffic metrics (Impressions, Clicks and CTR) between marketing periods.</p><p>For the PPC campaign itself, the marketing manager should be able to optimize the ad groups for the next PPC campaign based on the metrics for each ad group in the current period and previous period.</p><p>From the problem above our goals here are:</p><ol><li>Creating a dashboard for the marketing manager to understand and monitor the PPC campaign by comparing the Revenue metrics, Conversion Metrics and Traffic Metrics between marketing periods.</li><li>Providing marketing metrics for each ad groups per keyword matching types for marketing manager to be able to optimize the PPC ad groups between marketing periods.</li></ol><h3>User Flow</h3><p>Based on our mission we would develop a dashboard that can help the marketing manager to deduce their analysis of the marketing performance by looking at the revenue metrics on the current period. Then, they could compare the the revenue with the conversion metrics to understand the impact of conversion metrics to the revenue.</p><p>To further improve their analysis, users can find the marketing period as comparison to the current period.</p><p>Furthermore, they can also compare the conversion metrics with the traffic metrics to understand the source of the revenue and cost metrics on the current period and the best period to have more insights. Lastly, the marketing manager can compare the ad groups performance on the current period and the best period to optimize the ad groups performance.</p><p>Here is the flow diagram of the marketing manager journey:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ta3hw2Ql58q3eKxu" /><figcaption>User flow — <em>*For more clarity of the diagram above please </em><a href="https://drive.google.com/file/d/1i6QyHQGSAZ86eN_rZcDM1jIzqufrXHSS/view?usp=sharing"><em>click this link</em></a></figcaption></figure><h3>Dataset Explanation</h3><p>The dataset is from <a href="https://www.kaggle.com/datasets/marceaxl82/shopping-mall-paid-search-campaign-dataset">kaggle</a>, and the dataset describes a paid search marketing campaign from a certain online shopping mall in the United States from July to November 2021.</p><p>The dataset size is 12 x 1000, the variables are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*1F5LL7zIOUm-WpreZNz-Mw.png" /><figcaption>Dataset</figcaption></figure><h4>Breakdown the Ad Group Variable</h4><p>The Ad Group variable data points consist of a lengthy text which has valuable information that could be extracted as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*sEUGQ0BDhw66fWEsvWOYlg.png" /><figcaption>Ad Group variable Extraction</figcaption></figure><p>From the table above we could get the following information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*qgKtQbrjPehhRUxF9KNMFg.png" /><figcaption>Variable Explanation from the Ad Group extraction</figcaption></figure><h4>Extracts More Metrics from Data</h4><p>From our data we could get more information that could we use to support the business objectives, here are the metrics we extracted from the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*DQBNYZYJTAnQnMcM6nAi5Q.png" /><figcaption>New metrics from the current dataset</figcaption></figure><h3>Dashboard Visualization &amp; Insight</h3><h4>Dashboard Overview</h4><p>Here is the finished dashboard view, for more details check out this <a href="https://public.tableau.com/views/PaidSearchDashboard_16755095815440/FinalDboard?:language=en-US&amp;:display_count=n&amp;:origin=viz_share_link">link</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*clCHNhMfEmNyXc0V" /><figcaption>Overall Dashboard View</figcaption></figure><p>The top metrics are revenue-costs metrics such as average Cost per Conversions, average Cost per Click (CPC) and average Cost per Impressions (CPM) along with total revenue and costs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fi16nEI155m2MD_N" /></figure><p>The up and down arrow along with percentage value behind it represent the comparison between the next-month and the previous month metrics, and the percentage represents the change in percent between periods.</p><p>The select period menu (marked with the red rectangle) is arranged by the current period first then the previous period. For example, the “Current Period” menu compares the current month (November) and the last month (October). Hence, “Last period” menu compares the current month of October and Previous month of September and so on.</p><p>After understanding the marketing revenue and cost metrics the marketing manager is expected to combine the revenue-cost metrics on the scorecards with the conversion metrics over time to gather more insights about the relationship between those metrics as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xBhgY793dKfBeCrU" /></figure><p>The conversion metrics’ performance over time can be divided by Match Type and Devices. These divisions are useful for comparing conversions with the traffic metrics such as impressions, clicks and CTR.</p><p>Hence, the traffic metrics is placed below the conversion metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TKsp45SYPCrc8gry" /></figure><p>The traffic metrics is shown through a bar chart and can be divided by the devices and match types so we could compare with conversions over time easily. We could also select which month we want to explore the traffic metrics.</p><p>The last thing to do for the manager is to review the ad groups’ performance. In paid search marketing, an ad group is a container of one or more ads that share similar targets and is commonly used for organizing ads by a common theme <a href="https://support.google.com/google-ads/answer/6298?hl=en#:~:text=An%20ad%20group%20contains%20one,ads%20by%20a%20common%20theme.">[4]</a>. The metrics above are related to a specific ad group, hence we could measure the performance of the ad group which can help the marketing manager to allocate budget for each ad group.</p><p>In this table the ad group is organized by match type, hence the marketing manager can also evaluate the match type performance. And there are two menus:</p><ol><li>The menu to compare ad group performance on each marketing period</li><li>Match Type menu to select which match type should be reviewed</li></ol><p>Here is the example of the dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mZ1j2DCy-6ARVKEx" /><figcaption>Ad Group Table Example</figcaption></figure><h4>Data Analysis &amp; Insights</h4><p>We would gather the insight through the questions that can be answered by the dashboard. And those questions would be structured into 3 sections based on the dashboard structure that has been defined above.</p><h4>Cost-Revenue and Conversion analysis</h4><p><strong>Question: How are the revenue and costs metrics performance in the current period?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nn7RjdW52cPuW7kA" /><figcaption>Revenue and cost metrics scorecard</figcaption></figure><p>All of the metrics have increased drastically from the previous period, except for the cost per conversions, although this makes sense because the marketing cost has increased by 258,76%.</p><p>Despite the marketing cost being higher than revenue, the average ROAS for each ad group is 1,2. Meaning that, on average, the company generates $1,2 for each cost $1. Although still lower than some standards.</p><p>The other revenue-costs metrics, CPC and CPM are relatively low and perform better than the previous period in term of revenue-cost metrics.</p><p><strong>Question: How are the trend of conversion metrics affect the revenue-cost metrics in the current period?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V90qAeP_TeVbykiS" /><figcaption>Revenue-cost scorecard vs conversion metrics in the current period</figcaption></figure><p>The conversion is increased drastically from October to November. Hence, this trend explains why the current revenue-cost metrics in the current period are improving dramatically.</p><p>However, the conversion rate from October to November is not increasing (although there is 0.06% drops), which indicates that the increase of conversions are not due to the marketing effort, but it can be due to the Thanksgiving or Black Friday event in November where there is a gift giving tradition, hence people it seems more people are just looking for gifts through the site or apps without buying.</p><p>Unfortunately, we don’t have the daily data to show a more detailed impact of this event.</p><p>Furthermore, to improve the conversion rate and conversions in the next period, the marketing manager could advise the sales manager to put more competitive pricing as part of the next PPC campaign planning, considering next month is December where there are Christmas and New Years events.</p><p>From the conversion rate graphs we could also see that from September to October (which is the last period) there is a 1,28% increase of conversion rate, which is higher than any other period. Hence, it would be wise to analyze that period to get more insights.</p><p><strong>Question: How are the revenue-cost metrics performance compared to the conversion metrics at the other period?</strong></p><p>As mentioned above there is a 1,2% improvement on average of conversion rate in the September to October, hence we refer the last period as the other period:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CZWpucpkX4VFPR3D" /><figcaption>Revenue-cost scorecard vs conversion metrics in the last period</figcaption></figure><p>As you can see the improvement in conversion rate is affecting the marketing revenue greatly where it can outweigh the marketing cost, despite the loss in the average ROAS for all ad groups from the previous period by 20.71%.</p><p>This shows that marketing effort in this period generates more revenue than costs. It can be wondered why the November to October period keeps using the strategy in this period.</p><p>The other metrics are improving nicely, with the exception of the average CPC metrics, where it has raised 1.74% compared to the previous month.</p><p>We could argue that this period is where the marketing campaign performed the best due to the revenue outweighing the marketing cost and conversion and conversion rate improvement.</p><h4>Traffic and Conversion analysis</h4><p><strong>Question: How are the overall traffic metrics performance trends by Devices?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PKaScjRcjksAB4TG" /><figcaption>Overall traffic metrics per devices</figcaption></figure><p>Most users are coming from mobile devices with total impressions and clicks from mobile devices are 1.916.806 and 689.564 respectively. This makes sense considering the number of mobile phone users.</p><p>Despite being dominated by mobile devices, the CTR shows that there is only a 3,82% difference between traffic coming from desktop and mobile. Hence, to reduce this gap the marketing manager could fabricate better PPC campaign content or the CTA message for users.</p><p>The grand total of Average CTR is at 27,21% which is way beyond some industry standards which is around 4–5%. This could be due to the fact that July — November 2021 are during the 3rd wave of Covid pandemics. Hence, a lot of people might be still shopping online due to mobility restrictions and causing more clicks on the ads.</p><p><strong>Question: How are the overall traffic metrics performance trends by Match Type?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ol12oA--svMztT7P" /><figcaption>Overall traffic metrics match types</figcaption></figure><p>The 1:1 or broad match has better impressions and generates more traffic than the Exact and Phrase match types. This makes sense because in the paid search marketing broad match match-type is commonly used to generate more traffic due to its matching flexibility.</p><p>However, the company needs to be more careful in planning to invest more in the 1:1 match because it costs more compared to the other match types.</p><p>The gaps between 1:1 match types for all traffic metrics are pretty steep, to improve this perhaps the company should do A/B testing on ad groups that use exact and phrase match types to collect more clicks and impressions from users.</p><p><strong>Question: What is the impact of traffic metrics to the conversion metrics by device type in the current period (November-October)?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m4ldhbDp98xiHoQ0" /><figcaption>Conversion metrics vs Traffic Metrics based on the Device Type</figcaption></figure><p>Conversion rate from Desktop over time is much higher on the desktop compared to mobile devices that dominate the traffic metrics. This is also applied in the current period (November). Hence, this could indicate that the company’s PPC campaigns has not been targeting the right audience. Also, there is a possibility of bad design of the checkout process in the mobile apps, which makes the mobile users to not convert.</p><p>Furthermore, allocating more budget and creating better content for the ad group that targets desktop users can be pursued for the next marketing campaign.</p><p>Also, the marketing manager can discuss with other divisions regarding the checkout process for the mobile apps, hence the marketing manager can understand what is causing the low conversion rate for the mobile device despite getting more traffic from users.</p><p><strong>Question: What is the impact of traffic metrics to the conversion metrics by Match Types in the current period?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_-ClQWoIwc2hxkFG" /><figcaption>Conversion metrics vs Traffic Metrics based on the Match Type</figcaption></figure><p>From conversion perspective, the trend in the traffic metrics by match types is matched. However, from conversion rate perspective, the conversion rate by match types is distributed (almost) evenly per match type.</p><p>This looks concerning, because it seems that the the 1:1 match types can’t make user converting or buying products from the store, hence, focusing on the other match type is preferable.</p><p>However, from the benchmark perspective, the conversion rate per match type are still above some standards [6]. Hence, we could still choose to invest in the 1:1 match type.</p><h3>Ad group and match type performance analysis</h3><p>From the previous analysis we get the insight that During the October-September period the marketing campaign attracts more revenue than the other campaign</p><p>From the information above we could not just analyzing the current ad group performance, but we can also analyze the ad groups between period to get better insight.</p><p><strong>Question: How is the ad group performance during the current period and last period on the 1:1 match types?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TqWYFSyLw3-oiGov" /><figcaption>Ad groups for 1:1 match types current period</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rB7zPeFdgsdfhaug" /><figcaption>Ad groups for 1:1 match types last period</figcaption></figure><p>From each ad group from the current and last period we could decide that the “[shop promo code]”, the “[shop discount code]” and the “[shop coupon code]” perform better than any other ad groups within the 1:1 type match bracket. The revenue, CPC and conversion rate always improve on each period. Although the CTR during is not improving from the current and last period, hence the marketing manager can allocate more budget to improve CTR for this ad group through developing better CTA in the next campaign.</p><p>The marketing manager should consider combining the [shop promo] and [shop coupon] ad groups, because those metrics are among the lowest CTR and cannot generate more revenue, but the [shop promo] generates relatively high conversion rate whilst the [shop coupon] ad group can generate more revenue, impressions and clicks compared to the [shop promo] ad group (although those metrics are relatively low compared to the other ad group). Hence, creating a new ad group from [shop promo] and [shop coupon] can be used to optimize the next marketing campaign.</p><p><strong>Question: How is the ad group performance during the current period and last period on the Exact match type?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jLPm5n2_ZtUc1vIZ" /><figcaption>Ad groups for Exact match types current period</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2oJzbDTkXy86bE70" /><figcaption>Ad groups for Exact match types last period</figcaption></figure><p>The most notable thing of these ad groups within the current and last period are the Black Friday/Cyber Monday and Competitor ad group. Black Friday/Cyber Monday ad group is a seasonal ad group that only occurs during the current period due to a special events. This ad group generates excellent conversion rates with a low marketing cost even though it doesn’t generate the best revenue and CTR. However, having this kind of ad group for a special event could be a good idea.</p><p>The competitor ad group means that we try to steal our competitor traffic through bidding their keyword <a href="https://adespresso.com/blog/adwords-competitor-targeting/">[5]</a>, then we create a better value proposition or better CTA than our competitor. This strategy is valid but in a healthy manner, focusing too much on this ad group is costly.</p><p>The well performing ad groups during the current and last period for the Exact match type are the <strong>promo code</strong> and <strong>coupon code</strong>. The revenue impressions, clicks, and CTR are always improving with relatively low Cost, CPC and CPM. However, a good conversion rate is only for the promo code ad groups, whilst the coupon code’s conversion rate needs to be improved.</p><p>Furthermore, the marketing manager can focus on improving the conversion rate of the discount code conversion rate through a discussion with other divisions regarding pricing and perhaps improving the checkout process. Also, they can allocate more budget for generating more revenue for the promo code ad group.</p><p>The <strong>Sale, Discount Code and Offer</strong> ad groups can be seen as a bad ad group despite a high conversion rate for the Offer ad group and low CPC and CPM on each ad group. In general these ad groups are low on the CTR and it generates more costs than revenue. The marketing manager should reconsider using these ad groups or combining these ad groups with the Free Shipping ad group.</p><p>Free shipping is an interesting ad group because it generates a fairly good CTR, a low average CPC and CPM also an excellent conversion rate. Hence, this can be used as the ground work to create new marketing campaign to replace the Sale, Discount Code and Offer ad groups.</p><p><strong>Question: How is the ad group performance during the current and last period on the Phrase match types?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rpRpRvTkYlamnX9o" /><figcaption>Ad groups for Phrase match types current period</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_rT_q0utEEFSdd62" /><figcaption>Ad groups for Phrase match types last period</figcaption></figure><p>Just like in the Exact match types, having competitor ad groups in the Phrase match types is a good idea. Furthermore, the <strong>Promo Code, Discount Code, Coupon Code and Offer</strong> ad group performs better than any other metrics. Those ad groups keep improving from the last to the current period and the metrics like Impressions, Clicks, conversion rate and revenue keep always relatively high and the Cost, CPC and CPM are relatively low. Hence, allocating more budget for these ad groups are advisable for the marketing budget to get more traffic and conversions, hence improving revenue.</p><p>The <strong>sale ad group</strong> can be considered under an performing ad group. It has low CTR, conversion rate and revenue despite having the lowest cost, CPC and CPM and improving over periods. However, the improvement from the last period is not significant, hence dropping this ad group could be considered.</p><p>There is one peculiar ad group which is the Free Shipping ad group where it performs better on the last period in terms of conversion rate but significantly dropped during the current period. If we further investigate, this ad groups has been performed better from September-August period to the last period:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lupfDvNVtkRCMvkU" /><figcaption>Free Shipping ad group september-august period</figcaption></figure><p>Hence, we could safely understand that this period has been kept due to its high conversion rate and low cost ad group. Since it drops on the current period we should reconsider using the Free Shipping ad group for the future campaign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bYHVPi-67cyUyP9b" /><figcaption>Free Shipping ad group last period</figcaption></figure><p>Another strategy for the Free Shipping and Sales ad groups can be developing a new ad group based on these ad groups for the next PPC campaign.</p><h3>Conclusion</h3><p>The dashboard we have created is highly interactive and easy to understand. The analysis can be gathered from the most broad perspective (revenue-cost metrics on the scorecard) and then narrowed to more specific analysis through combining other metrics and the other marketing period together for more in-depth analysis.</p><p>The dashboard also provides the ad groups table divided by the match types. On the table, there are also marketing metrics that can be used to optimize the ad groups whether to scale the ad groups or to remove the ad groups.</p><p>Hence, we could say that our dashboard has achieved our problem statements, which is creating a Paid Search or PPC dashboard for the marketing manager with 2 purposes as follows.</p><h4>1st Problem Statement</h4><blockquote>The stakeholders in the marketing division such as marketing manager or marketing director should be able to quickly decide actionable strategies for the PPC campaign based on the revenue-cost metrics (CPC, ROAS, CPM, etc), conversion metrics (Conversion Rate, Conversion, Source of Conversion) and traffic metrics (Impressions, Clicks and CTR) between marketing periods.</blockquote><p>The solution for this mission statement is a dashboard that can be easily navigated for the marketing manager to compare the metrics and get insights from each marketing period. The dashboard is structured that, at first, the marketing manager can get insights of the current revenue and cost metrics such as (Cost, Revenue, ROAS, Cost per Conversion, CPC and CPM).</p><p>Then they can get additional insights by comparing those information with conversion and conversion rate trends. And also can understand the which traffic source and metrics affects the conversion metrics.</p><h4>2nd Problem statement</h4><p><em>”the marketing manager should be able to optimize the ad groups for the next PPC campaign based on the metrics for each ad group between marketing periods.”</em></p><p>We have created a table at the bottom of the dashboard. The table is able to highlight the performance of the existing ad groups in each marketing period (in this case monthly basis) and is divided per match type for better overview. On the table we also have provided the metrics hence the marketing manager can focus when analyzing the ad groups performance and make a decision based on the metrics on the table.</p><p>From this table the marketing manager can optimize the ad group through keeping well-performed ad groups or dropping/combining low performance ad groups.</p><h4>Further Improvement</h4><p>We could further improve the dashboard by doing these things:</p><ul><li>Improving data gathering not for monthly but daily period, hence we could get the marketing period in a better detail.</li><li>Gather data from multiple PPC campaign channels, such as Google Ads, Facebook Ads, etc for better overview of the PPC channels.</li><li>Creating two dashboard, first dashboard for analyzing marketing metrics in more general matters and the second dashboard is for analyzing ad groups.</li></ul><h4>References</h4><ol><li><a href="https://www.cloudwards.net/search-engine-statistics/#:~:text=What%20Percentage%20of%20People%20Use,%25%20and%20DuckDuckGo%20at%200.67%25.">22 search engine statistics, Facts &amp; Trends for 2023, Max Pitchkites, couldwards.net</a></li><li><a href="https://www.gartner.com/en/digital-markets/insights/measure-ppc-campaign-performance">10 key metrics to measure PPC campaign success, Mark DiGiammarino, Gartner.com</a></li><li><a href="https://www.kaggle.com/datasets/marceaxl82/shopping-mall-paid-search-campaign-dataset">Shopping Mall Paid Search Campaign Dataset, Marcello D, Kaggle</a></li><li><a href="https://support.google.com/google-ads/answer/6298?hl=en#:~:text=An%20ad%20group%20contains%20one,ads%20by%20a%20common%20theme.">Ad Group Definition, Google</a></li><li><a href="https://adespresso.com/blog/adwords-competitor-targeting/">AdWords Competitor Targeting: Everything YOu Need to Know to Do it Right, Brad Smith, Adespresso.</a></li><li><a href="https://www.wordstream.com/blog/ws/2019/08/19/conversion-rate-benchmarks">Conversion Rate Benchmarks: Find Out How YOUR Conversion Rate Compares, Conor Bond, wordstream.com.</a></li><li><a href="https://public.tableau.com/views/PaidSearchDashboard_16755095815440/FinalDboard?:language=en-US&amp;:display_count=n&amp;:origin=viz_share_link">Paid Search Marketing Dashboard by Fakhri Azhar</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad23e6bac36b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Cleaning and Product Analysis with Python Pandas, Seaborn and Matplotlib]]></title>
            <link>https://medium.com/@aifakhri/data-cleaning-and-product-analysis-with-python-pandas-seaborn-and-matplotlib-235af14e2c5d?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/235af14e2c5d</guid>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Sat, 03 Dec 2022 15:41:54 GMT</pubDate>
            <atom:updated>2022-12-03T15:41:54.628Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Wrangling, Cleaning and Analysis of an online marketplace</h4><figure><img alt="Thumbnail Picture" src="https://cdn-images-1.medium.com/max/1024/0*IZ2VQmSX2NP8_q42" /><figcaption>Photo by <a href="https://unsplash.com/@halacious?utm_source=medium&amp;utm_medium=referral">Hal Gatewood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the past few years marketplaces have been shifted from brick and mortar into digital models. It attracts sellers because they shouldn’t have to rent a space for their store and the buyers can find almost anything from anywhere.</p><p>Analyzing products that are sold in a marketplace is quite challenging. In this story I would like to explore product analysis of a marketplace from these business questions:</p><ol><li>Which product categories are ordered the most?</li><li>How is the revenue that is generated per product?</li><li>How does the product review proportions?</li></ol><p>The dataset that is used <a href="https://www.kaggle.com/datasets/olistbr/brazilian-ecommerce?select=olist_order_reviews_dataset.csv">can be found in Kaggle</a>. The dataset contains multiple CSV files, however, I have turned the table into SQLite format following the data schema on the Kaggle:</p><figure><img alt="Data Schema for the dataset" src="https://cdn-images-1.medium.com/max/1024/0*OrHQWrHcZ5fgR1b2" /><figcaption>Data Schema for the dataset</figcaption></figure><p>The tables and variables we use are based on our objective. Here are tables and variables we use:</p><ol><li><strong>olist_products_dataset </strong>Table<br>This table contains all product categories that are sold by the marketplace.</li><li><strong>olist_order_items_dataset </strong>Table<br>This table contains all the items that are purchased within each order.</li><li><strong>olist_orders_dataset </strong>Table<br>The table contains all of the order information in the marketplace.</li><li><strong>olist_order_review_dataset </strong>Table<br>Contain reviews of the item that has been ordered by customers.</li><li><strong>olist_sellers_dataset </strong>Table<br>The list of sellers that sell products in the marketplace .</li></ol><p>Here are the variable we are interested in:</p><ul><li><strong>order_id</strong>: unique identifier of an order.</li><li><strong>order_item_id</strong>: specify number of items in a single order.</li><li><strong>seller_id</strong>: unique identifier of a seller.</li><li><strong>product_category_name</strong>: Root category of product in Portuguese.</li><li><strong>price</strong>: the price of an item</li><li><strong>review_score</strong>: customer satisfaction score, from 1 to 5 where 1 is the lowest and 5 is the higheset</li></ul><p>There is another table that is not drawn in the Data Schema above, the table is called <strong>product_category_name_translation </strong>which contains the translation of the <strong>product_category_name </strong>— which in portuguese into English.</p><ul><li>Notes: there are plenty of variables on each dataset above. Please visit the dataset information in Kaggle for more detail.</li></ul><h3>Preparation</h3><h4>Libraries, User-Defined Modules and Internal Functions</h4><p>For data analysis we use Python external libraries: Pandas, Matplotlib, and Seaborn. There are also two user-defined modules which we create to store functions and SQL queries, separately.</p><p>The functions module includes 2 functions: open_connection and translate_products. The first function is used to connect to the database, which SQLite:</p><pre>def open_connection(file_path):<br>    connection = None<br>    try:<br>        connection = sqlite3.connect(file_path)<br>        print(&quot;Connection is successful&quot;)<br>        return connection<br>    except Error as e:<br>        print(&quot;Connection failed&quot;)</pre><p>Another module is the sql_query.py module which stores the SQL query. The query wrangles all the tables and variables that are described above. Here is the query:</p><pre>WITH order_information AS (<br>SELECT<br>  order_items.product_id,<br>  order_data.order_id,<br>  reviews.review_id,<br>  order_items.seller_id,<br>  order_items.price,<br>  reviews.review_score<br>FROM olist_order_dataset AS order_data<br>LEFT JOIN olist_order_reviews_dataset AS reviews<br>  ON order_data.order_id = reviews.order_id<br>LEFT JOIN olist_order_items_dataset AS order_items<br>  ON order_data.order_id = order_items.order_id<br>)<br><br>SELECT<br>  order_information.order_id,<br>  sellers.seller_id,<br>  products.product_category_name AS product_name,<br>  order_information.price,<br>  order_information.review_score<br>FROM order_information<br>LEFT JOIN olist_products_dataset AS products <br>  ON order_information.product_id = products.product_id<br>LEFT JOIN olist_sellers_dataset AS sellers<br>  ON order_information.seller_id = sellers.seller_id;</pre><h4>Basic Setup</h4><p>Our analysis is conducted in the jupyter-nootbook where we would import all the External Libraries and the modules:</p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br>import seaborn as sns<br><br>from sql_queries import main_query<br>from common_functions import open_connection</pre><p>There are 3 functions that are needed to ease up data processing. The first one is missing_value_table which is used to get the missing value information and the percentage of the missing value:</p><pre>def missing_value_table(data):<br>    missing_value_count = data.isna().sum()<br>    missing_value_percent = ((data.isna().sum()/data.count())*100).round(3)<br><br>    content = {<br>            &quot;Missing Data&quot;: missing_value_count, <br>            &quot;Percentage (%)&quot;: missing_value_percent<br>        }<br><br>    table = pd.DataFrame(content)<br>    return table</pre><p>The next function is the outliers_table function where we could get the table filled with outliers and we could delete the outliers if needed:</p><pre>def outliers_table(data, col_name, replace=False):<br>    q1 = data[col_name].quantile(.25)<br>    q3 = data[col_name].quantile(.75)<br>    iqr = q3 - q1<br><br>    lower_iqr = data[col_name] &lt; q1 - 1.5*iqr<br>    upper_iqr = data[col_name] &gt; q3 + 1.5*iqr<br><br>    if replace:<br>        new_outliers_value = data[col_name].median()<br>        data.loc[lower_iqr | upper_iqr, col_name] = new_outliers_value<br>        data[lower_iqr | upper_iqr][col_name].head()<br>    else:<br>        outliers = data[lower_iqr | upper_iqr]<br>        return outliers</pre><p>The last function is wrap_labels function. This function allow text wrapping along the x-ticks of the matplotlib graph:</p><pre>import textwrap<br><br><br>def wrap_labels(ax, width, break_long_words=False):<br>    labels = []<br>    for label in ax.get_xticklabels():<br>        text = label.get_text()<br>        labels.append(textwrap.fill(text, width=width,<br>                    break_long_words=break_long_words))<br>    <br>    ax.set_xticklabels(labels, rotation=0)</pre><h4>Importing Table and Get the Basic Info</h4><p>To import the table in SQLite we need to connect to it first and then call the query with Pandas read_sql() method:</p><pre>connection = open_connection(&quot;olist.db&quot;)<br>df_main = pd.read_sql(main_query, connection)</pre><p>Verifying the table and get the basic info:</p><figure><img alt="Basic info and shape of the tables" src="https://cdn-images-1.medium.com/max/1024/1*lS6mbUFcur7YQTg2GlMheg.png" /><figcaption>Basic info and shape of the tables</figcaption></figure><p>As we can see the queried table contains 114092 rows and 5 columns. it still have null values and maybe duplicates. Hence, we need to process the data first before going through the analysis.</p><h3>Data Processing</h3><h4>Finding Missing Value or Null Value</h4><p>To get the picture of the missing value we would call the missing_value function to get the number and percentage of missing values:</p><figure><img alt="Number of missing data and the percetange of the overall dataset" src="https://cdn-images-1.medium.com/max/1024/1*5OCNg9NDs73Q8FT70LxCmg.png" /><figcaption>Number of missing data and the percentange of the overall dataset</figcaption></figure><p>The missing values are not that much, but it still needs to be processed.</p><p>First, we would like to clean the missing value on product_name column, and if we take a look closer of the missing value on the columns:</p><figure><img alt="Missing Value data for product_name column" src="https://cdn-images-1.medium.com/max/1024/1*4ejWV0vr8WyNLyzlFnarYQ.png" /><figcaption>Missing Value data for product_name column</figcaption></figure><p>It appears that the product name contains no value is because there are product categories that have no name within the olist_products_dataset table:</p><figure><img alt="olist_products_dataset table call" src="https://cdn-images-1.medium.com/max/1024/1*ImECW1kkN98AG8uJKCMztg.png" /><figcaption>olist_products_dataset table call</figcaption></figure><p>The solution for this issue is to rename the None value in the queried table with “Unknown”:</p><figure><img alt="Re-checking missing data on the product_name column" src="https://cdn-images-1.medium.com/max/1024/1*l9T8VLYUKzDif3Nt5dif4w.png" /><figcaption>Re-checking missing data on the product_name column</figcaption></figure><p>There are no longer missing values on the product_name column. From the table above we could also see the missing value of the seller_id, price and review_score columns are just around 2% of the total dataset. Hence, we could just drop the data:</p><figure><img alt="Re-checking missing value after dropping it" src="https://cdn-images-1.medium.com/max/1024/1*8bM-vssogldNpA9naQ9cyA.png" /><figcaption>Re-checking missing value after dropping it</figcaption></figure><p>After we drop and call the missing_value function there are no longer missing values in our dataset.</p><h4>Finding Duplicates</h4><p>Here are the information of the duplicates in our dataset:</p><figure><img alt="Duplicates sample on the table" src="https://cdn-images-1.medium.com/max/1024/1*u-bEa6rjSeIUmPpRpSJmCw.png" /><figcaption>Duplicates sample on the table</figcaption></figure><p>There are 794 duplicates in our dataset, we would drop those duplicates but keep the first duplicate values:</p><figure><img alt="Re-checking duplicates" src="https://cdn-images-1.medium.com/max/1024/1*7jWA2HxrnBAxSn4gvQuLeA.png" /><figcaption>Re-checking duplicates</figcaption></figure><h4>Handling Outliers</h4><p>There are two numerical variables in our dataset: price and review_score columns. However, we would only consider the price column to be for outliers because the review_score column is a rank which is closer to ordinal data, hence, we shouldn’t check the outliers within the data.</p><p>To check the outliers, first, we define check the box plot:</p><figure><img alt="Boxplot: Checking outliers" src="https://cdn-images-1.medium.com/max/1024/1*wQoU9xNrqxpvpkxh8ewg9w.png" /><figcaption>Boxplot: Checking outliers</figcaption></figure><p>The data distribution is not looking good, we would check the number of outliers first by using the outliers_table function. The function itself would find the outliers above and below the 1.5*IQR value:</p><figure><img alt="Checking the number of outliers" src="https://cdn-images-1.medium.com/max/1024/1*t8hSkh4q3qrbCFnOOzP_9Q.png" /><figcaption>Checking the number of outliers</figcaption></figure><p>The outliers are 7.5% of our dataset, hence we need to change those values with the median of the price columns. We use the outliers_table function again, this time we add new parameter:</p><figure><img alt="Boxplot: View after outliers are modified" src="https://cdn-images-1.medium.com/max/1024/1*zNVvpDcDcWMYB_0MJS3CCA.png" /><figcaption>Boxplot: View after outliers are modified</figcaption></figure><p>Now we have better data to be analyzed.</p><h4>Data Formatting</h4><p>If we take a look again to our dataset info:</p><figure><img alt="Re-checking table information" src="https://cdn-images-1.medium.com/max/1024/1*qXxt-sI_AF5dGYKIqVMiqw.png" /><figcaption>Re-checking table information</figcaption></figure><p>And if we look at the unique value of review_score and order_items_id column:</p><figure><img alt="Checking unique value of review_score and order_item_id" src="https://cdn-images-1.medium.com/max/1024/1*YpOZbLKyhh_WbROggjDdOQ.png" /><figcaption>Checking unique value of review_score and order_item_id</figcaption></figure><p>These values should be in an integer instead of a float, so we would change the format:</p><figure><img alt="Checking table info after modify the review_score and order_item_id type" src="https://cdn-images-1.medium.com/max/1024/1*Yt6eCBhxVrLNzpSc5sjJ2A.png" /><figcaption>Checking table info after modify the review_score and order_item_id type</figcaption></figure><p>Now if we look at the product_name column:</p><figure><img alt="product_name column data" src="https://cdn-images-1.medium.com/max/1024/1*8rAX9YnYBeQ2Jz7J0vl2CQ.png" /><figcaption>product_name column data</figcaption></figure><p>The product_name column is in Portuguese and also there is “_” in its name. For readability purposes we want to replace it with English and remove the “_” value. And as mentioned above, there is a separate translation table from the data schema that can be used to translate The product_name column.</p><p>First, we get the translation table from the database and turn it into Pandas DataFrame:</p><figure><img alt="Translatation table" src="https://cdn-images-1.medium.com/max/1024/1*FhytewrqQ81z9K6sbR7DUA.png" /><figcaption>Translatation table</figcaption></figure><p>The translated product category (product_name) also contains “_” so we would clear it too. Here is the script to translate and remove the “_” character by using this code:</p><pre># Put each translation column in variable<br>original_product_name = df_translation[&quot;product_category_name&quot;]<br>product_in_english = df_translation[&quot;product_category_name_english&quot;]<br><br># Turn those columns into dictionary<br>translation_map = dict(zip(original_product_name,  product_in_english))<br><br># Removing the &quot;_&quot; characters<br>for key in translation_map:<br>    if &quot;_&quot; in translation_map[key]: <br>        translation_map[key] = &quot; &quot;.join(translation_map[key].split(&quot;_&quot;)).capitalize()<br>    else:<br>        translation_map[key] = translation_map[key].capitalize()<br><br>df_main.replace(translation_map, inplace=True)<br>df_main.head()</pre><p>The result is:</p><figure><img alt="Re-checking the product_name column" src="https://cdn-images-1.medium.com/max/1024/1*tlUIxg-jOq2SDPJKU6Vzmw.png" /><figcaption>The product_name column after translation</figcaption></figure><p>Now the product_name is translated, but we would re-check again:</p><figure><img alt="Re-checking the product_name column" src="https://cdn-images-1.medium.com/max/1024/1*5vOe1NQLVHBvwOv4644UYQ.png" /><figcaption>Re-checking the product_name column</figcaption></figure><p>There are still untranslated and unformatted name. This time the solution is to translate these items manually, then add the translation to the dictionary we’ve created before and replace again:</p><figure><img alt="Final check after translating last 2 unformatted value" src="https://cdn-images-1.medium.com/max/1024/1*cFLyzGAbt7nj0e00TTjDNQ.png" /><figcaption>Final check after translating last 2 unformatted value</figcaption></figure><p>There are no longer untranslated and unformatted product names.</p><p>The last formatting we would do is to format the seller_id columns, this column defines the unique seller identification (i.e name of the sellers) which is unique to each seller, however the data points are long and encoded.</p><p>Since, we need this data in our analysis we would change the nature of the encoding by replacing it with sellers 1, sellers 2, etc:</p><pre>seller_id = df_main[&quot;seller_id&quot;].unique()<br>seller_name = [f&quot;sellers {i}&quot; for i, _ in enumerate(seller_id)]<br><br>new_seller_id = dict(zip(seller_id, seller_name))<br><br>df_main[&quot;seller_id&quot;].replace(new_seller_id, inplace=True)<br>df_main.head()</pre><figure><img alt="The seller_id table after replace the encoding value" src="https://cdn-images-1.medium.com/max/1024/1*ZlhRXH4zaLmHVI-M57_wyg.png" /><figcaption>The seller_id table after replace the encoding value</figcaption></figure><p>Now the encoding and length are changing, we could start with our analysis.</p><h3>Data Analysis — Product Analysis</h3><h4>Case 1 — Analyzing the Product Categories That are Ordered the Most and the Least</h4><p>We need to group our table for this, but first we only need the product_name and order_id tables. Then, we group the table based on the product name and reset the transformation to get more readable table:</p><figure><img alt="Grouping and transforming product_name and order_id columns" src="https://cdn-images-1.medium.com/max/1024/1*TeNz7Ez9HEdtTS0HyAl3XA.png" /><figcaption>Grouping and transforming product_name and order_id columns</figcaption></figure><p>From this we could find the most ordered and least ordered products and visualize the data with bar chart by using Seaborn and Matplotlib:</p><pre># Setup the Matplotlib Axes<br>fig, axes = plt.subplots(ncols=2, nrows=1, figsize=(20, 8))<br><br>for i, _ in enumerate(axes):<br>    if (i == 0):<br>        # set the most ordered products<br>        data = df_ordered_products.sort_values(&quot;order_id&quot;,<br>                                               ascending=False)<br>        bar_title = &quot;Top 10 Most Ordered Products&quot;<br>    elif (i == 1):<br>        data = df_ordered_products.sort_values(&quot;order_id&quot;)<br>        bar_title = &quot;Top 10 Least Ordered Products&quot;<br><br>    sns.barplot(x=&quot;product_name&quot;, y=&quot;order_id&quot;, ax=axes[i],<br>                palette=&quot;YlGnBu_r&quot;, data=data[:10])<br><br>    wrap_labels(axes[i], 10)<br>    axes[i].bar_label(axes[i].containers[0])<br>    axes[i].title.set_text(bar_title)<br>    axes[i].set_xlabel(&quot;\nProduct Category&quot;)<br>    axes[i].set_ylabel(&quot;Number of Ordered Products&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="Bar Chart: Most ordered and least ordered product categories" src="https://cdn-images-1.medium.com/max/1024/1*l-2KZfsdarZb7ekxmYWeAA.png" /><figcaption>Bar Chart: Most ordered and least ordered product categories</figcaption></figure><p>As you can see, the Bed bath table category is the most ordered product with 9790 orders followed by the Health beauty category with 8894 orders. On the other hand the Security and services category only has 2 orders. Fashion children and PC Gamer with 8 orders respectively.</p><p>Let’s take a loot at the descriptive statistics of this data to get better view:</p><figure><img alt="Descriptive statistic of the ordered products" src="https://cdn-images-1.medium.com/max/1024/1*32hXbZ9ZCZ5QvAaHzbTBIQ.png" /><figcaption>Descriptive statistic of the ordered products</figcaption></figure><p>As we can see the mean (1513.149 orders) is almost 5.5 times more than the median(279 orders), and this indicates that the distribution is skewed to the right and highly unequal. Hence, the store might want to incentivize the sellers to sell the product category on the median to boost more revenue to the marketplace.</p><p>Now, we would see which seller sold the most Bed bath table category which is the most ordered product. So, we need new table</p><h4>Case 2 — Analyzing Revenue That is Generated by Products</h4><p>To get the revenue that is generated per products we should calculate the order_items_id column with the price column first, because the price column is the price of each product category whilst the order_items_id is the number of the items in a single order, hence here is the calculation`:</p><figure><img alt="Calculating Revenue per products" src="https://cdn-images-1.medium.com/max/1024/1*0pDGMwOD6aSS-w-1xr_oHw.png" /><figcaption>Calculating Revenue per products</figcaption></figure><p>Next we would only take the new revenue column with the product_name column to show the top 10 product categories that generate more revenue.</p><figure><img alt="Grouping and Transforming the product_name and revenue column" src="https://cdn-images-1.medium.com/max/1024/1*K5_tE01ko7I1kks3K7IB1Q.png" /><figcaption>Grouping and Transforming the product_name and revenue column</figcaption></figure><p>We will show the table above with a bar chart. Below is the code to create the bar chart and followed by the result:</p><pre># Create chart<br>plt.figure(figsize=(12, 8))<br><br>ax = sns.barplot(x=&quot;product_name&quot;, <br>                 y=&quot;revenue&quot;,<br>                 palette=&quot;YlGnBu_r&quot;,<br>                 data=df_revenue_analysis[:10],<br>                 order=df_revenue_analysis[:10]<br>                       .sort_values(&quot;revenue&quot;, <br>                                     ascending=False).product_name)  <br># Adding data label into the graph<br>wrap_labels(ax, 10)<br><br># Adding table name and axes labels<br>plt.bar_label(ax.containers[0], fmt=&quot;%.f&quot;)<br>plt.title(&quot;Revenue per Product Category&quot;)<br>plt.xlabel(&quot;Product Category&quot;)<br>plt.ylabel(&quot;Revenue (in Millions)&quot;)<br>plt.show()</pre><figure><img alt="Bar Chart: Revenue Per Product" src="https://cdn-images-1.medium.com/max/1024/1*_5wYBn4n0sq4HoA0E4NYBA.png" /><figcaption>Bar Chart: Revenue Per Product</figcaption></figure><p>From the bar chart above the bed bath table generates more revenue with 1,136,203 Millions, almost 1.5 higher than the 2nd category which at 400,953 Thousand, and the product is auto. This value makes sense because the Bed bath table category is the most ordered product also. However, the other categories’ revenue is also far below the highest revenue.</p><p>Also if we compare the above table with the top 10 most ordered products, only Bed bath table and Auto categories are within the top 10 revenue per product table.</p><p>Now let’s take a look at the descriptive statistic below:</p><figure><img alt="Descriptive statistics for the revenue" src="https://cdn-images-1.medium.com/max/1024/1*v7kHivoHwAiWEv5Rh2Wxsg.png" /><figcaption>Descriptive statistics for the revenue</figcaption></figure><p>The median (27,793) and mean (146,139.74) are too far, hence, the revenue per product category is imbalance. To boost revenue the marketplace could be transformed to be a marketplace focusing on Bed bath table categories only.</p><h4>Case 3 — Analyzing the Ordered Product Reviews</h4><p>The columns that are needed: product and the review_score. We would count the product based on its review score and find the percentage, then shows it in a bar chart:</p><figure><img alt="Grouping and Transforming the review_score and product_name" src="https://cdn-images-1.medium.com/max/1024/1*oiKzcX4BHjRuIcS-RcdyFw.png" /><figcaption>Grouping and Transforming the review_score and product_name</figcaption></figure><p>The we write python code the create the bar chart to show the</p><pre># colors<br>colors = [&#39;#F1AE89&#39;, &#39;#FFDFBa&#39;, &#39;#A8D3DA&#39;, <br>          &#39;#CBE2B0&#39;, &#39;#F29191&#39;]<br><br># Separator<br>explode = (0.02, 0.02, 0.02, 0.02, 0.02)<br><br>fig, ax = plt.subplots(figsize=(8, 8))<br><br>ax.pie(df_review_proportion[&quot;percentages&quot;],<br>       labels=df_review_proportion[&quot;review_score&quot;],<br>       colors=colors, autopct=&quot;%.2f%%&quot;,<br>       pctdistance=0.85, explode=explode)<br><br>center_circle = plt.Circle((0, 0), 0.70, fc=&quot;white&quot;)<br>fig = plt.gcf()<br><br>fig.gca().add_artist(center_circle)<br><br>plt.title(&quot;Proportion of Product Category Review Score&quot;)<br>plt.legend(df_review_proportion[&quot;review_score&quot;],<br>            loc=&quot;upper left&quot;, title=&quot;Review Score&quot;)<br>plt.show()</pre><figure><img alt="Donut Chart: Proportion of Ordered Product Category Review Score" src="https://cdn-images-1.medium.com/max/662/1*e6Gz66Hi77OTQHaxVgLzrQ.png" /><figcaption>Donut Chart: Proportion of Ordered Product Category Review Score</figcaption></figure><p>The 56.48% of product categories are rated with the highest score, which is 5, and it is almost 4.5 higher than the lowest score (12.67%), which is 1. The proportion of the other scores (4, 3, and 2) are also far lower than the highest score proportion. This indicates that all of the products within categories are well liked by the customers.</p><p>Now let’s take a look at which product categories that are getting the highest and lowest review score. To do this we need a new table:</p><figure><img alt="Grouping and transforming product_name, review_score and order_id column" src="https://cdn-images-1.medium.com/max/1024/1*tXyud10Hpx-cCIWfu-dlUQ.png" /><figcaption>Grouping and transforming product_name, review_score and order_id column</figcaption></figure><p>We will show the data above in a bar chart with seaborn and matplotlib, here is the python code and the bar chart:</p><pre>fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(18, 6))<br><br>for i, _ in enumerate(axes):<br>    if i == 0:<br>        high_score = df_product_review[&quot;review_score&quot;] == 5<br>        data = df_product_review[high_score][:10]<br>        data.sort_values(&quot;order_id&quot;, ascending=False, inplace=True)<br>        bar_title = &quot;Top 10 Products with the Highest Review Score&quot;<br>    elif i == 1:<br>        low_score = df_product_review[&quot;review_score&quot;] == 1<br>        data = df_product_review[low_score][:10]<br>        data.sort_values(&quot;order_id&quot;, ascending=False, inplace=True)<br>        bar_title = &quot;Top 10 Products with the Lowest Review Score&quot;<br><br>    bar_plot = sns.barplot(x=&quot;product_name&quot;, y=&quot;order_id&quot;,ax=axes[i],<br>                            palette=&quot;YlGnBu_r&quot;,data=data)<br><br>    wrap_labels(axes[i], 10)<br>    axes[i].bar_label(axes[i].containers[0])<br>    axes[i].title.set_text(bar_title)<br>    axes[i].set_xlabel(&quot;\nProdut Category Name&quot;)<br>    axes[i].set_ylabel(&quot;Number of Product Categories&quot;)<br><br>plt.tight_layout()</pre><figure><img alt="Bar Chart: Product Category on The Best and Worst review score" src="https://cdn-images-1.medium.com/max/1024/1*zL9Ds3Hfboa2La51CzgOLQ.png" /><figcaption>Bar Chart: Product Category on The Best and Worst review score</figcaption></figure><p>The results are similar (zoom in for more detail), the Bed bath table, Auto and Baby categories are the products with highest and lowest review at the same time. This makes sense because those products are within the most ordered products.</p><h3>Conclusion</h3><p>The dataset itself still contains missing values and duplications, hence we need to validate the data and clean it if necessary before making the analysis.</p><ol><li>The proportion of review score suggests that the overall product categories in the marketplace are well liked. 56.48% of ordered products get 5 review scores, which is the highest.</li><li>The Bed bath table category is the most ordered product with 9790 orders followed by the Health beauty category with 8894 orders. However the Health beauty category doesn’t appear on the top 10 Revenue by product category.</li><li>The distribution of the ordered product categories are imbalanced, which can be seen due to the orders median being 5.5 lower than the mean, this might cause revenue issues for the marketplace. Hence, incentives sellers to sell product categories within the median range is suggested.</li><li>Bed bath table category generates the most revenue with 1,136,203 Millions, almost 1.5 higher than the 2nd category which at 400.953 Thousand, and the product is auto.</li><li>The median (27,793) and mean (146,139.74) are too far, hence, the revenue per product category is imbalance. To boost revenue the marketplace could be transformed to be a marketplace focusing on Bed bath table categories only.</li></ol><p>For the complete notebook file, please visit my <a href="https://github.com/aifakhri/pacmann-sql-and-data-wrangling">github repo</a>.</p><p>Thank you for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=235af14e2c5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL and Python for Data Analysis]]></title>
            <link>https://medium.com/@aifakhri/sql-and-python-for-data-analysis-605f255125e?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/605f255125e</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 02:12:32 GMT</pubDate>
            <atom:updated>2022-11-08T02:12:32.030Z</atom:updated>
            <content:encoded><![CDATA[<h4>Analyzing a fake DVD rental database with Python and SQLite</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L7ddb03H35JtsnCz" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For data analyst mastery SQL is a must, although I think when we start to learn programming whether for data analytics or automation SQL is essential.</p><p>Anyway, Here I would like to do a little of bit data analysis using SQLite and Python. I won’t use any ORM library from Python such as SQLAlchemy, instead I use a basic query to the database.</p><h3>Dataset and Objectives</h3><p>The dataset that we use is coming from <a href="https://www.kaggle.com/datasets/atanaskanev/sqlite-sakila-sample-database">kaggle</a>. This dataset is about a fictional DVD rental store where they have a list of movies, customers, stores, inventory, rental, payment method, etc.</p><p>The table relation of the database can be looked at this ERD diagram:</p><figure><img alt="ERD Diagram for the database." src="https://cdn-images-1.medium.com/max/1024/1*mF_02Prr7p6QBjerXB3jwQ.png" /><figcaption>ERD Diagram for the database.</figcaption></figure><p>In our analysis we would not use all the table because our objective is to see these cases:</p><ol><li>Which movies are rented the most?</li><li>How much revenue is generated by each film?</li><li>Which users are renting the most?</li></ol><p>Hence, if we look at the ERD diagram we could use only these tables:</p><ol><li>Film<br>Consists of the list of movies that is owned by the store. It also contains important information: rental rate, rental duration and replacement cost tables, which can be used to determine the cost of the rent.</li><li>Inventory<br>This table is an joining table or junction table that connects film, rental, and store tables. This table is there because film, rental and store tables have many-to-many relationship.</li><li>Rental<br>The rental table records the rental that is made by each user. such as return date of the DVD and which staff handle the rental.</li><li>Payment<br>This table records payment that is made by each user. The table contains information such as the payment date of the customer and the amount that is paid by the customer</li><li>Customer<br>This table records the customer information such as their names, e-mail address, address, etc.</li></ol><p>The process of our work is to query the necessary data from the database by creating SQL query, then process and analyze by using Python.</p><h3>Connecting to the Database</h3><p>Before we start to call SQL query from Python code, we need to create connection to the database from Python. By using Python’s sqlite3, which is a built-in library, we could create a connection to the database. Here, is the function we could use to connect to the database:</p><pre>import sqlite3<br>from sqlite3 import Error</pre><pre>def create_connection(path):<br>    connection = None<br>    try:<br>        connection = sqlite3.connect(path, timeout=20)<br>        print(&quot;Connection to SQLite is successful&quot;)<br>    except Error as e:<br>        print(f&quot;The error &#39;{e}&#39; occured&quot;)<br>    <br>    return connection</pre><p>In this project, this function is stored on different file so it can be reused for different analysis on different SQL query. This query is stored in thesql_function.py file.</p><h3>Python Libraries</h3><p>For data analysis we use Python external libraries:</p><pre>pandas=1.4.2<br>seaborn=0.11.2<br>matplotlib=3.5.2</pre><p>Pandas is used for manipulating the table we queried, whilst Seaborn and Matplotlib are used to visualize our analysis. We use Jupyter-notebook to run the test. Hence, to make the notebook clean look and easy to read, the SQL query is stored in a different file, which is sql_query.py file.</p><h3>Analyzing Revenue and Most Favorite Movies</h3><p>From our use case this is the use case 1 and 2, respectively. We write this in the single section because the query for this analysis can be written in a single query:</p><pre>rented_film_and_revenue = &quot;&quot;&quot;<br>WITH rented_film as (<br>SELECT<br>    rental.rental_id,<br>    film.film_id,<br>    film.title,<br>    film.rental_rate,<br>    film.replacement_cost<br>    FROM inventory<br>    JOIN film ON inventory.film_id = film.film_id<br>    JOIN rental ON inventory.inventory_id = rental.inventory_id<br>)</pre><pre>SELECT<br>    rented_film.title,<br>    count(rented_film.title) as n_film,<br>    sum(payment.amount) as revenue_by_film<br>FROM payment<br>JOIN rented_film USING(rental_id)<br>GROUP BY rented_film.title<br>&quot;&quot;&quot;</pre><p>From the query above, first we join the film and rental table through the inventory table into a CTE (Common Table Expression) to store the joined table. Then we join the CTE table with the payment table and count all the rented film also sum the payment amount that is made by users. Then we group these columns by the movie titles to get a calculation for each movie.</p><p>Here is the result of our query in the notebook:</p><figure><img alt="Calling SQL query in the jupyter notebook" src="https://cdn-images-1.medium.com/max/1024/1*g8LyPse-BJkuqIgIgzAlwg.png" /><figcaption>Calling SQL query in the jupyter notebook</figcaption></figure><p>From this table we could start our analysis:</p><h4>Analyzing the most rented film</h4><p>From the table above we could easily find the top 10 film that is rented with the following code:</p><figure><img alt="Python code to show top 10 most rented film" src="https://cdn-images-1.medium.com/max/1024/1*2Td-BDJIeMpjLGVTTpIN8A.png" /><figcaption>Python code to show top 10 most rented film</figcaption></figure><p>We could visualize the data above with simple a barchart using seaborn and matplotlib. Here is the code and result:</p><figure><img alt="Python code to create barchart to show top 10 rented movies" src="https://cdn-images-1.medium.com/max/1024/1*MFxmAUWHMidCpX69f5QIUQ.png" /><figcaption>Python code to create barchart to show top 10 rented movies</figcaption></figure><figure><img alt="Barchart: Top 10 most rented movies" src="https://cdn-images-1.medium.com/max/1024/1*HmzgIIUBYyRZ-OPPBjRIFA.png" /><figcaption>Barchart: Top 10 most rented movies</figcaption></figure><p>From the result above Bucket Brotherhood is the most rented film in this DVD store.</p><h4>Analyzing Revenue per Film</h4><p>Our second analysis is to see the revenue that is generated by each film. The SQL query we use the same as before, hence, we could directly modify the table to show top 10 film that generate the most revenue:</p><figure><img alt="Python code to get top 10 film with most revenue" src="https://cdn-images-1.medium.com/max/1024/1*9oV0nJP2vPUwGegPQwk1-w.png" /><figcaption>Python code to get top 10 film with most revenue</figcaption></figure><p>With barplot we could visualize the table above:</p><figure><img alt="Python code to create barchart to show top 10 film with most revenue" src="https://cdn-images-1.medium.com/max/1024/1*N169n_e2vMpfFEWeZgcfXQ.png" /><figcaption>Python code to create barchart to show top 10 film with most revenue</figcaption></figure><figure><img alt="Barplot: Top 10 film with most profit" src="https://cdn-images-1.medium.com/max/1024/1*DKxyGUQQNxKda-ZhzqeePA.png" /><figcaption>Barplot: Top 10 film with most revenue</figcaption></figure><p>Telegraph Voyage is the movie that generates the most revenue for the store with a total of USD 231.73.</p><p>If we take a bit closer look at both analysis, we could see that the list of the most rented films with the most revenue are different, which is weird and seemingly doesn’t make any sense. However, this is make sense because if we take a look at the film table in the database we could see columns describing rental rate and replacement cost:</p><figure><img alt="Query from film table for rental rate and replacement cost column" src="https://cdn-images-1.medium.com/max/1024/1*oK5ldWHHyuH_2N3NpoBDnQ.png" /><figcaption>Query from film table for rental rate and replacement cost column</figcaption></figure><p>As we can see, each movie has a different rental rate, and also there is a replacement cost, which will be charged to each user that returns the film late. Hence, the most rented films doesn’t have to be the one that generates more revenue.</p><h3>Analyzing Favorite Customer</h3><p>Here we are going to analyze which user has been renting the most films in the store. We have similar query as before, however, now we would join our slightly bit CTE with customer table:</p><pre>rented_film_by_customer = &quot;&quot;&quot;</pre><pre>WITH rented_film as (</pre><pre>SELECT<br>    rental.customer_id,<br>    film.film_id,<br>    film.title,<br>    film.rental_rate<br>FROM inventory<br>JOIN film ON inventory.film_id = film.film_id<br>JOIN rental ON inventory.inventory_id = rental.inventory_id<br>)</pre><pre>SELECT<br>    customer.first_name,<br>    customer.last_name,<br>    count(rented_film.title) as n_film<br>FROM customer<br>LEFT JOIN rented_film ON customer.customer_id=rented_film.customer_id<br>GROUP BY customer.first_name, customer.last_name;<br>&quot;&quot;&quot;</pre><p>This time in our CTE, we use customer_id field which later be used to join the CTE with the customer table. Also, we would like to get the customer’s first name and last name to make sure there is no duplicate when we aggregate our data later.</p><p>Here is the result of our query:</p><figure><img alt="Result of the SQL query above" src="https://cdn-images-1.medium.com/max/1024/1*Nvygk04HLyZeYWR8HmqorA.png" /><figcaption>Result of the SQL query above</figcaption></figure><p>From the table above, we could manipulate the data to find which customer rented the most film:</p><figure><img alt="Python code to find top 10 customer that rented the most" src="https://cdn-images-1.medium.com/max/1024/1*SdCnBW8hW5j_dR2eZTfRRA.png" /><figcaption>Python code to find top 10 customer that rented the most</figcaption></figure><p>The visualization is using barchart again. One thing to note before we draw the barchart is we need to get the full name of each top 10 customer because it would make our visualization easy to read. Here is the code and the result:</p><figure><img alt="Python code to build barchart for visualize top 10 customer with most rent" src="https://cdn-images-1.medium.com/max/1024/1*8z6fZGKPxoZHU8bIaTQtwg.png" /><figcaption>Python code to build barchart for visualize top 10 customer with most rent</figcaption></figure><figure><img alt="Barchart: Top 10 Customer with Most Rent" src="https://cdn-images-1.medium.com/max/1024/1*eYGrRemPh7DyrY6ibuSkGw.png" /><figcaption>Barchart: Top 10 Customer with Most Rent</figcaption></figure><p>From the graph above, Eleanor Hunt is the customer that has rented the most films with a total of 46.</p><h3>Conclusion</h3><p>Our analysis above is pretty simple, the graphs that we show are not the complex ones. Nevertheless, the analysis above shows that by using Python we could make our SQL query come to life through a graph. Also we could manipulate the data from SQL much better with Python.</p><p>The code for this analysis is available in <a href="https://github.com/aifakhri/simple-sql-for-data-analysis">my github</a>. It contains not only the code for this analysis but I also add data validation too, feel free to check out the whole code. As for the database, again, it is from <a href="https://www.kaggle.com/datasets/atanaskanev/sqlite-sakila-sample-database">kaggle</a> and it is free to download.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=605f255125e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Approach to Solve Probability and Statistical Problems with Python (Part 2)]]></title>
            <link>https://medium.com/@aifakhri/a-practical-approach-to-solve-probability-and-statistical-problems-with-python-part-2-1389227a3a66?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1389227a3a66</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[statsmodels]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Thu, 03 Nov 2022 11:56:29 GMT</pubDate>
            <atom:updated>2022-11-03T11:58:21.843Z</atom:updated>
            <content:encoded><![CDATA[<h4>Finding relationship between variables in the dataset and conducting statistical hypothesis testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aTpKpGbSKVQfeUzW" /><figcaption>Photo by <a href="https://unsplash.com/@saadahmad_umn?utm_source=medium&amp;utm_medium=referral">Saad Ahmad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the previous story we have solved some probability and statistical problems with Python:</p><p><a href="https://medium.com/@zeitdeuter/a-practical-approach-to-solve-probability-and-statistical-problems-with-python-part-1-755c8a12f916">A Practical Approach to Solve Probability and Statistical Problems with Python (Part 1)</a></p><p>Now, we still use Python and the problem we want to solve is finding the correlation coefficient and also doing some hypothesis testing.</p><p>Here is the summary of the dataset we use:</p><ul><li><strong>age:</strong> The age of the insured.</li><li><strong>sex: </strong>The sex (gender) of the insured. The values are male and female only.</li><li><strong>bmi:</strong> Body Mass Index of the insured.</li><li><strong>children:</strong> Number of children the insured has.</li><li><strong>smoker:</strong> Information whether the insured is a smoker or not. The value is “yes” for smoker and “no” for non-smoker</li><li><strong>region:</strong> The region of which the insured resides.</li><li><strong>charges</strong>: The insurance charges in USD for the insured.</li></ul><h3>Correlation Coefficient</h3><p>Correlation coefficient is a numerical measurement to describe the meaning of a relationship between variables. It also defines whether the relationship between two variables is having strong or weak or no correlation. Also, the coefficient would tell us whether two variables correlate negatively or positively.</p><p>Theoretically, correlation coefficient can be found with the following equation:</p><figure><img alt="Correlation coefficient calculation" src="https://cdn-images-1.medium.com/max/515/1*pnYd3nHp3kvvnZWhd1WlJg.png" /><figcaption>Correlation coefficient calculation</figcaption></figure><p>That’s a bit of a complex equation, but with Python and Pandas we could just used corr() method to directly calculate the correlation between all variables in our dataset.</p><p>However, one thing to note, there is an object or string datatype within our dataset, these data cannot be used to calculate correlation coefficient. Hence, we need to transform the data first into numerical value.</p><h4>Transforming Categorical Data into Numerical Data</h4><p>Transforming categorical data into numerical is simply by coding the category into numbers. For example, the sex data values are “male” or “female” we could code the “0&quot; for male and “1” for female.</p><p>We could apply this concept into other data categorical datatype. Here is what I do for all categorical data in our dataset:</p><ol><li>Sex variable: male is 0 and female is1</li><li>Smoker variable: “no” is 0 and “yes” is 1</li><li>Region variable: southwest is 0, southeast is 1, northwest is 2, northeast is 3</li></ol><p>To transform this data with python we could use the following code:</p><figure><img alt="Dataset before the smoker column is transformed" src="https://cdn-images-1.medium.com/max/1024/1*-V0VpQMxnZy07_Q3AtahBQ.png" /><figcaption>Dataset before the smoker column is transformed</figcaption></figure><figure><img alt="Dataset after the smoker column is transformed" src="https://cdn-images-1.medium.com/max/1024/1*hDajriMBwS5ij7kfm_gfbA.png" /><figcaption>Dataset after the smoker column is transformed</figcaption></figure><p>As we can see the transformation of the smoker column is done by the map() method from pandas. We could apply the syntax above to the other category as we defined before. Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4ouSyy9zeCdSZhVDjrNxw.png" /></figure><p>From this result we could use corr() method from Pandas to find the correlation table as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_A4FCBrGHcRUEh7zSgUL6Q.png" /><figcaption>Correlation coefficient between variable</figcaption></figure><p>The result looks fine, but it is quite challenging to find which variable correlates strongly or weakly. Hence, we could use additional help from heatmap charts to get a better view. The heatmap chart can be drawn with seaborn with the following code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GAfV8dSjBkMw3Tg-VjoHQ.png" /></figure><p>From the heatmap we could see the strongest relationship is from charges and smoker variables with the value of correlation coefficient of 0.79 because . The value also indicates that the relationship correlates in positive manners.</p><p>Also, the weakest relationship is between region and age because the correlation coefficient between both variables are -0.0021 which is close to 0.</p><h3>Statistical Testing</h3><p>In statistics, <a href="https://www.britannica.com/science/statistics/Hypothesis-testing">statistical testing or hypothesis testing</a> is a form of statistical inference that uses data from a sample to draw conclusions about a population parameter or a population probability distribution. We use statistical testing to check whether a sample of data is sufficient to support or reject a particular hypothesis.</p><p>There are several steps to do hypothesis testing, here are the steps:</p><p><strong>Step 1 — Define the Null Hypothesis</strong><br>Null hypothesis or often defined as Ho is the initial claim that we want to test. For example: “A claim whether the insurance charges for the smoker is greater than the non-smoker”.</p><p><strong>Step 2 — Define the Alternate Hypothesis</strong><br>Alternate hypothesis or Ha is our hypothesis to challenge the null hypothesis or the initial claim. For example, if we refer to the null hypothesis we’ve defined before, our alternate hypothesis would be: the insurance charges for smokers are less than for non-smokers.</p><p><strong>Step 3 — Define the decision rule</strong><br>At this step we define rules that we want to use for the statistical test and decision making (conclusion inference). These rules are the level of significance and the type of tailed testing.</p><p>T<a href="https://en.wikipedia.org/wiki/Statistical_significance">he significance level or α</a> is the probability of the study rejecting the null hypothesis, given that the null hypothesis is true. The best practice value for the significance level, which is 5% or 0,05. This value would be used throughout this article.</p><p>There are 3 types of <a href="https://www.statisticshowto.com/probability-and-statistics/hypothesis-testing/how-to-decide-if-a-hypothesis-test-is-a-left-tailed-test-or-a-right-tailed-test/#:~:text=What%20is%20a%20Right%20Tailed,inequality%20points%20to%20the%20right.">tailed testing</a>: right-tailed, left-tailed and two-tailed test. The selection of the test is based on our alternate hypothesis testing.</p><ul><li><strong>Right-tailed test:</strong> the alternative hypothesis contains greater than operator.</li><li><strong>Left-tailed test: </strong>the alternative hypothesis contains less than operator.</li><li><strong>Two-tailed test:</strong> the alternative hypothesis contains equal or not equal operators.</li></ul><p><strong>Step 4 — Define and calculate the statistics test method</strong><br>There are some statistical methods we could use, each method is based on what kind of testing we want to test, such as: proportion, mean, standard deviation, etc. The result of this test can be p-value or critical value. These values then would be compared with the significance level value to get the conclusion in our test.</p><p><strong>Step 5 — Conclusion Inference </strong><br>The conclusion of our hypothesis testing is based on the p-value and the significant level. The decision is based on this rule:</p><ul><li>if the p-value is greater than the level of significance value the we should reject the claim or the null hypothesis</li><li>If the p-value is less than the level of significance value we shouldn’t reject the claim or null hypothesis.</li></ul><p>These steps are required steps when we do hypothesis testing manually or with Python. However, Python shines the best when we run step 4, because the equation to get p-value is complicated. Here is the example of one of the statistic test method, which is z-statistic, equation:</p><figure><img alt="Z-Statistic Equation" src="https://cdn-images-1.medium.com/max/485/1*MANzPSjKJmXjPCfo1Mb0wg.png" /><figcaption>Z-Statistic Equation</figcaption></figure><p>Python would help us to calculate this in a single line. The Python library that we use is <a href="https://www.statsmodels.org/stable/index.html">Statsmodel</a>, which has all the statistical testing methods that we could use.</p><p>Also, we need to remember that in hypothesis testing the data we use is a sample of population. Hence, we need to sample our dataset. To do that we use Panda’s sample() method to select a random sample in our dataset.</p><h4>Problem — The insurance charges of smoker is higher than non-smoker</h4><p><strong>Step 1 and 2 — Null hypothesis and alternate hypothesis</strong><br>The null hypothesis is the claim in our problem: “The insurance charges of a smoker is higher than a non-smoker.” Hence, our alternate hypothesis is: The insurance charges of a smoker is less than a non-smoker.” Mathematically, we could write the null and alternate hypothesis as:</p><figure><img alt="Null and alternate hypothesis" src="https://cdn-images-1.medium.com/max/562/1*ar2sfYeyjb8iDYgE6I9yOg.png" /><figcaption>Null and alternate hypothesis</figcaption></figure><p><strong>Step 3 — Define Decision Rule</strong><br>As mentioned, we would use the most common value for the level of significance, which is 0.05, also since the alternate hypothesis contains less than statement we would use left-tailed testing.</p><p><strong>Step 4 — Statistical testing method</strong><br>In this problem we want to test an average, hence, the most suited statistical test method is t-test. With <a href="https://www.statsmodels.org/stable/index.html">Statsmodels</a>, the t-test method is coming from the stats module: weightstats.test_ind() . The return value of this method is a tuple of t-statistic and p-value. The arguments that are needed:</p><ul><li><strong>x</strong>: array of the first sample. <br>In our case: the sample dataset of insurance charges for a smoker.</li><li><strong>y: </strong>array of the second sample. <br>In our case: the sample dataset of insurance charges for a non-smoker.</li><li><strong>alternative: </strong>the type of statistical testing.<strong> <br></strong>In this problem: left-tail, and by the Statsmodels, left-tail test is defined as “smaller”.</li><li><strong>usevar:</strong> select whether the calculation is using pooled or unequal<br>Pooled is used when the standard deviation is equal between two samples, whilst unequal is otherwise. Hence we need to compare the standard deviation value of the two samples.</li></ul><p>The number of samples we select is 10% of our dataset. So, with this information we could calculate the t-test with the following code:</p><figure><img alt="Calculation of t-statistic value with Python" src="https://cdn-images-1.medium.com/max/1024/1*s52fTjkuU_mVsIFK0nW2og.png" /><figcaption>Calculation of t-statistic value with Python</figcaption></figure><p>From the code above our p-value is 0.999.</p><p><strong>Step 5 — Conclusion Inference</strong><br>From step 4 the p-value is 0.999 while from step 3 the level of significance is 0.05. These values indicate that p-value is greater than the level of significance, hence, we should not reject the claim or the null hypothesis.</p><h3>Conclusion</h3><p>Again, by using Python we ease up the problem solving process of statistical problems. From the problem in the correlation coefficient we could draw a chart that express the coefficient correlation table better than a. Moreover, the chart ease up our decision making process too by its coloring.</p><p>Also, from the hypothesis testing we could make a quick calculation with Python while maintaining the hypothesis testing steps.</p><p>Here is the end of the series for using Python to solve probability and statistical problems. <a href="https://github.com/aifakhri/statistical-problem-with-python">You can find the notebook here.</a> Be warned that some details are different than you find in our series, but the essence of the code is still the same. Also, I add more code for another statistical test calculation.</p><p>Thank you for reading, I hope you enjoyed my writing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1389227a3a66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Meat Consumption Trends in Indonesia and its Regencies]]></title>
            <link>https://medium.com/@aifakhri/meat-consumption-in-indonesia-and-its-regencies-e436c2638546?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e436c2638546</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Thu, 03 Nov 2022 11:45:47 GMT</pubDate>
            <atom:updated>2023-07-19T05:30:26.513Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dive deep into Indonesian meat consumption trends and their impact on the GDP at the regency level.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YUzvaRJlN-k_o_BG" /><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><p><a href="https://ourworldindata.org/meat-production#meat-consumption-tends-to-rise-as-we-get-richer">Our World in Data</a> website suggests that as the world gets richer meat consumption is also increased. This seems true when it comes to the City I live in Jakarta, Indonesia. Meat enthusiasts seem to be growing in Jakarta and it can be shown by the increase in the number of all-you-can-eat meat buffet restaurants and also affordable frozen meat that is sold online.</p><p>However, I won’t scrutinize the impact of the all-you-can-eat buffet or the online frozen meat business on meat consumption. Although, it sounds like a good idea, maybe for later. Anyway, What I would like to understand is something more trivial that always comes to my mind when I eat meat or pass through the all-you-can-eat buffet: how does meat consumption around Indonesia?</p><p>So, in order to answer my question above and to better understand meat consumption in Indonesia, I am going to explore the meat consumption data in Indonesia. I would like to see answer the following questions:</p><ol><li>What is the meat consumption trend in Indonesia?</li><li>What types of meat do people eat in Indonesia and in its respective regency?</li><li>Does a regency with high GDP at the regency level or PDRB also consume a high volume of meat?</li></ol><p>The dataset for meat consumption data and PDRB are coming from Indonesia’s National Bureau of Statistics (BPS). The data is from 2017–2021, which is kind of great because we could also see whether the Covid-19 pandemic affects meat consumption.</p><h4>Dataset Description</h4><p>The dimension of our dataset is 2057 rows and 9 columns. The datasets for average meat consumption per capita in one week and PDRB are coming in separate files. Hence, I did combine the data before the analysis. Also, I did aggregate some such as type of meat because BPS data provides various kinds of meat which, in a way, could be grouped into a single type of meat. Herewith is the <a href="https://docs.google.com/spreadsheets/d/1GGoTXiFOxV1-Zw1LXeO6L00RQm1gUSMNWjZKi2iOu0o/edit?usp=sharing">link to the dataset</a> and below is the description of the variable in the dataset:</p><ul><li><strong>Regency: </strong>Name of regency in Indonesia.</li><li><strong>Year: </strong>The year the data is recorded by BPS.</li><li><strong>PDRB: </strong>The GDP of each regency in Indonesia.</li><li><strong>Beef:</strong> The average beef (cattle meat) consumption per week per capita in kilogram (kg).</li><li><strong>Goat: </strong>The average goat meat consumption per week per capita in kilogram (kg).</li><li><strong>Pigmeat: </strong>The average pig-meat consumption per week per capita in kilogram (kg).</li><li><strong>Chicken: </strong>The average chicken meat consumption per week per capita in kilogram (kg).</li><li><strong>Others: </strong>The average of other types of meat consumption (frozen meat, sausage, beef or chicken innards, etc.) per week per capita in kilogram (kg).</li><li><strong>Total: </strong>The total meat consumption per week per capita in kilogram (kg).</li></ul><p>*Note: We won’t do data cleaning for this exploration.</p><h3>The trend of Meat Consumption in Indonesia and its Regencies from 2018–2021</h3><p>We want to understand the year-by-year average meat consumption in Indonesia along with the proportion of the type of meat that is consumed by Indonesians in total. We could use a stack area chart to find both trends of meat consumption in Indonesia:</p><figure><img alt="Stacked Line Plot: Total of Average Meat Consumption in Indonesia (year-by-year)" src="https://cdn-images-1.medium.com/max/1024/1*ricFRkT3vHaEJxqFA1miWg.png" /><figcaption>Stacked Line Plot: Total Average Meat Consumption in Indonesia (year-by-year)</figcaption></figure><p>From the figure above, the most consumed meat within a household in Indonesia per capita in one week is Chicken. The average consumption of chicken is always increased year by year with the increment of 2.1 Kg, 2,97 Kg, and 4,79 Kg respectively from 2018 to 2021.</p><p>There is peculiar data on goat meat consumption from 2018 to 2019. The average consumption data declines dramatically from 19.83 Kg to 0.18 Kg, then it increases again by a small fraction. I am afraid this is caused by too many empty data on the dataset.</p><p>Another thing to notice is that during the Covid-19 year (2020–2021), the average meat consumption per capita was still increasing despite the lockdown in each regency in Indonesia during the Covid-19 year.</p><h4>Overall average meat consumption in each Regency</h4><p>Another trend we could find from our data is the top 10 regency that consumes the most meat (on average) per capita in one week.</p><figure><img alt="Bar Chart: Top 10 Regency That Consumes Most Meat (all types) on Average per Capita in One Week from 2018 to 2021" src="https://cdn-images-1.medium.com/max/1024/1*jvcGnvxgl4__J-E4M28GHw.png" /><figcaption>Bar Chart: Top 10 Regency That Consumes Most Meat (all types) on Average per Capita in One Week from 2018 to 2021</figcaption></figure><p>The results show that the Puncak regency consumed 3.919 Kg on average in one week from 2018 to 2021. Also, we could find that the next 4 regencies — which are Intan Jaya, Dogiyai, Deiyai, and Boven Digoel — that consumes the most meat are from Provinces in Papua Island.</p><h3><strong>Meat Consumption by Type of Meat</strong></h3><p>Next, we want to understand the total meat consumption in each regency from 2018 to 2021 based on the meat type, so we could understand the consumption types of Indonesian. I would pick the top 10 regency that consumes the most meat based on the type of meat.</p><h4>Chicken Meat Consumption</h4><figure><img alt="Bar Chart: Top 10 Regency That Consumes Most Chicken on Average per Capita in One Week from 2018 to 2021" src="https://cdn-images-1.medium.com/max/1024/1*rahh62oAG4LXPZuX90lmng.png" /><figcaption>Bar Chart: Top 10 Regency That Consumes Most Chicken on Average per Capita in One Week from 2018 to 2021</figcaption></figure><h4>Beef Consumption</h4><figure><img alt="Bar Chart: Top 10 Regency That Consumes Beef on Average per Capita in One Week from 2018 to 2021" src="https://cdn-images-1.medium.com/max/1024/1*hgy_kuE1Iv3S1FIITv-8WA.png" /><figcaption>Bar Chart: Top 10 Regency That Consumes Beef on Average per Capita in One Week from 2018 to 2021</figcaption></figure><h4>Goat Meat Consumption</h4><figure><img alt="Bar Chart: Top 10 Regency That Consumes Goat Meat on Average per Capita in One Week from 2018 to 2021" src="https://cdn-images-1.medium.com/max/1024/1*mP2p5WtKdNeS3zjrDl9mDQ.png" /><figcaption>Bar Chart: Top 10 Regency That Consumes Goat Meat on Average per Capita in One Week from 2018 to 2021</figcaption></figure><h4>Pig Meat Consumption</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4_AR7Cb9MEC6F6h7vdqfw.png" /><figcaption>Bar Chart: Top 10 Regency That Consumes Goat Meat on Average per Capita in One Week from 2018 to 2021</figcaption></figure><h4>Other Meat Consumption</h4><figure><img alt="Bar Chart: Top 10 Regency That Consumes Other Meat on Average per Capita in One Week from 2018 to 2021" src="https://cdn-images-1.medium.com/max/1024/1*U_lBZygvM1JZltgN5bhsLw.png" /><figcaption>Bar Chart: Top 10 Regency That Consumes Other Meat on Average per Capita in One Week from 2018 to 2021</figcaption></figure><h4>Summary of Average Meat Consumption by Type of Meat in Each Regency</h4><p>Here is the summary of our graph above:</p><ol><li>For chicken Meat, <a href="https://en.wikipedia.org/wiki/Intan_Jaya_Regency">Intan Jaya Regency</a> in Central Papua province. The average consumption of chicken meat from 2018 to 2021 is 1.048 Kg per capita in one week.</li><li>For beef, <a href="https://en.wikipedia.org/wiki/Dogiyai_Regency">Dogiyai Regency</a> in Central Papua province. The average consumption of beef from 2018 to 2021 is 0.267 Kg per capita in one week.</li><li>For goat meat, <a href="https://en.wikipedia.org/wiki/Puncak_Regency">Puncak Regency</a> in Central Papua province. The average consumption of goat meat is 3.543 Kg per capita in one week.</li><li>For pig meat, <a href="https://en.wikipedia.org/wiki/Mahakam_Ulu_Regency">Mahakam Ulu regency</a> in East Kalimantan province. The average consumption of pig meat is 0.688 Kg per capita in one week.</li><li>For other meat, <a href="https://en.wikipedia.org/wiki/Merauke_Regency">Merauke Regency</a> in Central Papua province. The average consumption of other meat is 0.522 Kg per capita in one week.</li></ol><p>From the summary above we could see that the highest goat meat consumption is far beyond the highest consumption of any other kind of meat. And this is also applied to the top 4 goat meat consumption Puncak, Intan Jaya, Dogiyai, and Deiyai Regency) compares to the others. This might be the reason why these regencies are in the top 4 of meat consumption in total.</p><h3>PDRB Relationship with Meat Consumption</h3><p>This section means to answer the question from Our World in Data website regarding the richer the country the more meat is consumed. Here, PDRB would indicate how rich the regencies in Indonesia.</p><figure><img alt="Bubble Scatter Plot: Average Meat Consumption vs PDRB from 2018 to 2021" src="https://cdn-images-1.medium.com/max/1024/1*6flVz7VMtYUJL5axSxb6dg.png" /><figcaption>Bubble Scatter Plot: Average Meat Consumption vs PDRB from 2018 to 2021</figcaption></figure><p>As you can see above, Puncak, Intan Jaya, Dogiyai, and Deiyai regencies are consumes more meat but have low PDRB compared to regencies such as Jakarta Pusat, Jakarta Selatan, Kota Surabaya and Jakarta Utara, which are having the highest PDRB. This finding is quite surprising because the worldwide trend in Our World in Data website shows different outcome.</p><p>However, from our previous data and analysis before, I suspect two things that might cause this contradiction:</p><ol><li>Our data set is already per capita, which means it has been divided by population in each regency. Then the population of Puncak, Intan Jaya, Dogiyai, and Deiyai regencies might have been small. Hence, the denominator is relatively low compared to meat consumption in total (not per capita).</li><li>There might be an issue with the dataset itself, especially for goat meat consumption. If you look at the top 10 goat meat consumption you would find that these regencies (Puncak, Intan Jaya, Dogiyai, and Deiyai) consume more goat meat than other Regencies. Hence, total meat consumption affects these regencies heavily.</li></ol><p>Despite the contradiction, we could see that in Jakarta Pusat, Jakarta Selatan, Kota Surabaya, and Jakarta Utara, which are having the highest PDRB, the total average meat consumption in those regencies is still above the median (0.495 Kg). This could indicate that the meat consumption in the rich regency is relatively higher than in any other region with low PDRB.</p><h3>Conclusion and Future Work</h3><p>From this analysis, I could understand better how Indonesian consumes meat. Chicken is the type of meat that is consumed the most per capita in one week in Indonesia. And the region that eats the most chicken meat is Intan Jaya Regency at Papua Province.</p><p>The total average meat consumption trend is increased year-by-year despite the covid-19 restriction, although the increment is only fractions. There is also an anomaly in goat meat consumption, which it suddenly decreased from 2018 to 2019. This decline might affect our analysis of the PDRB relationship with the overall average meat consumption per capita in each regency in Indonesia.</p><p>Contradictive results of the PDRB relationship and the total average meat consumption open new opportunities for future work to scrutinize even more deeply about meat consumption in Indonesia. This might be accomplished by getting data about the population of each regency data and the average household weekly expense of each regency data.</p><p>I have created <a href="https://public.tableau.com/views/MeatConsumptionIndonesia/Dashboard1?:language=en-US&amp;:display_count=n&amp;:origin=viz_share_link">a simple dashboard</a> for this exploration on Tableau, feel free to checkout.</p><p>Thank you for reading, I hope you enjoyed my writing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e436c2638546" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Approach to Solve Probability and Statistical Problems with Python (Part 1)]]></title>
            <link>https://medium.com/@aifakhri/a-practical-approach-to-solve-probability-and-statistical-problems-with-python-part-1-755c8a12f916?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/755c8a12f916</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 15:08:15 GMT</pubDate>
            <atom:updated>2022-11-02T15:39:12.848Z</atom:updated>
            <content:encoded><![CDATA[<h4>Solving descriptive statistical, categorical variables and continuous variables problems with Python.</h4><figure><img alt="Photo by Volkan Olmez on Unsplash" src="https://cdn-images-1.medium.com/max/1024/0*ZnJSnViBM-GgKVdN" /><figcaption>Photo by <a href="https://unsplash.com/@volkanolmez?utm_source=medium&amp;utm_medium=referral">Volkan Olmez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If we take a closer look to probability or statistic test problems in a text book we would find the data that is given is already in a single value or sets of value, for example:</p><figure><img alt="https://www.probabilitycourse.com/chapter4/4_1_4_solved4_1.php" src="https://cdn-images-1.medium.com/max/779/1*96OS355T7ti358XSIx_Yzg.png" /><figcaption><a href="https://www.probabilitycourse.com/chapter4/4_1_4_solved4_1.php">Theoritical or text-book statistical problem</a>[1]</figcaption></figure><p>However, in practice (most of the time), the data for probability and statistical problems comes within a table(s) or dataset. This kind of data requires a different problem solving approach compared to the one in the text books despite using the same logic to solve the problem.</p><p>There are a lot of tools that we could use to help us solve probability and statistical problems within a dataset, such as Microsfot Excel, Google Sheets, Stata, SPSS, and Programming Language (Python, R, etc). Microsoft Excel and Google sheets might be the most popular due to its user friendly environment and easy to use.</p><p>However, in the rise of Data Science in the past few years, Python and R have become popular to solve probability and statistics programmatically.</p><p>Here we are going to explore and solve probability and statistical (along with statistical testing) problems using a dataset and Panda’s Library in Python to solve some of the probability and statistical problems.</p><h4>Python Requirement</h4><p>I use python 3.10.0 for this article. Here are the external libraries I use to help me solve the probability issues:</p><pre>pandas=1.4.2<br>numpy=1.22.3<br>matplotlib=3.5.2<br>seaborn=0.11.2<br>scipy=1.9.0<br>statsmodel=0.13.4</pre><p>Also, I am going to use jupyter-notebook to run this analysis instead of using python script. To download and install jupyter-notebook you could use this following resource.</p><h4>Dataset</h4><p>The dataset is from <a href="https://www.kaggle.com/datasets/teertha/ushealthinsurancedataset">kaggle</a>, it contains the information relating to insurance charges and the parameters that might affects the insured:</p><ul><li><strong>age:</strong> The age of the insured.</li><li><strong>sex: </strong>The sex (gender) of the insured. The values are male and female only.</li><li><strong>bmi:</strong> Body Mass Index of the insured.</li><li><strong>children:</strong> Number of children the insured has.</li><li><strong>smoker:</strong> Information whether the insured is a smoker or not. The value is “yes” for smoker and “no” for non-smoker</li><li><strong>region:</strong> The region of which the insured resides.</li><li><strong>charges</strong>: The insurance charges in USD for the insured.</li></ul><h4>First Exploration</h4><p>With our environment and dataset set, we could start this exploration by creating a notebook file with .ipynb extension then imports all the external libraries to the notebook:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from scipy.stats import norm<br>from statsmodels.stats import weightstats, proportion</pre><p>Then we load the dataset with pandas by using pandas’ read_csv() method:</p><pre>df = pd.read_csv(&quot;insurance.csv&quot;)</pre><p>In any data exploration, we would start by checking the dataset dimension and whether there is a null data in our dataset, here are the way:</p><figure><img alt="Checking the dataset dimension" src="https://cdn-images-1.medium.com/max/1024/1*KjjPZAEinferTsHRDjezVQ.png" /><figcaption>Checking the dataset dimension</figcaption></figure><figure><img alt="Checking null value in the dataset" src="https://cdn-images-1.medium.com/max/1024/1*KyaLPfULyMamPbGzoGPkSg.png" /><figcaption>Checking null value in the dataset</figcaption></figure><p>From the result above we could see that our data dimension is 1300 x 7 and there is no null in our dataset.</p><h3>Descriptive Statistical Problem</h3><p>Descriptive statistics describe the characteristics of a dataset and contain basic statistical measurement such as mean (average), median, standard deviation. These measurement can be find easily with Pandas by using describe() method:</p><figure><img alt="Descriptive statistics value with pandas" src="https://cdn-images-1.medium.com/max/1024/1*QrpG71DlBDpU0tzmWjYCxg.png" /><figcaption>Descriptive statistics value with pandas</figcaption></figure><p>The data of mean is self explanatory but for standard deviation is labelled as “std” while median is by “50%”.</p><p>Also, there are no sex, smoker and region variables because those variables data type is string, which cannot be calculated. Hence, Pandas ignores the calculation for those variables.</p><h3>Probability of Categorical Variable</h3><p>In our dataset the sex, smoker and region variables are a the categorical data, and to find a probability value of categorical data we could use discrete random distribution approach.</p><p>The problem we want to solve are a simple probability and conditional probability of the categorical variable, such as:</p><h4><strong>Problem: Probability of the insured is a male</strong></h4><p>To solve this problem we could use the basic probability equation:</p><figure><img alt="Basic probability equation" src="https://cdn-images-1.medium.com/max/732/1*QIe31XYzaSET_Xdx-xl76Q.png" /><figcaption>Basic probability equation</figcaption></figure><p>To apply the equation above in our dataset is by counting how many male data in the sex column in the dataset then divide by the total data of male and female in the sex column within the dataset. Translating this into python syntax:</p><figure><img alt="Basic probability calculation with Python and Pandas" src="https://cdn-images-1.medium.com/max/1024/1*mbmtqQhAKjLxcZcWh6boOw.png" /><figcaption>Basic probability calculation with Python and Pandas</figcaption></figure><p>From the result above the probability of the insured is male is 0.50523 or 50.523%.</p><h4><strong>Problem: Probability of the insured is a smoker given he/she is from northwest region</strong></h4><p>This is a conditional probability problem, which in theory the conditional probability can be solved with the following equation:</p><figure><img alt="Conditional probability equation" src="https://cdn-images-1.medium.com/max/953/1*qnSM-_qUKspgqUH5xvcPTw.png" /><figcaption>Conditional probability equation</figcaption></figure><p>In our problem the event A is the insured is a smoker and event B is the insured region. So, applying this equation in our code, first we find the data of a smoker that lives in the northwest region, then count the data. Next, we count the data of the insured who lives in the northwest region:</p><figure><img alt="Conditional probability calculation with python" src="https://cdn-images-1.medium.com/max/1024/1*ADUwT5bnqwvnWF7ECuRvKQ.png" /><figcaption>Conditional probability calculation with python</figcaption></figure><p>From the result above the probability of the insured is male is 0.21168 or 21.168%.</p><h3>Probability of Continuous Variable</h3><p>Solving a probability problem of continuous variables is through the continuous random distribution approach such as normal distribution, uniform continuous, exponential distribution, etc.</p><p>In our dataset the age, charges and bmi are classified as the continuous variable. So, to check the distribution type of our continuous variable we could use the density distribution graph which can be drawn using Python libraries: matplotlib and seaborn. Here is the code to draw the density distribution chart of our continuous variable:</p><figure><img alt="Python code to draw variable density distribution of continuous variable" src="https://cdn-images-1.medium.com/max/1024/1*ZmsaeLh633Xah5ladmGBAQ.png" /><figcaption>Python code to draw variable density distribution of continuous variable</figcaption></figure><p>Here is the result of the code above:</p><figure><img alt="Density distribution of our continuous variable" src="https://cdn-images-1.medium.com/max/1024/1*B3xO0Y1NHw2BmDlsNKFo3Q.png" /><figcaption>Density distribution of our continuous variable</figcaption></figure><p>The distribution of our continuous variable in our data resembles the normal distribution. Hence, we could use the normal distribution approach in order to solve our problem. With normal distribution, the probability value can be found with normal distribution Continuous Density Function (CDF) Here is the equation of CDF for normal distribution:</p><p>From the equation above, we need to find the mean and standard deviation from our continuous variable first, then use those values in the equation above along with the desired point of the calculation. The calculation might be a little complex, but with Python the calculation could be simpler.</p><p>The libraries we use are Pandas and Scipy. Pandas is used to find the mean and standard deviation with mean() and std() method respectively, while scipy is used to calculate the probability with stats.norm.cdf() method where the mean and standard deviation will be used in the argument.</p><h4>Problem: Probability of the age of the insured less than 40</h4><p>Like we mention above, we find the mean and the standard deviation, then using these as an arguments in the stats.norm.cdf() method:</p><figure><img alt="CDF and probability of the insured age is less than 40" src="https://cdn-images-1.medium.com/max/1024/1*enQn1tQ4P4f_zklqGVlQPw.png" /><figcaption>CDF and probability of the insured age is less than 40</figcaption></figure><p>Based on our data, the probability of the insured is less than 40 is 0.5225 or 52.25%</p><h4>Probability of the bmi of the insured greater than 25</h4><p>With the same step as before we could find the probability with the following code:</p><figure><img alt="CDF Calculation for bmi variable" src="https://cdn-images-1.medium.com/max/1024/1*LJI-RjAeXzOoYIW0_WlZ1Q.png" /><figcaption>CDF Calculation for bmi variable</figcaption></figure><p>However, this is not the result because the stats.norm.cdf() is coming from a normal distribution table, which only calculate the probability that is less than the desired point or “x”. Hence, to find the value of the insured greater than the “x” value, we subtract 1 with the CDF value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUW3oa5pJgAV5vumJc3UAg.png" /><figcaption>Actual probability for bmi greater than 25</figcaption></figure><p>Based on our data, the probability of the insured has bmi greater than 25 is 0.82348 or 82.234%</p><h3>Conclusion</h3><p>As you can see, the theoretical probability equation can be solved with ease by using python and its external libraries while maintaining the logic of the equation itself. Also, we could draw a graph with Python to better understand the variables inside our dataset.</p><p>In the next part I would like to solve the correlation coefficient problem and statistical testing problem within our dataset using python.</p><p>Thank you for reading, see you in the next post.</p><p>If you want to download the notebook, <a href="https://github.com/aifakhri/statistical-problem-with-python">here is the link</a>. However, the notebook already covers the writing in the next part of this series. So, feel free to checkout the notebook.</p><h4>Reference</h4><p>[1] H. Pishro-Nik, “Introduction to probability, statistics, and random processes”, available at <a href="https://www.probabilitycourse.com/">https://www.probabilitycourse.com</a>, Kappa Research LLC, 2014.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=755c8a12f916" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brief Intro to Robot Framework and Extending Robot Framework with Python]]></title>
            <link>https://medium.com/@aifakhri/brief-intro-to-robot-framework-and-extending-robot-framework-with-python-7c8b795dca7f?source=rss-8fecd32f3b9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c8b795dca7f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[robot-framework]]></category>
            <dc:creator><![CDATA[Fakhri Azhar]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 09:48:53 GMT</pubDate>
            <atom:updated>2022-08-03T09:49:27.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Robot Framework is a generic open source automation framework. It is one of the testing frameworks, which can be used to test any kind of testing environment: Web UI, Mobile, Network Device or Robotic Process Automation (RPA). Robot Framework is a python-based framework, however, it can be extended by using other programming languages such as Java, etc.</p><p>In this story I would like to tell a story about my project to extend the Robot Framework with Python.</p><h3>A Brief Introduction of Robot Framework</h3><p>Robot Framework has its own syntax, it is utilizing human-readable keywords. Also the content of the Robot Framework file, which has .robot extension, should be structured in sections. Here are the sections based on <a href="https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-data-syntax">Robot Framework guide</a>:</p><ul><li>Settings</li><li>Variables</li><li>Test Cases</li><li>Tasks</li><li>Keywords</li><li>Comments</li></ul><p>Those sections are optional, however, we should define at least one of the sections in a Robot Framework file to define the purpose of the file. These sections, also, should be defined in the Robot Framework file with this format: *** Settings *** .</p><p>I mostly use these sections: Settings, Variables, Keywords, and Test Cases.</p><h4>Settings Section</h4><p>This section is used to import data that is required in a Robot Framework file, such as, External Libraries, Keywords Libraries or External Variables. Also in this section we could set up our testing, such as defining a connection to a database or defining web driver connectivity etc.</p><p>Here is the example of the Setting section in a Robot Framework file:</p><figure><img alt="Robot Framework Settings Section" src="https://cdn-images-1.medium.com/max/1024/1*6Rqj8v7K8QCFZ0SdrEulYw.png" /><figcaption>Robot Framework Settings Section</figcaption></figure><p>The words on the left are the special keywords for the Settings section. The Documentation is to describe what kind of Robot File is this. The Resource keyword is used to import a Robot Framework file or library, whilst the Library keyword is used to import an external Library from another programming language or a robot framework built-in library that is required to be imported.</p><p>Lastly the Variables keyword is to import external variable files, which can be in the form of a Robot, Python or YAML File.</p><p>To import the Resource, Library and Variables files, we need to define its relative path to the Robot Framework file that loads those files as the argument. We could also parameterize the path:</p><figure><img alt="Parameterizing the Path" src="https://cdn-images-1.medium.com/max/1024/1*OD-yweRe-hyBnmi5XDE22Q.png" /><figcaption>Parameterizing the Path</figcaption></figure><p>How can we supply the information for this path? We could do it by assgning the variable name in the Variables section or we could pass the value for the variable when we run the Robot Framework script.</p><p>Also, in the Settings section there are the Test Setup, Test Teardown, Suite Setup and Suite Teardown. These are special keywords for preparing all necessary actions before the test is executed. These keywords require a single keyword as the argument, it can be an external keyword or an external library or a keyword within the file.</p><p>The difference of these special keywords are within the scope, the Test Setup and Teardown are for test case scope, while the Suite Setup and Teardown are for test suite scope.</p><h4>Variables Section</h4><p>In this section, we define variables that can be used in our test case. There are various types of variables in the Robot Framework, the most common variables we could use are scalar, list and dictionary:</p><figure><img alt="Robot Framework Variables Section" src="https://cdn-images-1.medium.com/max/1024/1*YFnEh2IuZsSuXowmkGx-Cw.png" /><figcaption>Robot Framework Variables Section</figcaption></figure><h4>Keywords Section</h4><p>We could define our own keyword in this section by combining existing built-in keyword libraries or using external libraries. These self-defined keywords are called user keywords.</p><p>In this section there setting we could use to set up our keywords, such as: Documentation, Arguments, Return, etc. These are optional but I always have the Documentation setting to describe what our keywords do. Here is the example of Keywords syntax:</p><figure><img alt="Robot Framework Keywords Section" src="https://cdn-images-1.medium.com/max/1024/1*6i_vTNzax9WFV2Bl8fwHew.png" /><figcaption>Robot Framework Keywords Section</figcaption></figure><h4>Test Cases Section</h4><p>This section is where we build our test case, which is constructed from the user keywords or built-in keywords or combination of both. Just like the Keywords section, there are some settings that we could use, but again, it is optional but nice to have. Here is the example of the Robot Framework test case:</p><figure><img alt="Robot Framework Test Cases Section" src="https://cdn-images-1.medium.com/max/1024/1*RSeICjdFR9BBBVZ-sU1bjw.png" /><figcaption>Robot Framework Test Cases Section</figcaption></figure><h4>Extending Robot Framework with Python</h4><p>Extending Robot Framework means that we create an external functionality that is not available with Robot Framework built-in libraries. This external functionality is stored in a specific file (or could be in a remote server) then loaded into the Robot Framework as a Keyword.</p><p>Here is the example of the implementation for extending Robot Framework:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqFm2wC7oOXi_7haYb5-Sg.png" /></figure><p>Here you could see that in the Settings section that we import the Python file commonLib.py which is the extended Python script that provides additional logic to the Robot Framework. Here is the content of that Python file and its logic:</p><figure><img alt="The Extended Python Script" src="https://cdn-images-1.medium.com/max/1024/1*WReY0bo3rv9GGI_FX959qQ.png" /><figcaption>The Extended Python Script</figcaption></figure><p>These script provides a function that can’t be found in the Robot Framework, which is the Netmiko library. Hence, by using this script we could use the Netmiko Library in the Robot Framework. Here how we use it:</p><figure><img alt="Using the Extended FunctionUsing the Extended Function" src="https://cdn-images-1.medium.com/max/1024/1*5mE5J2yxKsMHS1LOThpnBw.png" /><figcaption>Using the Extended Function</figcaption></figure><p>As you can see above, all we need to do is to call the function name connect_to_device as the Robot Framework Keyword: Connect To Device. We don’t need to write the underscore and the name become case insensitive, hence we can ditch the lower case naming convention.</p><h4>Conclusion</h4><p>With the richness of Python libraries, extending Robot Framework function with Python provides a way to create an expansive automation framework. One of the implementation that might helpful with this is an automated network infrastructure framework, where we record network change and test its changes in automated fashion.</p><p>So, in the midst of writing this, I’ve been developing such framework. So, stay tune with my stories!</p><p><em>Happy Testing!</em></p><p>*If you want to learn more about the script that I’ve used in this story, please kindly visit my <a href="https://github.com/aifakhri/extending_robot_framework_with_python">Github repo</a> for this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c8b795dca7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>