<?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 Mayur Dangar on Medium]]></title>
        <description><![CDATA[Stories by Mayur Dangar on Medium]]></description>
        <link>https://medium.com/@mayurdangar?source=rss-fdd85b7d203a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SfS4iaKHoJX3n94q6AitSQ.jpeg</url>
            <title>Stories by Mayur Dangar on Medium</title>
            <link>https://medium.com/@mayurdangar?source=rss-fdd85b7d203a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:42:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mayurdangar/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[CPM Bargainer for Programmatic Advertising]]></title>
            <link>https://mayurdangar.medium.com/cpm-bargainer-for-programmatic-advertising-833a65d7696f?source=rss-fdd85b7d203a------2</link>
            <guid isPermaLink="false">https://medium.com/p/833a65d7696f</guid>
            <category><![CDATA[programmatic-advertising]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cpm]]></category>
            <category><![CDATA[rtb-advertising]]></category>
            <dc:creator><![CDATA[Mayur Dangar]]></dc:creator>
            <pubDate>Thu, 19 May 2022 14:49:44 GMT</pubDate>
            <atom:updated>2022-05-19T15:10:30.796Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of digital marketing, Ads are bought and sold programmatically through auctions <strong>RTB </strong>(<strong>Real-time bidding</strong>) which means that every time there is an ad inventory that is available from <strong>SSPs</strong>(S<strong>upply-Side Platforms</strong>)/Ad Networks, multiple <strong>DSPs</strong>(<strong>Demand-Side Platforms</strong>) on behalf of advertisers bid for advertising at the same spot. Whoever wins the bid gets to save their ad on that site. This is a very rapid process that takes place from the time one hits enter on the URL and the page loads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*DQp0Wms2RiKIlp_d2OwfBg.png" /></figure><p>This is where programmatic advertising comes into play which facilitates the whole exercise of quick bidding. It is machine-to-machine automation of advertising and media transactions. There is no human intervention required, and the content has a higher level of personalization.</p><blockquote><strong>What is the Goal?</strong></blockquote><p>The ultimate goal of this project is to optimize the bidding value of the advertising inventory. So that DSPs can have control over bids and don’t end up bidding very high on the inventories.</p><p>Several metrics are being used by DSPs to measure the value of advertising inventory. One of the most effective KPIs is <strong>eCPM</strong>(<strong>effective cost per mille</strong>), a commonly used measurement that allows you to calculate the effective cost of an ad for every <strong>thousand impressions</strong>.</p><p>This project is all about bargaining for the CPM price of incoming inventory bid requests and still winning the impressions. That is why the project is named <strong>CPM Bargainer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*ZpzuqTJTL1Mh8iKmWE0ChQ.png" /><figcaption>eCPM formula</figcaption></figure><blockquote><strong>How can Data Science help?</strong></blockquote><p>Data Science is an essential part of many industries today as well as in programmatic advertising. Here in <a href="https://affle.com/"><strong>Affle</strong></a>, we always work with a massive amount of data and apply various data science solutions to optimize our <strong>UA (User Acquisition)</strong> and <strong>RT (Re-Targeting)</strong> campaigns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*50SD2CZW7G4yRQEZwSoGCQ.jpeg" /></figure><p>As we all know Data Science is the domain of study that deals with vast volumes of data and for this optimization problem, Here we will gather the historical bids data along with outcomes of those bids and will do the analysis of it then we can train the complex <strong>Machine learning/Deep learning algorithms</strong> to build predictive models that can predict the <strong>max eCPM </strong>for every incoming ad request, which will control the bid price and save money by not bidding higher than the predicted max eCPM.</p><p>For this project, we used GCP Bigquery for Data sets, Tensorflow with Keras to build the deep learning model, and Cloud storage to store the outcomes.</p><p>Let’s go further into details,</p><blockquote><strong>Introduction to Data</strong></blockquote><p>In terms of the historical data, we gathered the last 1 month&#39;s bid data which were successfully won by us and served as an impression using Bigquery SQL as all the datasets are stored in the <strong>GCP Bigquery</strong>. The number of rows of the resulted dataset was in millions which were very huge because of that it was then stored as a table in GCP Bigquery.</p><p>We considered supplier level features like site URL, an aggregator for training the ML/DL model,</p><p>We are trying to build the CPM bargainer model which will predict the max CPM for different publisher sites requesting different creative sizes<strong><em> </em></strong>and coming from the different country</p><blockquote><strong>Data Preparation and Data pipeline</strong></blockquote><p>For the Data preparation part, we performed the below few steps only:-</p><ol><li>Data Cleaning:- Fortunately, There were very less missing values that were filled with predefined default values. Also removed some outliers which had very high CPMs and this one was done according to <strong>IQR</strong> <strong>(Interquartile range) rule</strong>.</li><li>Data Preprocessing:- Converted the features’ values to hash values to handle the high cardinality (high number of unique categories), as we did for the <strong><em>Publisher Site </em></strong><em>feature and we also hashed all the values of creative size too.</em></li></ol><p>To do all of the above pre-processing very fast and feed the huge amount of data to the ML/DL model we integrated the extremely powerful <strong>GCP</strong> <strong>BigQuery I/O streaming API</strong>. With this API we were able to create the train and test data loaders directly from the Bigquery dataset.</p><blockquote><strong>Modeling</strong></blockquote><p>So, After setting up the data pipeline for the data streaming. We arrived at the most expected part of this article. let’s start looking into the implementation of the deep learning model.</p><p>For this project, we trained different Neural Network regressor models for different combinations of country and creative size using TensorFlow and Keras.</p><p>Below is the model configuration,</p><ol><li>Introduced two input layers one<strong> </strong>was<strong> an embedding layer </strong>for categorical features and another one was a normal input layer for numeric features, both followed by a concatenate layer combining both input layers.</li><li>Then this concatenate layer is followed by fully connected neural networks created by <strong>3–5 hidden layers</strong> containing <strong>32–64 neurons</strong> on each.</li><li><strong>Relu</strong> activation for all the hidden layers except the output layer. The output layer had <strong>Softplus</strong> activation.</li></ol><p>For compiling we used <strong>Adam optimizer</strong> and <strong>mean absolute error </strong>as a loss metric.</p><p>After the model creation, we fit both train and test data loaders which were already generated by bigquery streaming API to the model and completed the training process of the model.</p><p>This whole process was repeated for all the different combinations.</p><blockquote><strong>Automation and monitoring</strong></blockquote><p>In this project, we are following the offline training methods but we are training the same number of models every day.</p><p>To automate the whole process we created the cron job with the help of crontab, It runs the shell script containing run commands for python scripts daily on a dedicated GCP VM and generates the max eCPM caps for all the keys.</p><p>This process runs every day and it updates the max eCPM caps which could affect the whole bidding process either in a good or bad way due to this concern daily monitoring is very important for this project.</p><p>There are 2–3 factors that we need to monitor which are highly dependent on the eCPM max cap,</p><ol><li>Impression win rate:- total impressions / total bids</li><li>eCPA:- effective cost per action</li><li>eCPC:- effective cost per click</li></ol><p>Two other critical situations are described below:-</p><p><strong>Very High eCPM max cap</strong>:- In this scenario, we might see a higher number of impressions but there might be a chance that eCPC and eCPA might be high as well. Which might affect the overall revenue.</p><p><strong>eCPM max cap below the min_cpm</strong>:- In this scenario, we could most probably lose many impressions due to the min_CPM cap that comes in the request from the publisher/SSP. We are required to bid at least the minimum CPM in the local currency, or our bid will be filtered; if let’s say <strong>$0.05</strong> is the minimum in USD, and the max eCPM cap is <strong>$0.04.</strong> Then we will lose the bid for sure.</p><h4><strong>Conclusion</strong></h4><p>In this article, we went through all the steps which helped us to complete the project. In terms of the improvement, we can save <strong>20–25%</strong> of total media spending which was <strong>0–3%</strong> only with the static max CPM cap. This project helped our DSP to save lots of money and which resulted in higher revenue.</p><p>Also, check out the blog <a href="https://revx.io/blog/cpm-bargainer-model/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=833a65d7696f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Mail-order sales with Data Science]]></title>
            <link>https://medium.com/swlh/boost-mail-order-sales-with-data-science-68e3a12b37f4?source=rss-fdd85b7d203a------2</link>
            <guid isPermaLink="false">https://medium.com/p/68e3a12b37f4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mail-order]]></category>
            <category><![CDATA[udacity-nanodegree]]></category>
            <dc:creator><![CDATA[Mayur Dangar]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 10:59:54 GMT</pubDate>
            <atom:updated>2021-02-11T13:17:13.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*Tit3KkQ6H80gfDeK.jpg" /></figure><blockquote>Hello fellas,</blockquote><blockquote>The goal of this project is to help marketing team to identify particular customer segments which are most likely to be interested in mail-order sales by analyzing the demographic data of the general population of Germany and the current customers of Arvato Financial Services.</blockquote><h3><strong>Introduction</strong></h3><p>This case study is based on real life project given by <a href="https://www.bertelsmann.com/divisions/arvato/#st-1"><strong>Bertelsmann/Arvato</strong></a> <strong>Financial Services </strong>located in Germany and <strong>Udacity</strong> as a capstone project of Data Science Nano Degree. This project is also about <strong>Unsupervised learning</strong> and customer segmentation.</p><p>This project is divided in below mentioned three major parts :-</p><blockquote><strong>Customer Segmentation :-</strong> Analyze the demographic data of the general population and the current customers using Unsupervised learning techniques.</blockquote><blockquote><strong>Supervised Learning Model :- </strong>Preprocess<strong> </strong>the given training data based on previous analysis done in customer segmentation part and train the machine learning model that predicts whether or not each individual will respond to the campaign.</blockquote><blockquote><strong>Kaggle Competition :- </strong>Use trained machine learning model on given campaign data to do the predictions as a Kaggle competition.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/0*8y67CXU4EhFAnXdn.jpg" /></figure><h3>1. Customer Segmentation</h3><p>In this part, we first understand the data-set and underlying features.We have two data-sets which are provided by Arvato financial services , which I am not allowed to share with anyone according to already accepted terms and conditions.</p><p><strong><em>Datasets :-</em></strong></p><blockquote><strong>AZDIAS</strong> :-<strong> </strong>Demographic data for the general population of Germany.</blockquote><blockquote><strong>CUSTOMERS</strong> :- Demographic data for the current customers of mail-order service company</blockquote><blockquote><strong>MAILOUT_TRAIN and MAILOUT_TEST :- </strong>Demographic data to train the machine learning model and test data to make predictions on it for Kaggle competition.</blockquote><p>We analyze Azdias and Customers data using unsupervised learning technique called <strong>KMeans</strong> <strong>clustering</strong> algorithm, get the customers segmentation and compare the customers clusters against the general population.</p><p>Of-course we need to go through data cleansing process before we start doing all the analysis. As we know this is very important and very time consuming part of the data science work flow.</p><h4>1.1 Data introduction</h4><p>Let’s have a look at general population dataset (Azdias) :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtuClpDT-NenM5Yoz1jTWQ.png" /></figure><p>Azdias dataset has total <strong>366</strong> features (columns) and <strong>891211 </strong>individuals (rows) where Customers dataset has <strong>369 </strong>features ( Extra 3 features ‘CUSTOMER_GROUP’, ‘ONLINE_PURCHASE’, ‘PRODUCT_GROUP’ ) and <strong>191652 </strong>individuals data. Almost all the features are categorical feature, so most of them are ordinal and some of them are nominal features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*1PXRkYAYAwzNk_jCruW79g.png" /></figure><p>The Image on the left side is showing <strong>number of features </strong>X <strong>the information levels</strong> , So we have <strong>PLZ8 </strong>related features more than 100 , which is all about the car/s’ detailed information owned by a person. Then we also have about person him/her self , household, building etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEC3SzgHQpNpvN3XcjdVJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKIs630oehzpYmX3CF6v3w.png" /></figure><p>Then every information levels have related features and as I mentioned before most of the features have ordinal categorical data that is starting from 1 or 0.</p><p>Checkout the last table, you can see that it has 2 attributes’ information and its levels. <strong>HH_EINKOMMEN_SCORE </strong>has 6 levels , from <strong>1–6 </strong>( <strong>Highest</strong> income to<strong> very low</strong> income ) and also <strong>-1,0</strong> as <strong>unknown</strong>. About unknowns we are going to discuss in next steps. Also in <strong>INNENSTADT </strong>we have data in distance orders. Most of the features have ordinal data like in above image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*HLjZiOlj3pHn-MuY.jpg" /></figure><h4>1.2 Missing Data</h4><p>In this step, we are going to deal with the missing data as well as unknown data. First we will deal with the unknown values but also before that there is one more problem that we need to take care of that is a Mixed Types at <strong>(18,19)</strong> as warned in below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJEnIzHNNGdgwUzdE_8lPA.png" /><figcaption>We should not ignore this warning, I repeat never.</figcaption></figure><p>I converted those columns data into numeric type with the parameter errors=”coerce”, so if for some values the function gets converting error , those will be replaced with <strong>NaN</strong>. After fixing mixed type problem we have all the data in numeric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUmQhcuGSx5X77etq0NLBQ.png" /></figure><p>We also need to convert unknown labels as NaN, because there are so many values with -1 or 0 which are actually unknowns. I converted all of them to NaN And just fyi not all the features had the -1 or 0 as unknowns , some of them also have 9 as unknowns so I had to create the dataframe like you are seeing in the above image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*NBVVxFJD4Pia1tzSRUwiKA.png" /></figure><p>Now after converting all the data to numeric and unknowns to <strong>NaN , </strong>we need to check the missing data % in all of the features and there are 366 columns. In the image you can see that columns having more than 40% percentage of missing values. 1st subplot is for <strong>Azdias</strong> and 2nd one is for <strong>Customers</strong> data.</p><p>I observed that there are <strong>20</strong> columns which have more than <strong>20%</strong> missing values in their data in Azdias. but when I checked for for more than <strong>15%</strong> missing values there are total <strong>80</strong> columns which have that much percentage. It is too much data loss and I decided to drop only columns that have more than <strong>20%</strong> missing values.</p><p>After dropping columns I also checked for rows. It means calculated missing values in percentage by rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpgb2-paePhpqyinHFssFQ.png" /><figcaption>Grey is For Azdias and red for Customers</figcaption></figure><p>As you can see in the image we have around 80–90k rows which have more than <strong>20% </strong>missing values (columns). I concluded from the image so decided to go with threshold of <strong>20%</strong> and dropped all the rows which have more than <strong>20%</strong> missing values.</p><p>That is just a coincidence that we have both threshold for <strong>20%</strong> ;)</p><p>So, After dropping unnecessary columns and rows , we have now (<strong>763864</strong>, <strong>366</strong>) in Azdias and (<strong>138691</strong>, <strong>369</strong>) in Customers dataset.</p><h4>1.3 Data engineering and Missing Data Imputation</h4><p>After looking into the dataset in deep. I found there are actually 4 features that don’t have numeric type. one has timestamp <strong>EINGEFUEGT_AM </strong>that can be converted into timestamp data type, two have so many labels but not ordinal data but completely random labels which we dropped, where last one <strong>OST_WEST_KZ </strong>has only two unique values <strong>{“W” , “O”}</strong> which we can convert it in to numeric like <strong>{“W” : 1, “O” : 0}</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOv-TLRkyPaP3ZotVRhmgg.png" /></figure><p><strong>CAMEO_DEUINTL_2015</strong> has labels that we can split into two and create two new features. If you try to look closely, from <strong>11–15 </strong>the households is wealthy and the family type is changing.</p><p>After cleaning all the features and some feature engineering I used Missing data simple imputer with <strong>strategy=”most_frequent”</strong> because all the features are categorical features.Now, we don’t have any missing values. It all fixed!!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*g8avHBo9k9lVrDO2.jpg" /></figure><h4><strong>TL DR;</strong></h4><p><strong>Data preprocessing :-</strong></p><ol><li>Fixed Mixed type features by converting them to numeric</li><li>Replaced unknown values to <strong>NaNs.</strong></li><li>Converted some object data to Numeric</li><li>Drop columns having more than 20% missing values and also same for rows.</li><li>Created more features from one feature and some other data engineering</li><li>Used simpleImputer with <strong>strategy=”most_frequent” </strong>and<strong> </strong>filled all the missing values.</li></ol><h4>1.4 Dimentionality reduction using PCA</h4><blockquote>So Why Do we need <strong>PCA</strong> and what does it actually do?</blockquote><p>As you know we have around 346 features after removing 20 columns in preprocessing step. All of the features are not important and to reduce the complexity of the machine learning models we need to reduce the dimensionality but by keeping the variability same as before.</p><p>PCA stands for <strong>Principal Component Analysis, </strong>which<strong> </strong>is a method that uses simple matrix operations from linear algebra and statistics to calculate a projection of the original data into the same number or fewer dimensions. In short , It reduces the columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Im9NO9eVTlCeZ_6rAmqV-w.png" /></figure><p>From above image we can conclude that to get more than 90% explained variance we need atleast 170 features and I decided to keep 172 components as final dimensions.</p><blockquote>Analysis on components and the original features :-</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*mYbJXX7kcqL5kZbI.png" /></figure><p>This image is for component number <strong>0,</strong></p><ol><li>number of 1–2 family houses in the PLZ8 has positive weights where more than 6 family houses it has negative weights</li><li>most common building-type within the PLZ8 has negative weights too.</li><li>When it is all about cars the feature weights are also positive.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*F0ZzRBsLhk8zWuWKxJVGTQ.jpeg" /></figure><h4>1.4 KMeans Clustering</h4><p>After deciding that we keep 172 components only we will use KMeans clustering algorith. KMeans is a very popular Unsupervised learning technique to get the clusters of not labeled dataset. This is for estimating customers segments/groups.</p><p>Here we use KMeans’s Elbow method to decide the optimal number of clusters.In this method we will apply KMeans for different number of clusters and calculate the sum of squared distance of every point to its respective (predicted) cluster. Then we plot those data as <strong>number of clusters vs SSD.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zw1G-zNZzjVmdx0XluG_OA.png" /></figure><p>In the Image, we can see that the SSD (Distortions) is keep decreases as number of clusters increases. When we zoom into that then at 10 we could find the small elbow there. So in the end we can conclude that the optimal clusters is 10 based on elbow mothod.</p><p>After considering 10 clusters as optimal we run the model on Azdias and Clusters data to predict the cluster number.</p><h4>1.5 Analyze the Cluster distribution</h4><p>Let’s compare two dataset’s cluster distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QmMa8NvqvkdFQvhwFAJZw.png" /></figure><p>From Above Image we can observe that most of the customers are coming from 1,4,8,9 clusters. And also in the customers data that mail order company has showed that most of the customers are coming from 1,4,5,8. Let’s also look at the percentage of population.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rfU4eYXBhVfdANB3w-WeA.png" /></figure><p>so clusters which have &lt; 1 ratio. we can inference that the customers that belong to those particular clusters are more likely be our future customers, the mail order company should target those clusters to attract and add new individuals into their customer service list.</p><p><strong>Conclusion for part 1</strong> :- Based on the real life demographic data provided by Arvato Financial service has helped to get the customer segmentation, which can be used for targeting the general population.</p><h3>2. Supervised Learning Model</h3><p>Now, It is time to build a prediction model, which we always interested about. 😜</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*d4sJveCECCUdAZWA.png" /><figcaption>Buy DogeCoin 😅</figcaption></figure><p>We have <strong>MAILOUT-TRAIN</strong> and <strong>MAILOUT-TEST</strong> two datasets for training and testing of the machine learning model.</p><h4>2.1 Training and Testing Process</h4><p><strong>MAILOUT-TRAIN</strong> :- It has <strong>366</strong> features same number as we have in Azdias dataset and <strong>42962 </strong>rows. We are going to use the same analysis and cleansing techniques that we used for Azdias and customers to clean our data.</p><p>After getting the cleaned data we will follow the standard ML training process,</p><blockquote>1. Standardization of the dataset and Splitting it into the train and test datasets</blockquote><blockquote>2. Try different machine learning classification models</blockquote><blockquote>3. Do the predictions on test dataset and compare the test score based on one metric called ROC-AUC score.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Qaota7HeTarRPSAMv8tKlg.png" /></figure><p>The table is showing that we got good accuracy using boosting algorithms and GradientBoostingClassifier has highest ROC-AUC score and elapsed time is 37.63 secs. We can directly use the model to do the predictions for the Kaggle competition but I wanted to try hyper-parameter tuning method to improve this model and to generalize the model.</p><h4>2.2 Hyper-parameter tuning</h4><p>We have so many hyper parameters in the machine learning models , let take first Gradient boosting classifier it has hyper parameters like <strong>min_samples_split, min_samples_leaf, max_depth, max_leaf_nodes , max_features, learning rate </strong>etc<strong>.</strong></p><p>In the last table we observed that 3 models have good accuracy <strong>Adaboost</strong>, <strong>XGBoost</strong> and <strong>Gradient Boosting</strong>. We will use these three models and try to improve its performance by tuning some of the hyper-parameters. For that we use <strong>GridSearchCV</strong> method.</p><p>On Adaboost I got <strong>0.6822 test </strong>ROC-AUC score, On GBM I got <strong>0.7051 </strong>and<strong> </strong>on<strong> </strong>XGBoost I got <strong>0.7046.</strong></p><p>I saved above three best models to make the predictions on the test dataset.</p><h3>3. Kaggle Competition</h3><p>Finally, we are at the last step of this project, it’s time to test above best three models in competition through Kaggle. <a href="http://www.kaggle.com/t/21e6d45d4c574c7fa2d868f0e8c83140">here</a>.</p><p>In this step I have to clean <strong>MAILOUT-TEST </strong>dataset, which has same number of rows and columns <strong>42962 rows </strong>and<strong> 366 columns. </strong>We use the same cleansing function. I used above saved three boosting models to get the predictions and submitted the three different outcomes as CSV format.</p><p>The best score I got is 0.70876 and 237 Rank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*SSIcnzvyGnVd33Ip" /></figure><h3>Improvement</h3><p>Below are the things or steps we can try to improve our predictions,</p><ol><li>Analyze all the features in more depth because some of them I ignored because of multi-level categorical features, try to remove the outliers, more feature engineering on the data.</li><li>Try different approach to fill the missing values.</li><li>Include more Hyper-parameters for tuning.</li></ol><h3>Conclusion</h3><p>This real life project provided by Mail-Order service, was to create the customer segmentation using the general population of Germany. This analysis could be helpful for marketing team to target individuals who are more likely to be interested in their Mail-Order service.</p><p>Y<em>ou can find the code and detailed analysis </em><a href="https://github.com/EagleDangar/mailorder-service-datascience"><em>here</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*3STB0oA0WHvJwWPF.jpg" /><figcaption>😅</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68e3a12b37f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/boost-mail-order-sales-with-data-science-68e3a12b37f4">Boost Mail-order sales with Data Science</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Black Friday Insights and Prediction]]></title>
            <link>https://medium.datadriveninvestor.com/black-friday-insights-and-prediction-16933b8a8bfb?source=rss-fdd85b7d203a------2</link>
            <guid isPermaLink="false">https://medium.com/p/16933b8a8bfb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[black-friday]]></category>
            <category><![CDATA[udacity-nanodegree]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mayur Dangar]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 19:45:50 GMT</pubDate>
            <atom:updated>2021-03-08T13:43:10.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDcf93PFu_gJb5bD2XEhVQ.jpeg" /><figcaption>source :- Google</figcaption></figure><h3>Black Friday: How much is the customer going to spend?</h3><h3>A Data Science Case Study</h3><p><strong><em>Hello 👋 , my fellow Data Scientists and non Data Scientists ,</em></strong></p><p><strong><em>First of All, I am very glad that you are here, this is my first article to encourage myself towards Data Science. I am not good at writing articles or English. Please forgive if there is any flaw in this article.</em></strong></p><h3>Introduction</h3><p>In this article, we will talk about Black Friday, like how important it is for shoppers and retailers, and insights based on the historical transaction data.</p><p>We will follow the <strong>CRISP-DM Process (Cross Industry Process for Data Mining) </strong>in this case study. Below are the stages of this process,</p><ol><li><strong>Business Understanding</strong></li><li><strong>Data Understanding</strong></li><li><strong>Prepare Data</strong></li><li><strong>Data Modeling</strong></li><li><strong>Evaluate the Results</strong></li><li><strong>Deploy</strong></li></ol><p>We will cover all the stages except Deploy.</p><p>OK, But first let’s talk about this very special day.</p><blockquote><strong>What is Black Friday?</strong></blockquote><blockquote>Most probably you all know that It is typically a day full of special shopping deals and heavy discounts and is considered as the kickoff of the holiday shopping season. This season is crucial for the economy, especially for retailers.</blockquote><blockquote>You wait for a whole year to grab the best <strong>offers/discounts</strong> on online platforms and in physical stores. 😉</blockquote><blockquote>But you might not know about <strong>the</strong> <strong>origin</strong> of Black Friday,</blockquote><blockquote>So why the name? Some say the day is called “Black Friday” with respect to the term “black” referring to being profitable, which stems from the old bookkeeping practice of recording profits in black ink and losses in red ink. The idea is retail businesses sell enough this Friday to put themselves “in the black” for the rest of the year.</blockquote><h3>1. Business Understanding</h3><p>Retailers spend an entire year planning their Black Friday sales. They use the day as an opportunity to offer the lowest possible prices on overstock inventory and to offer doorbusters and discounts on <strong>seasonal items, electronic items, decoration items, etc.</strong></p><p>Consumers also wait for a whole year to shop on Black Friday because of the big discounts and great offers. The contents of Black Friday advertisements are often so highly anticipated that retailers go to great lengths to ensure that they don’t lose out publicly beforehand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*o-CPed4MK6HwI-G4XxSdjg.png" /></figure><p>According to <strong>2018</strong> data the average global growth of interest in Black Friday sales was <strong>117%</strong>. That’s why It’s a critical and profitable day for the retail sector. It also creates the new competition for the retailers and to keep up with this, retailers need to dive deeper into advanced Black Friday marketing strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rqWPw4EvCnNezJVDcV35Tw.png" /></figure><p>Retailers need proper numbers and better insights on consumers’ historical transaction data of Black Friday to know about the shopping characteristics of consumers and the trending products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0InNiuas5s9_TWTGJwsatQ.png" /><figcaption>This report was created based on data provided by Picodi.com — a global discount provider existing since <strong>2010</strong>. Black-Friday.Global — dedicated to Black Friday deals — was created by Picodi.com. <strong>12,000</strong> participants from <strong>55</strong> countries took part in the survey.</figcaption></figure><p>Based on that, they can implement and apply different types of marketing strategies for different types of customers and offer discounts to attract them.</p><p>OK, now we know about Black Friday and its importance. So, Let’s get started with the data. 😊</p><h3>2. Data Understanding</h3><p><strong>Data Collection</strong>:</p><p>For this case study, we are going to download the dataset from <a href="https://www.kaggle.com/sdolezel/black-friday">Kaggle (Black Friday)</a>. This data set has two files <strong>train.csv</strong> and <strong>test.csv. </strong>As we are not participating in the competition so we are going to use only <strong>train</strong> data.</p><p><strong>Data Visualization:</strong></p><p>Let’s display the first 5 rows of training data and some basic information of all the fields,</p><pre>train_df = pd.read_csv(&quot;./kaggle/input/black-friday/train.csv&quot;)<br>train_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRTtycLSNXcS2QUeUnKMoA.png" /><figcaption>Every row has unique pair of (User_ID, Product_ID)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*cQjqDZUNXsTnNFNWm4lMEA.png" /></figure><pre>Total Transactions -&gt; 550068<br>Total unique users -&gt; 5891<br>Total unique products -&gt; 3631</pre><p>Looking at the data, we can conclude that we have a total <strong>of 12</strong> columns, a total <strong>of 550058</strong> transaction rows, <strong>5891</strong> unique users, and <strong>3631</strong> unique products. We have <strong>7</strong> numeric variables and <strong>5</strong> object variables. We don’t have any missing values except two columns <strong>Product_category_2</strong> and <strong>Product_category_3.</strong> We will handle it later in the Data Preprocessing part.</p><p>let’s also compute a summary of statistics related to the Data Frame columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVuT2XBcfzIOhGP4v0RixQ.png" /></figure><p>In the above image, if you try to look at the <strong>Occupation </strong>field it has all the quartile (min, 25%, 50%, 75%, and max) values an integer, the same goes to <strong>Marital_Status</strong>, <strong>Product_category_1, Product_category_2, and Product_category_3 </strong>columns. Well obviously<strong>, Occupation</strong> and <strong>Marital_Status</strong> must be considered<strong> </strong>as<strong> categorical</strong> columns. But I wonder about the remaining 3 columns 🤔, like do they contain the actual values or are those only the labels for different categories? 😕. We will find it out soon 😎 .</p><p>OK, now we have a general picture of our data. So, let’s start with some questions related to the total number of transactions count.</p><blockquote><strong>Questions :-</strong></blockquote><blockquote>1. Which age group has done more transactions?<br>2. Have males done more transactions than females?<br>3. Do users’ occupations have any relation with the number of transactions?<br>4. Do users who are living in the city more than 1 year have done more transactions?<br>5. Does category of city have any impact on purchase quantity? <br>6. Does marital status have any correlation with Black Friday purchase value?</blockquote><p>To get the answers to the above questions we need count plots of the particular fields. We are going to use the<strong> seaborn</strong> library to create cool charts. It is a wonderful library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-M0JEmKDCrmQZoYRqwjwHw.png" /></figure><blockquote><strong>Answers :-</strong></blockquote><blockquote>1. In figure 1, 26–35 age range have done more transactions.<br>2. In figure 2, Male users have done more transactions.<br>3. In figure 3, Users whose occupations are 0 and 4 have done more transactions.<br>4. In figure 4, Users who stayed in the current city for 1 year have done more transactions.<br>5. In figure 5, Users from city category B have done more transactions.<br>6. In figure 6, Users who are not married yet have done more transactions.</blockquote><p>Oh, now this is getting interesting. 🎃</p><p>Let’s talk about <strong>total purchase amount </strong>too. 👍</p><blockquote><strong>Questions :-</strong></blockquote><blockquote>1. Which age group has spent more on Black Friday?<br>2. Have females spent more than males?<br>3. Do users’ occupations have any relation to spending money on Black Friday?<br>4. Do users who are living in the city for more than 1 year have spent more money?<br>5. Does category of city have any impact on the total purchase amount? <br>6. Does marital status have any correlation with Black Friday purchase value?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZW7pXTifndM9GKsChm_Cg.png" /></figure><blockquote><strong>Answers :-</strong></blockquote><blockquote>1. In figure 1, 26–35 age range have spent more money.<br>2. In figure 2, Male users have spent more money.<br>3. In figure 3, Users whose occupations are 0 and 4 have spent more money.<br>4. In figure 4, Users who stayed in the current city for 1 year have spent more money.<br>5. In figure 5, Users from city category B have spent more money.<br>6. In figure 6, Users who are not married yet have spent more money.</blockquote><p>Well, I guess you might be wondering why do we have the same answers for both, and to clear out this confusion 😕 we need to do the same exercise for the <strong>average purchase amount</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0sy-xaAHnR0_Ja3Ymk9bfA.png" /></figure><p>From the above figures, we can conclude that our suspicion was right. Because every category has almost <strong>the same height of bars</strong> for every field. This clears out the confusion.</p><p>OK, Let’s add one more group gender and see what insights we will get.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iim2Tw9WD07YJjFCdqFgDw.png" /></figure><p>OK, I can’t do anything about this. But according to data males have spent more amount than females have on average. It is the same for all the fields.</p><p>Now next is an exciting one, which is Pair-plot 😉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PO0cUuCoM3EzkvhUxYbtKA.png" /></figure><p>Well above Pair-plot is not giving more good insights about the correlation between numeric fields. Also, look at all three product category fields. It is a bit confusing 🤔. We will figure it out together in the next stage. 👍</p><h3>3. Data Preprocessing</h3><p>Now we have an understanding of data and we have some insights as well but we need a trained <strong>Machine Learning model</strong> which can predict that how much the consumer is going to spend and to train the machine learning model we need to have a well-formatted, structured, and cleaned data.</p><p>The process of cleaning, structuring, and enriching raw data into the desired format is known as <strong>Data Wrangling</strong>, sometimes referred to as <strong><em>Data Munging</em>/ Cleansing. </strong>This process costs around 80% of the data science project’s time. It is like cooking a meal we need to be ready with all the ingredients and that takes too much time.</p><p>First, we need to deal with the missing values. So, let’s check the percentage of missing values,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*zW6jNo6y9kVv7fB3bOK6nw.png" /></figure><p>As you can see that we have only 2 fields which have missing values. <strong>Product_Category_3 </strong>with <strong>69.67%</strong> and <strong>Product_Category_2</strong> with <strong>31.57%</strong> missing values.</p><p>We can use several impute methods to fill the missing values. So, we can use the mean method to fill the values in <strong>Product_Category_2. </strong>But for <strong>Product_Category_3</strong>, we are talking about 70% missing values. Before we impute anything, We need to clear out our confusion.Doing so let’s see all the transaction data for the only product_ID = “<strong>P00265242</strong>”.</p><pre>train_df.loc[<br>train_df.Product_ID==&quot;P00265242&quot;,[&quot;User_ID&quot;,&quot;Product_ID&quot;,&quot;Product_Category_1&quot;,&quot;Product_Category_2&quot;,&quot;Product_Category_3&quot;]<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0VRWQ9L25eI09s8E2J72w.png" /></figure><p>After seeing the result of the last query, what I can see is that all the three product category fields are containing the labels, not the actual values. Let’s create the count plots for these three fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krbDSKzlp2vi3UDnqTaDtA.png" /></figure><p>So, we cannot just use the mean method to impute the values. Also, median/mode will also make the data somewhat biased. What we can do is create another label which will be in replace of the <strong>Nan</strong> values. Let’s use 0.0 as a missing label and impute it into both fields and check again the percentage of missing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*18-Q_PIGFQQOMdnA7udQHg.png" /></figure><p>So we have all the values, no missing values anymore. Now we can transform our data such a way that we can feed the data into the machine learning model for training.</p><p>For Data transformation , we need to handle categorical and numeric columns separately. If we again look at the data. We don’t need <strong>User_ID</strong> and <strong>Product_ID </strong>because<strong> </strong>those are just the identification numbers and don’t give any information to us. So first we have to drop those columns.</p><pre>train_df = train_df.drop([&#39;User_ID&#39;, &#39;Product_ID&#39;],axis=1)</pre><p>Now, we are left with only all categorical fields, almost all the fields have numeric labels except <strong>Age</strong>, <strong>Stay_In_Current_City_Years, City_Category, </strong>and<strong> Gender. </strong>To transform the string values to labels we are going to use the <strong>scikit-learn’s preprocessing</strong> method called <strong>LabelEncoder</strong> and for one-hot encoding, we are going to use pandas inbuilt method <strong>pandas.get_dummies</strong> method. We will fit and transform the values of the first three columns with LabelEncoder and Gender column with the get_dummies method.</p><pre>le = LabelEncoder()</pre><pre>train_df[&quot;Age&quot;] = le.fit_transform(train_df[&quot;Age&quot;])</pre><pre>train_df[&quot;Stay_In_Current_City_Years&quot;] = le.fit_transform(train_df[&quot;Stay_In_Current_City_Years&quot;])</pre><pre>train_df[&quot;City_Category&quot;] = le.fit_transform(train_df[&quot;City_Category&quot;])</pre><pre>train_df = pd.get_dummies(train_df, prefix=[&quot;Gender&quot;])</pre><p>What is the correlation between all the fields after the transformation?</p><p>Let’s create a heat-map of the correlation values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yj6ImUsV8P-veqVbU2NcFw.png" /></figure><p>According to the heat-map, we have some correlation between purchase and product_categories.<br>Now we have well-formatted and cleaned data. So, let’s create two data-frames, one is for all independent fields and another is for the dependent field (Target field).</p><pre>X = train_df.drop(columns=&#39;Purchase&#39;)<br>y = train_df[&#39;Purchase&#39;].values</pre><pre>Input shape -&gt; (550068, 11)<br>Output shape -&gt; (550068,)</pre><p>OK next stage is the Data Modeling.</p><h3>4. Data Modeling and <strong>Evaluate the Results</strong></h3><p>In this stage, I assume you are already well aware of the machine learning and how it works. So, we are not going to talk about the theory in this article. We are directly going to train several <strong>supervised machine learning</strong> models and evaluate the outcomes one by one.</p><p>Before that, we will use the <strong>train_test_split</strong> method to divide all our data into two sets: training and testing set. The training set will be used to fit our model. Training data is always used for learning, adjusting parameters of a model, and minimizing an error on the output. The rest of the data (the Test set) will be used to evaluate the results.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)</pre><p>We have split our data into train and test with 70% train and 30% test. the shape of both datasets are,</p><pre>Input train shape -&gt; (385047, 11)<br>Input test shape -&gt; (165021, 11)</pre><p><strong>Machine Learning Models :</strong></p><p>Let’s start with Linear Regression as usual 😅,</p><ol><li><strong>Linear Regression</strong></li></ol><pre>lr = LinearRegression(n_jobs=-1)<br>train_and_evaluate(lr,X_train,y_train,X_test,y_test)</pre><p>In the above code snippet, I have used <strong>train_and_evaluate </strong>which is a method that I have created. Inside this method, the model is fed with train data, and after the model is trained we evaluate the model’s results/performance using two metrics <strong>R-2 score</strong> and <strong>RMSE</strong> error.</p><pre>Train R-2 Score -&gt; 0.1530319738650423<br>Test R-2 Score -&gt; 0.1502225848000539<br><br>=============================================<br><br>Train RMSE  -&gt; 4623.897758674754<br>Test RMSE  -&gt; 4627.777465694635</pre><p>OK, Well this is very poor result. Didn’t expect this much low. Let’s see what happens with the next.</p><p><strong>2. KNN Regressor</strong></p><pre>knnreg = KNeighborsRegressor(n_neighbors = 6)<br>train_and_evaluate(knnreg,X_train,y_train,X_test,y_test)</pre><p>And the Result,</p><pre>Train R-2 Score -&gt; 0.6867254458886132<br>Test R-2 Score -&gt; 0.584082218078744<br><br>=============================================<br><br>Train RMSE  -&gt; 2812.1421834752146<br>Test RMSE  -&gt; 3237.603187280763</pre><p>This is good, it is much higher than the Linear regression, but still between the train and test R-2 score has so much difference.</p><p><strong>3. Decision Tree Regressor</strong></p><pre>dtr = DecisionTreeRegressor(max_depth=8,<br>                            min_samples_split=5,<br>                           max_leaf_nodes=10,<br>                            min_samples_leaf=2,<br>                            random_state=142)<br>train_and_evaluate(dtr,X_train,y_train,X_test,y_test)</pre><p>Let’s try with tree regressor.</p><pre>Train R-2 Score -&gt; 0.620705208649921<br>Test R-2 Score -&gt; 0.6151249212697111</pre><pre>=============================================</pre><pre>Train RMSE  -&gt; 3094.305250315925<br>Test RMSE  -&gt; 3114.4385769651567</pre><p>Now we got very less difference between train and test R-2 score.But, it is only 61% accurate.</p><p><strong>4. Random Forest Regressor</strong></p><pre>rf = RandomForestRegressor(max_depth=8,<br>    min_samples_split=4,<br>    min_samples_leaf=2,<br>    random_state=142)<br>train_and_evaluate(rf,X_train,y_train,X_test,y_test)</pre><p>Let’s try forest regressor , because tree regressor didn’t give us good results.</p><pre>Train R-2 Score -&gt; 0.6562463716226338<br>Test R-2 Score -&gt; 0.6491769152142575<br><br>=============================================<br><br>Train RMSE  -&gt; 2945.7667802369456<br>Test RMSE  -&gt; 2973.4727049991225</pre><p>Now we got 65% accuracy which is more than tree regressor.</p><p><strong>5. XGBoost Regressor</strong></p><pre># Various hyper-parameters to tune<br>xgbr = XGBRegressor()<br>parameters = {<br>              &#39;objective&#39;:[&#39;reg:squarederror&#39;],<br>              &#39;learning_rate&#39;: [.03, 0.05, .07], #so called `eta` value<br>              &#39;max_depth&#39;: [5, 6, 7],<br>              &#39;min_child_weight&#39;: [4],<br>              &#39;subsample&#39;: [0.7],<br>              &#39;colsample_bytree&#39;: [0.7],<br>              &#39;n_estimators&#39;: [500]}</pre><pre>xgb_grid = GridSearchCV(xgbr,<br>                        parameters,<br>                        cv = 5,<br>                        n_jobs = -1,<br>                        verbose=True)</pre><pre>fitted_xgb = train_and_evaluate(xgb_grid,X_train,y_train,X_test,y_test)</pre><p>We are also going to use hyper parameter tuning method with XGBRegressor with some permutations and combinations of hyper parameters.</p><pre>Train R-2 Score -&gt; 0.6907706227786307<br>Test R-2 Score -&gt; 0.6723572398432<br><br>=============================================<br><br>Train RMSE  -&gt; 2793.9272127493064<br>Test RMSE  -&gt; 2873.5592924067096</pre><p>Well this one stands out to be good. We achieved 67% in test data. We can still achieve more but in next chapters.</p><h3><strong>Conclusion</strong></h3><p>Machine learning can be used for a variety of tasks. In this article, we used a machine-learning algorithm to predict the amount that a customer is likely to spend on Black Friday.</p><p>We went through almost all the stages of <strong>CRISP_DM</strong>, We performed exploratory data analysis to find interesting trends from the dataset and trained the model with different types of machine learning models.</p><p>So, now the question is what retailers can get from all of this?</p><p>Retailers now have analysis reports and a trained model, this will help them to perform clustering on consumers, and based on the cluster’s characteristics can offer various types of discounts. This is how they can attract consumers and reach their target.</p><p>you can find the Notebook <a href="https://github.com/EagleDangar/BlackFriday-prediction">here</a>.</p><h4>Thank you</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16933b8a8bfb" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/black-friday-insights-and-prediction-16933b8a8bfb">Black Friday Insights and Prediction</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>