<?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 Wahyu Sejati Roso on Medium]]></title>
        <description><![CDATA[Stories by Wahyu Sejati Roso on Medium]]></description>
        <link>https://medium.com/@wahyusejatiroso?source=rss-5e2137bd676------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1lPTTbwUyOIWDOhw6tA-hA.jpeg</url>
            <title>Stories by Wahyu Sejati Roso on Medium</title>
            <link>https://medium.com/@wahyusejatiroso?source=rss-5e2137bd676------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:16:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wahyusejatiroso/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[Predicting Customer Churn with PySpark]]></title>
            <link>https://medium.com/@wahyusejatiroso/predicting-customer-churn-with-pyspark-a-deep-dive-into-data-analysis-and-machine-learning-8ec12b0c9438?source=rss-5e2137bd676------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ec12b0c9438</guid>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Wahyu Sejati Roso]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 13:51:59 GMT</pubDate>
            <atom:updated>2023-09-02T08:58:12.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*WiiC8-jbQrPSDof7" /><figcaption><a href="https://www.ttec.com/articles/customer-churn-prevention-3-best-practices-retain-customers">https://www.ttec.com/articles/customer-churn-prevention-3-best-practices-retain-customers</a></figcaption></figure><h3><strong>High-level Overview</strong>:</h3><p>In today’s data-driven business landscape, predicting customer churn stands as a pivotal facet of effective customer relationship management. This blog post embarks on a comprehensive journey to construct a robust customer churn prediction model using PySpark. By delving into data loading, cleaning, exploratory data analysis (EDA), feature engineering, and model evaluation, we harness the potent capabilities of Spark to empower data-centric decision-making.</p><h3><strong>Description of Input Data</strong>:</h3><p>The project centers around the Sparkify Project Workspace from Udacity, providing a curated environment to develop our churn prediction model. The dataset, a subset of the full 12GB dataset (128MB), contains event data in JSON format, capturing user interactions with the Sparkify music streaming service. Variables encompass user attributes, timestamps, session information, and activity events.</p><h3><strong>Strategy for Solving the Problem</strong>:</h3><p>To tackle the sheer size of data &amp; ensure scalability we wont use pandas and scikit learn for developing this model, instead we will use Spark &amp; its machine learning library. The chosen approach involves data cleaning, EDA, and feature engineering to transform raw data into meaningful insights. The models, Decision Tree Classifier, Random Forest Classifier, and Gradient Boosted Tree Classifier, undergo training and evaluation using the F1 score, ideal for imbalanced datasets.</p><h3><strong>Discussion of the Expected Solution</strong>:</h3><p>Our solution encompasses a comprehensive pipeline that integrates data preprocessing, feature engineering, and model training. This streamlined workflow enhances data quality, derives meaningful features, and enables robust model construction. Each step is meticulously designed to address the core challenge of predicting customer churn.</p><h3><strong>Metrics with Justification</strong>:</h3><p>The evaluation of our models relies on the F1 score due to its sensitivity to imbalanced datasets. This metric strikes a balance between precision and recall, aligning with our objective to accurately predict churn while minimizing false positives.</p><h3>Exploratory Data Analysis (<strong>EDA)</strong>:</h3><p>To begin this analysis, it was crucial to determine what constitutes churn in our dataset. We achieved this by identifying events labeled as “Cancellation Confirmation,” which serves as a clear indication of churn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*zR8a5ZMlv_RAjoDonB0ZDw.png" /><figcaption>churn vs not chrun comparison show imbalance label</figcaption></figure><p>The provided data indicates that out of the total customer base, approximately 16.12% (44,864 out of 278,154) churned, while the remaining 83.8% (233,290 out of 278,154) did not churn. This show the dataset contain imbalance churn label.</p><p>Next we start exploring potential feature to predict churn behaviour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*WLs7m_w8eybij9FUf1NIEA.png" /><figcaption>Male customer have higher churn rate compared to female counterpart</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*nGcBxQMbKqx1eCDzB1RemA.png" /><figcaption>Paid customer are substantially more loyal compared to free customer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*MJIfe3cTly7X_Fb4cLb26w.png" /><figcaption>Highest churn rate are in new customer segment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6MPz0qysjP_4eQCPVjtGTA.png" /><figcaption>CUstomer with higher song in session tend to have slightly lower churn rate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*Y6tQpoiKW6Yni0eOwSAtEw.png" /><figcaption>Customer spent more time on song tend to be more loyal</figcaption></figure><p>Based on our exploratory data analysis (EDA), several factors emerge as potentially indicative of whether a customer will churn or not. These factors include gender, user level, length of stay (LoS), and the length of songs listened to.</p><h3><strong>Data Preprocessing</strong>:</h3><p>Data preprocessing encompasses this step</p><ol><li><strong>FilterInvalidUser:<br></strong>Removes entries with ‘auth’ values “Logged Out” or “Guest”.</li><li><strong>CalculateDate:<br></strong>Converts timestamps and registrations to appropriate formats.<br>Computes hours and days since registration.</li><li><strong>GenerateAggregatedFeatures:<br></strong>Creates rolling window features: session count and time spent.</li><li><strong>get_churn_flag:<br></strong>Labels users as churned based on ‘Cancellation Confirmation’.<br>Incorporates churn labels into the main DataFrame.</li></ol><pre>class FilterInvalidUser(Transformer):<br>    ...<br>    def _transform(self, df: DataFrame) -&gt; DataFrame:<br>        return df.where(~f.col(&quot;auth&quot;).isin([&quot;Logged Out&quot;,&quot;Guest&quot;]))<br>    ...<br>    <br>class CalculateDate(Transformer):<br>    ...<br><br>    def _fit(self, df: DataFrame) -&gt; DataFrame:<br>        df = (<br>            df<br>            .withColumn(&#39;activity_timestamp&#39;, f.from_unixtime(f.col(&#39;ts&#39;).cast(LongType())/1000).cast(TimestampType()))<br>            .withColumn(&#39;activity_date&#39;, f.from_unixtime(f.col(&#39;ts&#39;)/1000).cast(DateType()))<br>            .withColumn(&#39;registration_timestamp&#39;, f.from_unixtime(f.col(&#39;registration&#39;).cast(LongType())/1000).cast(TimestampType()))<br>            .withColumn(&#39;registration_date&#39;, f.from_unixtime(f.col(&#39;ts&#39;)/1000).cast(DateType()))<br>            .withColumn(&quot;los_hour&quot;,(f.col(&quot;activity_timestamp&quot;).cast(&quot;long&quot;) - f.col(&quot;registration_timestamp&quot;).cast(&quot;long&quot;))/(3600))<br>            .withColumn(&quot;los_day&quot;,(f.col(&quot;activity_timestamp&quot;).cast(&quot;long&quot;) - f.col(&quot;registration_timestamp&quot;).cast(&quot;long&quot;))/(3600*24))<br>        )<br>        return df<br>    ...<br><br>class GenerateAggregatedFeatures(Transformer):<br>    ...<br>    <br>    def _fit(self, df: DataFrame) -&gt; DataFrame:<br>        i = self.aggregate_window_in_days<br>        days = lambda i: i * 86400<br>        w = Window.orderBy(f.col(&quot;activity_timestamp&quot;).cast(&#39;long&#39;)).rangeBetween(-days(1), 0)<br>        <br>        df = (<br>            df<br>            .withColumn(f&#39;count_activity_{i}d&#39;, f.size(f.collect_set(&quot;sessionId&quot;).over(w)))<br>            .withColumn(f&#39;time_spent_{i}d&#39;, f.sum(&quot;length&quot;).over(w))<br>        )<br>        return df<br>    ...<br>    <br>def get_churn_flag(df):<br>    is_churn_label = (<br>        df<br>        .withColumn(&quot;is_churn&quot;,<br>                    f.when(f.col(&quot;page&quot;)==&#39;Cancellation Confirmation&#39;,f.lit(1))<br>                    .otherwise(f.lit(0)))<br>        .groupby(&quot;userId&quot;)<br>        .agg(f.max(&quot;is_churn&quot;).alias(&quot;is_churn&quot;))<br>    )<br>    ...</pre><h3><strong>Modeling</strong>:</h3><p>Prior to training, we partition 70% of the activity records for training and allocate the remainder for testing. We are using three machine learning models:</p><ol><li>Decision Tree Classifier<strong><br></strong>The Decision Tree Classifier is a widely used classification algorithm that works by recursively partitioning the dataset into subsets based on the most significant attribute at each node.</li><li>Random Forest Classifier<strong><br></strong>The Random Forest Classifier is an ensemble learning method that combines multiple decision trees to improve prediction accuracy and reduce overfitting.</li><li>Gradient Boosted Tree Classifier (GBT)<strong><br></strong>The Gradient Boosted Tree Classifier builds an ensemble of decision trees sequentially, with each tree correcting the errors of its predecessor.</li></ol><h3><strong>Hyperparameter Tuning</strong>:</h3><p>To optimize model performance, hyperparameter tuning is conducted using techniques like grid search on crossvalidated data with 3 number of fold. This process refines the models, enhancing their predictive capabilities and ensuring robustness.</p><pre>models_and_params = {<br>    &quot;GBTClassifier&quot;: (GBTClassifier(), ParamGridBuilder()<br>                      .addGrid(GBTClassifier.maxDepth, [5,10,20])<br>                      .addGrid(GBTClassifier.maxBins, [5,10,20,30])<br>                      .build()),<br>    &quot;RandomForestClassifier&quot;: (RandomForestClassifier(), ParamGridBuilder()<br>                               .addGrid(RandomForestClassifier.maxDepth, [5,10,20])<br>                               .addGrid(RandomForestClassifier.numTrees, [10,30,50,100])<br>                               .build()),<br>    &quot;DecisionTreeClassifier&quot;: (DecisionTreeClassifier(), ParamGridBuilder()<br>                               .addGrid(DecisionTreeClassifier.maxDepth, [5,10,20])<br>                               .addGrid(DecisionTreeClassifier.maxBins, [5,10,20,30])<br>                               .build())<br>}</pre><p>Next we test best parameter for each model on test dataset.</p><h3><strong>Results</strong>:</h3><p>Model evaluation performed on remaining 30% sample (test data) using best parameter from previous step. Results showcase the Gradient Boosted Tree Classifier as the most effective, boasting an F1 score of <strong>0.794</strong>.</p><p>Model Performance Comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*2XDdISbenvyz3T0xZiwdlQ.png" /></figure><h3>Conclusion:</h3><p>While developing this customer churn prediction model using PySpark, we encountered several challenges that are worth highlighting. Here, we discuss these challenges and the solutions we applied to overcome them:</p><ol><li>Data Volume and Scalability<strong><br></strong>Challenge: The dataset provided for this project is a subset of a much larger dataset. Working with the full dataset posed scalability issues, and using traditional data processing libraries like pandas and scikit-learn was not feasible.<br>Solution: To address this challenge, we turned to PySpark, a distributed data processing framework. PySpark’s parallel processing capabilities allowed us to efficiently handle the large dataset by distributing tasks across a cluster of computers. This choice not only ensured scalability but also enabled us to harness the full power of our computing resources.</li><li>Imbalanced Dataset<br>Challenge: Customer churn prediction often involves imbalanced datasets, where the number of users who churn is significantly smaller than those who don’t. This imbalance can lead to skewed model performance.<br>Solution: Recognizing the class imbalance, we made a strategic decision to use the F1 score as our primary evaluation metric. Unlike accuracy, the F1 score considers both precision and recall, making it well-suited for imbalanced datasets. Additionally, we experimented with various machine learning algorithms and hyperparameter tuning to improve model performance on the minority class. This approach ensured that our model could effectively identify and predict churn, even in the presence of imbalanced data.</li><li>Feature Engineering<strong><br></strong>Challenge: Identifying relevant features to predict customer churn was a complex task. Deciding which user attributes and interaction events to include in the model required careful consideration.<br>Solution: We conducted extensive exploratory data analysis (EDA) to gain insights into potential churn indicators. Features such as gender, user level, length of stay, and song-related activities emerged from our EDA as crucial factors. These insights guided our feature engineering efforts.</li><li>Algorithm Selection and Parameter Tuning<strong><br></strong>Challenge:Selecting the right machine learning algorithms and tuning their parameters for optimal performance was a non-trivial task.<br>Solution: We experimented with three classification algorithms: Decision Tree Classifier, Random Forest Classifier, and Gradient Boosted Tree Classifier. We documented our parameter tuning process for each algorithm to provide transparency and enable reproducibility.</li></ol><p>These insights and challenges underscored the importance of not only choosing the right tools and metrics but also the significance of thoughtful data preprocessing and feature engineering. By sharing these specific aspects, we hope to provide a deeper understanding of the intricacies involved in customer churn prediction on large scale data and demonstrate how spark can be utilized to handle the scalability issue.</p><h3>Improvements:</h3><p>Future enhancements could explore additional feature engineering avenues, incorporating device variables, genres played, and song completion rates. These refinements could further elevate the model’s accuracy and predictive capabilities.</p><h3>Acknowledgment:</h3><p>We extend our gratitude to Udacity for providing data &amp; workspace environment for this exploration and all reviewer feedback to improve this post.</p><p>Notebook containing more detail can be found <a href="https://github.com/wsr13990/Sparkify">here</a>.</p><h3>References:</h3><p>*<a href="https://www.analyticsvidhya.com/blog/2020/11/popular-classification-models-for-machine-learning/"><em>Popular Classification Models for Machine Learning</em></a><em><br></em>*<a href="https://www.formpl.us/blog/exploratory-research"><em>Exploratory Research: What are its Method &amp; Examples?</em></a><em><br></em>*<a href="https://spark.apache.org/docs/3.1.1/api/python/reference/pyspark.ml.html"><em>Spark MLlib General Documentation</em></a><em><br></em>*<a href="https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.ml.classification.GBTClassifier.html#pyspark.ml.classification.GBTClassifier"><em>Spark Gradient Boosted Tree Documentation</em></a><em><br></em>*<a href="https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.ml.classification.RandomForestClassifier.html#pyspark.ml.classification.RandomForestClassifier"><em>Spark Random Forest Documentation </em></a><em><br></em>*<a href="http://DecisionTreeClassifier - PySpark 3.1.1 documentation Edit descriptionspark.apache.org"><em>Spark Decision Tree Documentation</em></a><em><br></em>*<a href="https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.ml.Pipeline.html#pyspark.ml.Pipeline"><em>Spark Pipeline Implementation Documentation</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec12b0c9438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airbnb in Seattle vs. Boston: A Comparison of Pricing, Customer Satisfaction, and Superhost Status]]></title>
            <link>https://medium.com/@wahyusejatiroso/airbnb-in-seattle-vs-boston-a-comparison-of-pricing-customer-satisfaction-and-superhost-status-2ce4d204caaa?source=rss-5e2137bd676------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ce4d204caaa</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Wahyu Sejati Roso]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 17:42:17 GMT</pubDate>
            <atom:updated>2023-04-11T06:18:36.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AqpfKu34V6KMFfhk.jpg" /><figcaption>credit: <a href="https://matadornetwork.com/read/airbnb-seattle/">https://matadornetwork.com/read/airbnb-seattle/</a></figcaption></figure><p>In 2016, Airbnb listings increased significantly in Seattle, providing visitors with more lodging options and since some of dataset are publicly available, thus prompting new opportunities for data analysis. This article examines insights from datasets from Airbnb in Seattle during 2016 and compares them to Boston during the same year.</p><h3><strong>1. </strong>Pricing: Seattle vs. Boston</h3><p><em>How is price in Seattle compared to to Boston?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*vRy4LCTl3asthmn7nCWodg.png" /></figure><p><em>What is the dominant type of accommodation in each city, and how is it priced?</em></p><p>Seattle’s Airbnb listings are typically priced between $75 to $150, while Boston’s listings fall within the $85 to $215 range. As for the distribution of prices, Boston has a larger proportion of properties in the higher price range of $200 to $400 compared to Seattle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*N9doP05azzFVqqcg7_yd7A.png" /></figure><p>In Seattle, the majority of listings are for houses, which are almost equally represented as apartments, whereas in Boston, houses only make up less than 20% of listings, with apartments being the dominant property type reaching around 2.6k listing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*5kjlRsG-N0kUU313wSyyng.png" /></figure><p>Aside from House, Seattle’s prices are consistently lower than Boston’s for the same types of properties, such as apartments, condominium, townhouse, and loft.</p><h3><strong>2. Customer Satisfaction</strong></h3><p><em>Based on customer review score, which city have higher customer satisfaction level?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*Jid_OHF9PaPEe5CiAk0Iyw.png" /></figure><p>After analyzing customer satisfaction reviews, it appears that Seattle has a higher overall satisfaction rating compared to Boston. Additionally, Seattle has a larger proportion of reviews with ratings above 90%, indicating a higher level of customer satisfaction than Boston.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*1a2NJXzFqdJC3uWeGR9S2Q.png" /></figure><p>On property type level, both in house &amp; apartment segment, Seattle have average score higher than Boston and with high number of review too.</p><p>This result beg to the next question.</p><p><em>Is higher customer satisfaction due to cheaper price, if not what foctor correlate with it?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0WSce6Bomi5NpGJ5YhxCw.png" /></figure><p>Turns out, price have small correlation with satisfaction. Largest correlating factor mainly on transparency and hospitality qualities, such as cleanliness, communication, check-in, and advertising accuracy. Interestingly those hospitality qualities have higher correlation to review score in Boston compared to Seattle, indicating Boston customer desire those quality more than Seattle.</p><h3><strong>3. Superhost</strong></h3><p>Airbnb have Superhost program, where host will gain more visibility and exclusive reward. To gain Super host status, host must meet the following criteria:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMw5p6w3njwKQz_xsHKH9A.png" /><figcaption>source: <a href="https://www.airbnb.com/d/superhost">https://www.airbnb.com/d/superhost</a></figcaption></figure><p>Inline with previous analysis about customer experience, this raise question from customer perspective.</p><p><em>Is there any difference between Superhost and Non-Superhost for in term of price and rating?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Id_zPp7hiybPbgzYsoyag.png" /></figure><p>For majority of segment such as apartment &amp; house, pricing are relatively similar. Although there is some exception such as Seattle’s townhouse &amp; condominium where price spread are more wide &amp; price median is higher on Superhost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FdrOis7nU11nGzM1e8g1bA.png" /></figure><p>As expected Superhost have more consistent rating, which can be seen seen in smaller standard deviation &amp; higher minimum rating column. This is expected since they have obligation to maintain overall rating and keep cancellation rate below 1%.</p><h3>Conclusion</h3><p>In conclusion, the comparison of Airbnb data from Seattle and Boston in 2016 provided following insights:</p><ol><li>While Seattle had more affordable pricing for all types of properties compared to Boston, Boston had a larger proportion of high-end properties in the $200-$400 price range.</li><li>Seattle had a higher overall satisfaction rating compared to Boston, with transparency and hospitality qualities being the main factors correlating with higher review scores in both cities. Interestingly, Boston customers seem to prioritize these qualities more than Seattle customers.</li><li>Additionally, the Superhost program had a positive impact on the consistency of ratings for both cities, with some variations in pricing for specific property types. Overall, the analysis highlights the importance of customer experience and hospitality qualities in the Airbnb industry, as well as the potential benefits of the Superhost program for both hosts and guests.</li></ol><p>For additional information regarding this analysis, you can check out the link provided to my Github <a href="https://github.com/wsr13990/airbnb_seattle_boston_2016">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ce4d204caaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Product & Allocation Optimization Process]]></title>
            <link>https://medium.com/@wahyusejatiroso/product-allocation-optimization-process-fcb72030b80a?source=rss-5e2137bd676------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcb72030b80a</guid>
            <category><![CDATA[product-experimentation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Wahyu Sejati Roso]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 14:12:59 GMT</pubDate>
            <atom:updated>2023-01-01T14:12:59.361Z</atom:updated>
            <content:encoded><![CDATA[<p>Offering customer centric product requires two key optimized element, what is the best <strong>product</strong> to offer &amp; to <strong>which customer</strong> will it be offered (allocation). First problem can be solved with product experiment &amp; second problem using machine learning (ML) model.</p><p>Product experiment is a process to test newly designed product in controlled environment &amp; on small subset of customer. Generally, the main objective is to assess product attractiveness, viability &amp; how its perceived by customer.</p><p>Another objective of product experimentation is to assess new product with predefined baseline, such as how the newly constructed product (challenger) will compare with current product (champion).</p><p>End to end optimization process can be summarized as follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*SyuJnXJKpj_Dw4rHhKsCCg.png" /><figcaption>General Product &amp; Allocation Optimization Process</figcaption></figure><h4>Product Optimization</h4><p>Optimization on product side can be solved with setting up product experimentation. Product experimentation mainly consist following steps:</p><ul><li><strong>Define product goal</strong>. First of, we determine what is the objective of new product &amp; how its impact on customer.</li><li><strong>Formulating hypotheses.</strong> Based on specified goals, we detailing expected result into more specific, testable &amp; measurable hypotheses.</li><li><strong>Determine relevant metrics</strong>. Given initial hypotheses, determine what is the relevant metric to measure in order to prove or disprove the hypotheses.</li><li><strong>Designing experiment</strong>. When designing product experiment we need to sample customer into two separate group, treatment &amp; control group These two separate group must be homogeneous (similar characteristic).<br>- <strong>Treatment group. </strong>Customer are offered with newly constructed product or champion.<br>- <strong>Control group.</strong>Customer are not offered with any product or instead offered with current champion product.<br>Other things to consider is the time-frame of experiment &amp; ensure each experiment group have sufficient sample size to prove or disprove the initial hypotheses.</li><li><strong>Develop product and execute experiment. </strong>After designing the experiment, next step is to construct live product for experiment and then deploy it on customer sample defined in experiment design.</li><li><strong>Evaluate result. </strong>Last step is analyze experiment result on predefined relevant metric and prove or disprove the initial hypotheses.</li></ul><p>The output of product experimentation is new champion product. After solving product optimization, next step is allocation optimization.</p><h4>Allocation Optimization</h4><p>One possible approach to solve allocation optimization is by using machine learning model trained on product experimentation data generated earlier and then evaluate it by backtest it on product experiment generated data. Training allocation model, generally consist of the following steps:</p><ul><li><strong>Prepare training, validation &amp; test data</strong>. First step is to split sample data for each product into training, validation &amp; test data. In case product experimentation is done in multiple iteration &amp; time window, its a good idea to split them into train, test &amp; out of time (OOT) portion. OOT data should be in separate iteration with no overlapping time window with train &amp; validation.</li><li><strong>Training ML model</strong>. Training ML model on train portion &amp; use validation to ensure there is no severe over-fitting symptom.</li><li><strong>Backtest and evaluation</strong>. Use test/OOT data from new champion with newly trained model &amp; compare it with previous champion &amp; previous allocation method. Performance comparison is done by only pick customer with actual product allocation allocation equal with model prediction. Additional note, don’t forget to ensure homogeneity between OOT / validation sample with control group.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*wP7ntwMRvl56TXyflr4hvw.png" /></figure><p>After we get the optimum product &amp; optimum allocation method, next we can gradually scale up and test newly optimized product &amp; allocation method on larger sample.</p><p><strong>References:</strong></p><p><a href="https://www.hotjar.com/product-experimentation/framework/">https://www.hotjar.com/product-experimentation/framework/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcb72030b80a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facial Keypoint Detection with Openvino]]></title>
            <link>https://medium.com/@wahyusejatiroso/facial-keypoint-detection-with-openvino-e58fec8be8d1?source=rss-5e2137bd676------2</link>
            <guid isPermaLink="false">https://medium.com/p/e58fec8be8d1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[openvino]]></category>
            <dc:creator><![CDATA[Wahyu Sejati Roso]]></dc:creator>
            <pubDate>Fri, 27 Dec 2019 02:24:17 GMT</pubDate>
            <atom:updated>2019-12-27T02:45:34.031Z</atom:updated>
            <content:encoded><![CDATA[<p>In facial keypoint detection, we try to predict where the key facial features are located. There are 34 point we are trying to predict and detail of what each point represent can be found <a href="https://docs.openvinotoolkit.org/latest/_models_intel_facial_landmarks_35_adas_0002_description_facial_landmarks_35_adas_0002.html">here</a>. To perform those task, we will be using Openvino.</p><p>Openvino is a computer vision toolkit developed by Intel which focused on model deployment on the edge. It means the model inference is performed in decentralized manner and on the front end device, rather than server side.</p><p>Openvino leverage the use of pretrained model for various computer vision task in Model Zoo, which can be used right away. Pretrained model in the Model Zoo have been optimized for inference process on Intel hardware.</p><p>In case our model doesn’t exist in the Model Zoo, we can still use it by converting it first to it’s intermediate representation (IR). Model optimizer can convert model from various framework, such as Tensorflow, Pytorch, Caffe etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*q9u1hB6Srximw1_d7S2_5w.png" /><figcaption><a href="https://software.intel.com/en-us/openvino-toolkit/deep-learning-cv">openvino overview</a></figcaption></figure><p>Luckily for facial key point detection task, there are model we can use right away in the model zoo. We will use <strong>facial-landmarks-35-adas-0002</strong> from the model zoo. We will use model with precision 16 floating point (FP16).</p><pre>#Change with the model downloader path and desired output path<br>output_dir=/home/workspace/model<br>openvino_dir=/opt/intel/openvino/deployment_tools/tools/model_downloader<br>sudo $openvino_dir/downloader.py --name facial-landmarks-35-adas-0002 -o $output_dir --precisions FP16</pre><ul><li>.xml: Describes the network topology</li><li>.bin: Contains the weights and biases binary data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*57M8JXUxHX23Ml6Dm9OeRg.png" /></figure><p>I use the inference code from Intel® Edge AI Scholarship Foundation Course Nanodegree Program.</p><p>To perform inference, we need to use IENetwork and IECore from openvino inference engine.</p><pre>import os<br>import sys<br>import logging as log<br>from openvino.inference_engine import IENetwork, IECore</pre><pre>class Network:<br>    def __init__(self):<br>       self.plugin = None<br>       self.network = None<br>       self.input_blob = None<br>       self.output_blob = None<br>       self.exec_network = None<br>       self.infer_request = None<br>    ...</pre><blockquote><a href="https://docs.openvinotoolkit.org/2019_R3.1/classie__api_1_1IENetwork.html">IENetwork</a>: This class contains the information about the network model read from IR and allows you to manipulate with some model parameters such as layers affinity and output layers</blockquote><blockquote><a href="https://docs.openvinotoolkit.org/2019_R3.1/classie__api_1_1IECore.html">IECore</a>: This class represents an Inference Engine entity and allows you to manipulate with plugins using unified interfaces</blockquote><p>Full documentation can be found <a href="https://docs.openvinotoolkit.org/2019_R3.1/ie_python_api.html">here</a>.</p><p>Next we need to initialize the inference engine and then load the IR model.</p><pre>class Network:<br>   ...<br>   def load_model(self, model, device=&quot;CPU&quot;, cpu_extension=None):<br>      # Initialize the plugin<br>      self.plugin = IECore()</pre><pre>      # Add a CPU extension, if applicable<br>      if cpu_extension and &quot;CPU&quot; in device:<br>         self.plugin.add_extension(cpu_extension, device)</pre><pre>      # Read the IR as a IENetwork<br>      self.network = IENetwork(model=model_xml, weights=model_bin)</pre><pre>      # Load the IENetwork into the plugin<br>      self.exec_network = self.plugin.load_network(self.network,\ device)</pre><pre>      # Get the input layer<br>      self.input_blob = next(iter(self.network.inputs))<br>      self.output_blob = next(iter(self.network.outputs))<br>      return<br>   ...</pre><p>For streaming input, we will use async inference and extract the output when it’s done.</p><pre>class Network:<br>   ...<br>   def async_inference(self, image):<br>      #Makes an asynchronous inference request, given an input image.<br>      self.infer_request = self.exec_network.start_async(<br>      request_id=0, inputs={self.input_blob: image})<br>      return</pre><pre>   def wait(self):<br>      #Checks the status of the inference request.<br>      status = self.exec_network.requests[0].wait(-1)<br>      return status</pre><pre>   def extract_output(self):<br>      #Returns a list of the results for the output layer of the       network.<br>      res = self.exec_network.requests[0].outputs[self.output_blob]<br>      return res<br>   ...</pre><p>Let’s prepare the setup for inference using video stream from webcam. To use webcam we use 0 argument in the OpenCV video capture function.</p><pre>#Path to IR model xml<br>ir_model = &#39;D:/facial_keypoint/models/intel/facial-landmarks-35-adas-0002/FP16/facial-landmarks-35-adas-0002.xml&#39;</pre><pre>def capture_stream(args):<br>   ...<br>   plugin = Network()<br>   face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades+ &quot;haarcascade_frontalface_default.xml&quot;)<br>   plugin.load_model(ir_model, &#39;CPU&#39;)<br>   net_input_shape = plugin.get_input_shape()</pre><pre>   #Argument 0 to use video stream from webcam<br>   cap = cv2.VideoCapture(0)</pre><pre>   # print(net_input_shape)<br>   model_width = int(net_input_shape[2])<br>   model_height = int(net_input_shape[3])<br>   ...</pre><p>Before feeding the video to the inference engine we need to preprocess it first. We will use haarcascade classifier to detect face area and then feed forward it to pretrained model.</p><pre>def capture_stream(args):<br>   ...<br>   while cap.isOpened():<br>      cv2.namedWindow(&quot;facial_keypoint_detection&quot;)<br>      flag, frame = cap.read()<br>      faces = face_cascade.detectMultiScale(frame, 1.2, 2)</pre><pre>      if faces is not None:<br>         for (ix, iy, w, h) in faces:<br>            #Crop face detected<br>            face_image = frame[iy:iy+h, ix:ix+w]<br>            <br>            # Draw rectangle around face<br>            frame = cv2.rectangle(<br>            frame, (ix, iy), (ix+w, iy+h), color, int(args.lw))<br>            <br>            face_width = face_image.shape[1]<br>            face_height = face_image.shape[0]<br>            <br>            #Resize cropped face to match IR input size<br>            face_image = cv2.resize(face_image, (model_width, model_height))<br>            face_image = face_image.transpose((2, 0, 1))<br>            face_image = face_image.reshape(1, *face_image.shape)<br>   ...</pre><p>After preprocessing the input stream, we can start performing inference and displaying the predicted keypoints.</p><pre>def capture_stream(args):<br>   ...<br>   flag, frame = cap.read()<br>   ...<br>   while cap.isOpened():<br>      ...<br>      plugin.async_inference(face_image)<br>      if plugin.wait() == 0:<br>         result = plugin.extract_output()<br>         for i in range(0, result.shape[1], 2):<br>            x, y = int(ix+result[0][i]*ori_width), iy+int(result[0][i+1]*ori_height)<br>            # Draw Facial key points<br>            cv2.circle(frame, (x, y), 1, color, int(args.kw))<br>   if not flag:<br>      break<br>   key_pressed = cv2.waitKey(60)<br>   cv2.imshow(&quot;facial_keypoint_detection&quot;, frame)<br>   cap.release()<br>   cv2.destroyAllWindows()</pre><p>Here are the sample result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*YBQwPWV6rQZf64DDrYl4FQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e58fec8be8d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>