<?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 Nazrul Miya on Medium]]></title>
        <description><![CDATA[Stories by Nazrul Miya on Medium]]></description>
        <link>https://medium.com/@nazrul-miya91?source=rss-a0a9a26a10d6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_fG0uTWJR_nvoBJ_</url>
            <title>Stories by Nazrul Miya on Medium</title>
            <link>https://medium.com/@nazrul-miya91?source=rss-a0a9a26a10d6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:44:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nazrul-miya91/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[Customer Churn — Chapter 1: Understanding Churn from a Business Perspective]]></title>
            <link>https://nazrul-miya91.medium.com/customer-churn-chapter-1-understanding-churn-from-a-business-perspective-5415a27452ec?source=rss-a0a9a26a10d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5415a27452ec</guid>
            <category><![CDATA[customer-churn-prediction]]></category>
            <category><![CDATA[churn-analysis]]></category>
            <dc:creator><![CDATA[Nazrul Miya]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 12:57:59 GMT</pubDate>
            <atom:updated>2026-02-17T12:57:59.869Z</atom:updated>
            <content:encoded><![CDATA[<p>In this write-up , we will first understand customer churn from the perspective of a business person.</p><p>Before we talk about data, models, or algorithms, it is important to understand churn as a business reality.</p><p>Every organization — whether it is a bank, a retail brand, a telecom provider, or a subscription platform — operates with a simple expectation: customers will continue to stay, engage, and generate value over time. Customer acquisition is celebrated as growth. <strong><em>But true business stability is defined not by how many customers join, but by how many choose to stay.</em></strong></p><p>This is where the concept of churn becomes critically important.</p><h3><strong>What is Customer Churn??</strong></h3><p>Customer churn refers to the moment when a customer stops doing business with a company. It is not always announced. There is no formal goodbye. Sometimes, it is simply a customer who never returns, never renews, or never logs in again.</p><p>And yet, churn is one of the most powerful signals about the health of a business.</p><ul><li>It signals customer dissatisfaction.</li><li>It signals declining engagement.</li><li>It signals potential revenue loss.</li><li>And most importantly, it signals risk to future growth.</li></ul><p>What makes churn especially important is its compounding effect. Losing customers today reduces revenue tomorrow, weakens customer base stability, and increases pressure on acquisition teams to replace those losses.</p><h3><strong>Churn Looks Different in Every Industry</strong></h3><p>Churn is not defined by a single action. Its definition depends on the business model and how customers interact with the company.</p><h4><strong>Banking and Financial Services (BFSI)</strong></h4><p>In banking, churn is rarely explicit. Customers do not always close their accounts. Instead, they disengage silently.</p><p>A churned customer in BFSI might be someone who:</p><ul><li>Stops using their credit card</li><li>Moves their salary account to another bank</li><li>Withdraws funds and leaves the account dormant</li><li>Stops transacting for a defined period (e.g., 90 or 180 days)</li></ul><p>The account exists. But the relationship is gone.</p><p>This type of churn is particularly dangerous because it is invisible unless actively measured.</p><h4>Retail Industry</h4><p>In retail, churn is defined by the absence of repeat purchases.</p><p>If a customer who used to shop regularly suddenly stops buying, they are considered churned.</p><p>For example:</p><ul><li>A customer who purchased every month but hasn’t purchased in the last 6 months</li><li>A loyalty program member who stopped visiting stores</li><li>An online shopper who never returned after initial purchases</li></ul><p>Retail churn reflects declining customer engagement and loyalty.</p><h4>Subscription-Based Businesses</h4><p>Subscription businesses have the clearest definition of churn. Here, churn occurs when a customer actively cancels or fails to renew their subscription.</p><p>Examples include:</p><ul><li>Cancelling a Netflix subscription</li><li>Ending a SaaS software contract</li><li>Not renewing a gym membership</li><li>Unsubscribing from a digital service</li></ul><p>In subscription models, churn directly translates to immediate revenue loss.</p><h4>Telecommunications</h4><p>In telecom, churn happens when customers switch providers.</p><p>Examples include:</p><ul><li>Porting a mobile number to another operator</li><li>Cancelling an internet service</li><li>Moving to a competitor offering better pricing or service</li></ul><p>Telecom companies track churn aggressively because acquiring a new customer can cost five to seven times more than retaining an existing one.</p><h3>Why Churn Matters More Than Acquisition?</h3><p>Most companies invest heavily in acquiring new customers. Marketing campaigns, promotions, onboarding journeys — all designed to bring customers in.</p><p>But sustainable growth is not defined by how many customers you acquire. It is defined by how many you retain.</p><p>A business that acquires 10,000 customers but loses 9,000 is not growing. It is leaking. Churn is that leak.</p><p>And unless it is measured, understood, and predicted, it quietly erodes revenue, profitability, and long-term stability.</p><h3>The Cost of Ignoring Churn</h3><p>Consider this simple reality:</p><p>Improving customer retention by just 5% can increase profits by 25% to 95%.</p><p>Not because new customers are unimportant. But because retained customers:</p><ul><li>Spend more</li><li>Trust more</li><li>Cost less to serve</li><li>And stay longer</li></ul><p><strong><em>Retention is not just a metric. It is a strategy.</em></strong></p><h4>Business Scenario: Credit Card Portfolio of a Mid-Size Bank</h4><p>Imagine A bank has <strong>100,000 active credit card customers</strong>, and each customer generates an average revenue of <strong>$15 per month</strong> through transaction fees, interest, and interchange income.</p><p>This means the bank generates:</p><p>Monthly Revenue = 100,000 × $15 = $1.5 Million per month</p><p>Now consider two scenarios:</p><h4>Scenario 1: Bank Ignores Churn</h4><p>The bank focuses primarily on acquisition and does not actively monitor or manage churn.</p><p>Over time:</p><ul><li>Customers gradually stop using their cards</li><li>Monthly churn rate reaches approximately 5%</li><li>Acquisition efforts bring in new customers, but not enough to offset losses</li><li>Active customer base declines steadily</li></ul><p>As shown in the plot below, monthly revenue drops from $1.5 Million → $0.8 Million within 24 months</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*Wo1-xUNtwdlwHQf61qlTMQ.png" /></figure><p>This is nearly a <strong>47% decline in revenue</strong>, despite continuous acquisition.</p><p>Over two years, total revenue generated: <strong>$25.38 Million</strong></p><h4>Scenario 2: Bank Actively Manages Churn</h4><p>Now consider a bank that invests in churn management using:</p><ul><li>Early warning systems</li><li>Customer behavior monitoring</li><li>Retention campaigns</li><li>Personalized offers for at-risk customers</li></ul><p>As a result:</p><ul><li>Churn reduces from 5% to 2%</li><li>Customer base stabilizes and gradually grows</li><li>Revenue increases over time</li></ul><p><strong><em>Monthly revenue grows from: $1.5 Million → $1.63 Million</em></strong></p><p><strong><em>Total revenue over two years: $37.09 Million</em></strong></p><h4>Hence Financial Impact of Ignoring Churn</h4><p>The difference between the two scenarios:</p><p><strong>Revenue Lost Due to Ignoring Churn = $11.7 Million in just 24 months</strong></p><p>This loss occurs without any operational failure, market crash, or economic downturn. It happens purely due to customer disengagement.</p><h3>The Role of Data Science in Churn</h3><p>Churn analysis answers three fundamental questions:</p><ol><li><strong>Who has churned?</strong> — Historical analysis</li><li><strong>Why did they churn?</strong> — Behavioral and causal analysis</li><li><strong>Who is likely to churn next?</strong> — Predictive modeling</li></ol><p>In the next journal (PART 2) , we will explore churn from a data science perspective.</p><p>We will move beyond definitions and dive into:</p><ul><li>How churn is defined mathematically</li><li>How churn datasets are structured</li><li>How features are engineered from behavioral data</li><li>How machine learning models predict churn</li><li>And how churn models drive real business decisions</li></ul><h4>Author,</h4><p><strong>Nazrul Miya, AVP in Data Science &amp; Machine Learning, </strong><a href="https://www.linkedin.com/in/nmiya"><strong>https://www.linkedin.com/in/nmiya</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5415a27452ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shapely Value & Feature Importance]]></title>
            <link>https://nazrul-miya91.medium.com/shapely-value-feature-importance-4e90a0ca7374?source=rss-a0a9a26a10d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e90a0ca7374</guid>
            <category><![CDATA[feature-importance]]></category>
            <category><![CDATA[feature-attribution]]></category>
            <category><![CDATA[shapely-values]]></category>
            <category><![CDATA[local-feature-importance]]></category>
            <dc:creator><![CDATA[Nazrul Miya]]></dc:creator>
            <pubDate>Wed, 07 Jul 2021 18:40:38 GMT</pubDate>
            <atom:updated>2021-07-07T18:40:38.608Z</atom:updated>
            <content:encoded><![CDATA[<p>A solution concept in cooperative game theory</p><p>A machine learning model is trained on a set of features (x1, x2, x3, … xn), and the model predicts an outcome when feature values are provided. Now the question is how do you explain why the model has predicted an outcome P, not Q? or Which feature value influencing the model to predict P over Q? The answer to these questions is <strong>‘Feature Importance’ that helps to inspect a model by understanding the feature contributions towards the model’s prediction. </strong>The story will explain a popular solution concept used to find feature importances.</p><h4><strong>Shapely Value</strong></h4><p>The backbone of the feature attribution is a concept in cooperative game theory called <strong>“Shapely Value”. In a cooperative game </strong>( a competition that involves players and each player contributes towards winning the competition),<strong> shapely value is a concept to find a unique distribution of a total reward generated by the involvement of these players. </strong>In a game theory, a game can be anything that involves participants, and each participant contributes towards reaching its goal. For example, running a business can be considered as a game where owners, co-owners, other staffs contribute towards generating revenue.</p><p>Let&#39;s imagine two entrepreneurs named <em>Enp-1, </em>and <em>Enp-2</em> are running a startup, consider this as a cooperative game because both are cooperatively involved in the business. When the startup is managed only by Enp-1, the revenue generated is $25K. When only Enp-2 managed the operations in the startup, revenue generated is $50K. And when both of them cooperatively managed the operations then the revenue generated by the startup grows to $80K. The shapely value represents an allocation of revenue to the entrepreneurs depending on their marginal contributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*Sx1N3gA4PPebBxT_nlj2wA.png" /></figure><p>Marginal Contribution represents the true contribution of a particular player when the player joins others in a game. It is the difference between the reward received by the game with the specific player and without that player.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*4s7br61mTQlxP42vgWa0bQ.png" /></figure><p>Shapely values are derived from an individual&#39;s marginal contribution. More the contribution, the bigger the allocation of reward or shapely value.</p><h4>Shapley value in feature importance</h4><p>Shapely value provides a way to explain predictions of a machine learning model. A model is trained on a dataset with a set of features. The phenomenon Shapely value provides a way to compute the fair contribution of each feature in the model’s prediction. It helps to interpret which feature has a high influence on the prediction. Think a feature like a player in game theory and model’s prediction is the same as reward or earnings in a game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*MM5ZJogaxFQ1DFzcxCcuMw.png" /></figure><p>Consider a model is trained on a feature set F. The marginal contribution of adding a feature at a time can be calculated similarly as in the case of a game theory. These marginal contributions(MC) are actually the difference between the model’s prediction with and without the feature. Shapely value or allocation unit can then be derived from these marginal contributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*TAwAjZIyNKIqqnmiUgrUgw.png" /></figure><p>In the above computation of MC, features are added sequentially one at a time. What if the order of adding a feature is changed? for example what if feature <em>X3</em> is included before the feature <em>x1? </em>The plot on the left shows marginal contributions when features are added in order<em> x1, x2, and x3.</em> The right plot shows the MCs when orders are changed. When orders are changed, it may change the marginal contributions. Hence All possible combinations of features and orders need to be considered when finding MCs and thereby Shapely values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*zuwFG5xTe7K3xEBzJ247Lw.png" /><figcaption>Shapely Value Equation</figcaption></figure><h4>Local feature importance</h4><p>By now we understand that MC is the difference between model’s prediction with and without a specific feature being included and a specific data instance is used for the prediction. This is referred to as <em>‘local feature importance’.</em> Shapely value captures feature importance for a specific prediction case. shapely values differ for different sets of values of the corresponding features.</p><h4>Dependency Plot</h4><p>The plot helps to understand the <strong>local feature importance. </strong>In the plot, the x-axis is a particular feature, and the y-axis represents the shapely values for that feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*LnIJGNUXnsSwh9CfV02q3w.png" /><figcaption>Dependency Plot</figcaption></figure><p>Consider the plot in the left is a dependency plot where it shows the local feature importance summary of a feature <em>‘Hours per week’</em>. The plot shows that for low values of feature <em>‘Hours per week’, </em>the feature has low shapely values, which means the feature has a low impact on the model’s prediction when feature values are in the low range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*rwn35pVhSEIKM81DvIt7qw.png" /></figure><p>The plot on the left shows features importance scores when a single data instance (a row) is used for the model’s prediction. feature ‘Capital Gain’ has a high positive impact on the model’s output and feature ‘Age’ has a highly negative impact on the model’s prediction. It means both these features are important in the model. The plot on the right explains the average impact of each feature across the dataset. In the plot, feature ‘Age’ has the highest impact (positive and negative) on the model’s prediction.</p><p>Google cloud’s service ‘AI Explanations’ uses the shapely value theory to provide an explanation (feature attribution) of a model deployed in the google cloud’s AI Platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e90a0ca7374" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explainable AI — using google cloud (Demo)]]></title>
            <link>https://nazrul-miya91.medium.com/explainable-ai-using-google-cloud-demo-b55f56a96ec8?source=rss-a0a9a26a10d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b55f56a96ec8</guid>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[gcloud-ai-explanation]]></category>
            <category><![CDATA[ai-explanation]]></category>
            <dc:creator><![CDATA[Nazrul Miya]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 12:45:28 GMT</pubDate>
            <atom:updated>2021-07-02T16:45:34.771Z</atom:updated>
            <content:encoded><![CDATA[<h3>Explainable AI — AI Explanation Service by google cloud (Part 1)</h3><p>This is my 4th story and this time is about ‘explainable AI’. The story will demonstrate using google cloud-backed explainable ai. I have separated the article into two parts — the first starts with practical implementation and the second part explains the concept behind google cloud’s explainable AI. By the end of these stories, one can get a clear idea about <strong>what is explainable AI ? how google cloud’s AI explanation service helps to explain your model.</strong></p><p><strong>If you like the story please hit a clap and share :) Also, follow me for more such stories. :).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*oRNHJRIuc5ZjubqY2o_29w.png" /><figcaption>High-level steps</figcaption></figure><p>I will start with building a TensorFlow classification model, which will then be deployed into the google cloud’s AI platform. Finally, will get predictions and explanations from the model.</p><p><strong>Example Dataset: Loan prediction dataset. </strong>The dataset captures information on loans taken by customers. The task is to build a binary classification model to predict if a loan can be granted, given the customer’s details.</p><h3><strong>1. Building the TensorFlow model</strong></h3><p>Note: Main focus is on explanations of the model, hence just built a basic TensorFlow model without much emphasizing preprocessing, analysis, hyperparameter tuning, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*OAgDtFRQNcPb9Ychui1Akg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*ZyGs5hoDVfJeUaFCfLPv_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*KyC79CwDP9rYmTpJiJgY-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*-KCc_iT86voNxjBoy619fg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*yXF7SFlBus5tbW3rgIy0Mw.png" /></figure><p>Now a TensorFlow model is ready to predict loan status when customer details are provided.</p><p>The next step is to deploy the model into google cloud service — AI Platform.</p><h3>2. <strong>Deploy TensorFlow model to google AI platform</strong></h3><h4>Prerequisites:</h4><ol><li>One must have a valid google cloud(GC) Account. (<em> </em><a href="https://cloud.google.com/"><em>create a gcp account</em></a> )</li><li>A project must be created in GC. (<a href="https://cloud.google.com/resource-manager/docs/creating-managing-projects#console"><em>create a project</em></a> )</li><li>A billing account must be linked to the project. ( <a href="https://cloud.google.com/billing/docs/how-to/modify-project">link billing to project</a> )</li><li>Enable ‘AI Platform prediction &amp; Training’ API service for the created project, so that the AI platform can be used in the project. ( <a href="https://cloud.google.com/endpoints/docs/openapi/enable-api">enable API service </a>)</li><li>A storage bucket is created for storing the TensorFlow model. (<a href="https://cloud.google.com/storage/docs/creating-buckets#storage-create-bucket-console">create a google cloud storage</a>)</li></ol><p>I have followed the above prerequisite steps and finally, I have a project id <em>(nm-xai-demo)</em> and storage bucket <em>(xai-demo-bucket)</em> to proceed with the deployment.</p><p>The following steps are involved in deploying a model to the AI platform.</p><h4>a. Set project resource</h4><p>In google cloud, the root of the resource&#39;s hierarchy is a project, all other resources are mapped to the root. To deploy the TensorFlow model, I will access the google ai platform service from the notebook, and the ai platform service is enabled for the project I created in prerequisite step 2. Hence I need to set the right project in the notebook as an environment variable, it ensures that all the google cloud resources are being accessed from the notebook mapped to the set project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*Z6U0jZ15WORbZtKwfLOrzg.png" /></figure><h4>a. Authenticate a google cloud account from the notebook</h4><p>To access google cloud resources such as AI platform, storage, etc, the google cloud account needs to be authenticated. Below code, snippet authenticates google cloud account through google oAth access token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*0wEzUDjw9JjfYlAICOjStw.png" /></figure><p>Verification code can be generated upon clicking the link and then by authenticating through a google cloud account</p><h4>c. Save the model into the storage bucket</h4><p>The next step is to save the TensorFlow model into the created storage bucket ‘xai-demo-bucket’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*lR5TGN4eJpxKafCghaxYlg.png" /></figure><p>Now the TensorFlow model is stored at the storage bucket location <em>‘gs://xai-demo-bucket/xai/models/assets’</em></p><h4>d. Create a model resource in the AI platform</h4><p>The next step is to create a model resource in the AI platform which is a container of all versions of the trained models. Each version is linked to the model file saved in the storage bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*UHeIhwr9V6hbz7i6Yq344A.png" /><figcaption>Model resource creation in AI platform</figcaption></figure><h4>d. Create a version resource in the AI platform</h4><p>A version is to be linked to a model saved in a storage bucket. Will create a version providing the model path.</p><p>The region, model path in google cloud storage, and model name are to be provided while creating a version of the model. Optionally frameworks such as TensorFlow/scikit-learn, python version, framework version can be set while creating the version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*G_jgg5xU0WtOoouBAkiDIw.png" /><figcaption>Creating a version</figcaption></figure><p>Google AI explanations use different types of explanations such as <strong>“sampled-shapley”, “integrated-gradients”, or “xrai”. This explanation type is provided while creating the version, through the parameter ‘explanation-method’. </strong>I will explain these explanation methods theory in the next story<strong>. </strong>For the practical demo, I used the explanation method <strong>“integrated-gradients”.</strong></p><p>For more run time versions <a href="https://cloud.google.com/ai-platform/training/docs/runtime-version-list">check here</a></p><p>For more machine types <a href="https://cloud.google.com/ai-platform/training/docs/machine-types#compute-engine-machine-types">check here</a></p><p>Now, let&#39;s verify the model resource and version resource created in the last two steps,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*vpUOhUv_gVFgLYS6hWqYqA.png" /><figcaption>Version consfiguartions</figcaption></figure><p>Let&#39;s summarise what I did so far — created a TensorFlow model to predict loan status given customer details, the model is then saved in google cloud storage bucket, next a model resource named <em>‘loan_pred_model’</em> is created in google cloud AI platform, and a version<em> ‘v1’</em> is linked to the model resource.</p><p>The next step is to get an explanation from the TensorFlow model which deployed in the AI platform.</p><h3>3. Get an explanation from the model</h3><p>Explanation from the TensorFlow model deployed in AI platform can be achieved through <strong>google provided python sdk ‘explainable-ai-sdk’</strong></p><h4>a. Download explainable ai SDK</h4><blockquote><strong>explainable-ai-sdk</strong> is a Python SDK for <a href="https://cloud.google.com/explainable-ai">Google Cloud Explainable AI</a>, an explanation service that provides insight into machine learning models deployed on <a href="https://cloud.google.com/ai-platform">AI Platform</a>. The Explainable AI SDK helps to visualize explanation results, and to define <em>explanation metadata</em> for the explanation service. it is an interface which helps to communicate more easily with models deployed in AI platform.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlQqLy-cu1ARjCB0xuGnnw.png" /></figure><p>The Explainable AI SDK supports models built with:</p><ul><li>Python 3.7 and later</li><li>TensorFlow 1.15 or TensorFlow 2.x.</li></ul><h4>b. Build model metadata</h4><p>an explanation metadata JSON file ‘explanation_metadata.json’ must be created and saved in the same path where the TensorFlow model is saved in google cloud storage. The JSON should contain information about the TensorFlow model such as the input of the model, output by the model, any baseline, etc. <em>explainable-ai-sdk</em> uses the configurations in the metadata file to interact with the model and provide explanations.</p><p>the <em>explainable-ai-sdk </em>also helps to create this explanation metadata file for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*SurLOzC3hrwrIqAujsalfQ.png" /><figcaption>importing explainable_ai_sdk</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*tNDSdhjrRZTcvsHVh1_9Qg.png" /><figcaption>Generating model metadata</figcaption></figure><h4>c. Save model metadata</h4><p>The next step is to save the generated model metadata into a cloud storage bucket, where the TensorFlow model is saved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*hGLb1MLzaU4BZRGWCNVOMw.png" /><figcaption>saving metadata to the bucket</figcaption></figure><p>The function <em>save_metadata() </em>creates an <em>explanation_metadata.json </em>file and writes metadata configurations into that file.</p><h4>d. Configure explanation type</h4><p>Google AI explanations use different types of explanations such as <strong>“sampled-shapley”, “integrated-gradients”, or “xrai”. I will explain these explanation methods theory in the next story.</strong></p><p>For the practical demo, let&#39;s use the explanation method <strong>“integrated-gradients”. The method has to be updated in the version resource <em>‘v1’</em>.</strong></p><p>If the explanation method has not been set while creating the version, then the parameter can be updated through an update request. The parameter has to be written in a YAML file and the file path to be provided in the update request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*SeCkEyJ81fMYim9zen6vpw.png" /><figcaption>Updating explanation method</figcaption></figure><h4>e. Prepare test data</h4><p>The aim is to get explanations from the model for given test data instances. Now it is time to prepare the test data instances for getting the explanations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*S-DG9IT9efnsZzW8Ncv0Sw.png" /><figcaption>Loading and preprocessing test data instances</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*Kd1MAnrTWSLxqan6UQCtlA.png" /></figure><h4>f. Load model resource from AI platform</h4><p>The TensorFlow model was deployed in the AI platform by creating a model resource and a version resource. The version resource internally points to the actual TensorFlow model stored in the bucket.</p><p>To get predictions or explanations, this model resource has to be exported to the notebook instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*uNNC9Ez1x3I6ihQsEjytxA.png" /><figcaption>loading ai platform model resource</figcaption></figure><h4>g. Send explanation request</h4><p>Next will send test data instances to get explanations objects. Sending 50 data instances hence will receive 50 explanations object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*XT2svb0Mx3j1XywRWh6wwA.png" /><figcaption>explanation request</figcaption></figure><h3>4. Understand explanations</h3><p>Now I have received 50 explanations objects corresponds to 50 input test data instances. Let see how these explanations can be consumed.</p><p>I am stopping this story here. In the next story, I will explain how to use the explanations object and the core concept behind such explanations. The next story will give a clear idea about explaining your model by these explanations.</p><p>Thanks to <a href="https://cloud.google.com/ai-platform/prediction/docs/ai-explanations/overview">Google Cloud AI Explanation Service</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b55f56a96ec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autoencoder — a neural network architecture]]></title>
            <link>https://nazrul-miya91.medium.com/autoencoder-a-neural-network-architecture-a4b5824670d3?source=rss-a0a9a26a10d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4b5824670d3</guid>
            <category><![CDATA[encoder-decoder-model]]></category>
            <category><![CDATA[dimensionality-reduct]]></category>
            <category><![CDATA[autoencoder]]></category>
            <dc:creator><![CDATA[Nazrul Miya]]></dc:creator>
            <pubDate>Tue, 22 Jun 2021 11:04:30 GMT</pubDate>
            <atom:updated>2021-06-22T12:38:26.703Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dimensionality Reduction by Autoencoder — a neural network architecture</h3><p><strong>Autoencoder or Encoder-Decoder model </strong>is a special type of neural network architecture that mainly aims to learn the hidden representation of input data in a lower-dimensional space. The model copies its input to its output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*tQ9BtSyKqi7aGF3L39jNQA.png" /><figcaption>Structure of an Autoencoder</figcaption></figure><p>Input data is encoded to a representation (<strong><em>h) </em></strong>through the mapping function <strong><em>f. </em></strong><em>The function</em><strong><em> h = f(x) </em></strong>id encoding function.</p><p>The encoded representation(<strong><em>h)</em></strong> is decoded back to output <strong><em>y. </em></strong>Where <strong><em>y </em></strong>is as similar as possible to the input <strong><em>x. </em></strong>The function <strong><em>y = g(h)</em></strong> is decoding function.</p><p>Autoencoder tries to reconstruct its input in the output layer, by learning the representation of the input. The approach is to minimize the loss which is the difference between input and output.</p><p><strong>Note:</strong> Autoencoder does not copy or reconstruct its input perfectly. Usually, they are restricted in ways that allow them to copy only approximately, and to copy only input that resembles the training data. Because the model is forced to prioritize which aspects of the input should be copied, it often learns useful properties of the data.</p><p>An autoencoder comprises two components — an <strong><em>Encoder </em></strong>and a <strong><em>Decoder. </em></strong>The <strong><em>encoder</em></strong> encodes its input to internal representation and the<strong><em> decoder</em></strong> decodes this representation back to its input as closely as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*pXJchnEwAmYvNZ1dzgjd1A.png" /><figcaption>The basic architecture of autoencoder</figcaption></figure><p>Autoencoder is a feed-forward non-recurrent neural network comprised of an <strong><em>input layer, one or more hidden layers,</em></strong> and <strong><em>an output layer</em></strong>. The autoencoder is trained on input data to learn its representation.</p><p><strong>The output layer has the same number of nodes(neurons) as its input layer because its purpose is to reconstruct its input.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*GYPab2JUr0LT9iop6FbBhg.png" /><figcaption>mapping functions in autoencoder</figcaption></figure><p><strong>Encoder mapping:</strong></p><p><strong><em>h = f (</em></strong>input_vector * weight_vector + bias<strong><em>)</em></strong> = <strong><em>f (X.W + b).</em></strong></p><p><strong>Decoder mapping:</strong></p><p><strong><em>y = g (</em></strong>encoded_vector * weight_vector + bias<strong><em>) = g (H.W` + b`) , </em></strong>where <strong><em>H </em></strong>is the encoded vector from hidden layer and <strong><em>W`</em></strong> is the weights associated to hidden layer neurons.</p><p><strong>Loss function:</strong></p><p><strong><em>L = squared </em></strong>difference between input and output(reconstrcted input)</p><p>= || ( (X — Y)||²</p><p>= || X — (<strong><em> g (</em></strong> <strong><em>f (X.W + b) . W` + b`)</em></strong>)||²</p><p>The autoencoder neural network is trained on input training data, learns accurate weights through <strong>backpropagation, </strong>and aims to minimize this reconstruction loss,</p><p><strong>Controllable parameters:</strong></p><p>The number of hidden layers (capacity) and the number of neurons in hidden layers (size) are two factors that can be set while implementing an autoencoder neural network.</p><p>If hidden layer size or dimension is lesser than input layer’s then the autoencoder model is called <strong>undercomplete autoencoder</strong>. And when hidden layer’s dimensions are larger or the capacity of hidden layers is huge then the autoencoder models are called <strong>overcomplete autoencoders.</strong></p><p><strong>Applications of Autoencoder:</strong></p><ol><li>Dimensionality Reduction</li><li>Anomaly Detection</li><li>Machine Translation</li><li>Image processing (denoising images)</li></ol><p><strong>Demo (Dimensionality Reduction):</strong></p><p>I will implement an autoencoder neural network to reduce the dimensionality of the <strong>KDD 2009 dataset.</strong></p><p>The data set has 50,000 observations and 230 features (190 numerical and 40 categorical). The purpose of this autoencoder model is to reduce dimensions from the dataset to 2.</p><p>The following steps need to be executed in order</p><ol><li>Loading KDD dataset</li><li>Missing value treatment to deal with missing values</li><li>Numerical features selection (Excluding categorical features in this example, however, categorical features should be encoded before using it in the autoencoder model)</li><li>Normalization to bring features in a common range</li><li>Finally, an autoencoder model is trained on the dataset</li></ol><p>I will use <strong>undercomplete autoencoder</strong> for this example and architecture of which is below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cN6uZTtsQ_3oEsOMk1MGPg.png" /></figure><p>The size of hidden layers is less than the size of the input layer. Also, the size of the output layer must be the same as the size of the input layer, because the model aims to get the input back as an output. The encodings layer size is set to 2 because I want to bring the features in a 2-dimensional space.</p><p><strong>Python Code:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*XAR4rUEdOSvjxA6gcPgm1Q.png" /><figcaption>Importing Libraries</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*f0rWtPpvPcjiE5mewlNdWQ.png" /><figcaption>Loading Data, Missing Value Treatment, Numerical Features Selection, and Normalization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*hvQg0nA0l_BGQayHiaN3Yw.png" /><figcaption>Encoder-Decoder Model Building</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*bVkcDg6qUomdafaimjkUDw.png" /><figcaption>Model Compilation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*XQqrfL8gJU3pLC6FEvwZww.png" /><figcaption>Initial Loss</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*OIH6wS6XwH6ZyJhes7qmIg.png" /><figcaption>Model Training (Learning weights and biases from training data, through backpropagation)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*_9Vr_dkQUMPF6P5iNn4ikQ.png" /><figcaption>Post-training loss</figcaption></figure><p>Post-training loss is much lesser than initial loss because the model has learned optimal weights and biases by getting trained on training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*nX-XVfdBy9UiHfVXTth_WA.png" /><figcaption>Training loss and validation loss curve</figcaption></figure><p>The model has started converging as the epochs increase.</p><p>Let&#39;s now visualize the learned representation. So when the input data is passed to the encoder component, it returns a 2-dimensional feature representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*BecMoYMFrky2lKzb5-zieA.png" /><figcaption>Encodings</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*smYGUptplVs1iXUTixLkYw.png" /><figcaption>2-D visualization of feature representation</figcaption></figure><p>The task is to reduce dimensions in a way such that the reduced representation represents the original data. Here the task is not to identify clusters. hence I am not trying to interpret clusters from the above visualization.</p><p><strong>Note: Different representation is produced by the model on each run because initial weights and biases are initialized with different values at each run.</strong></p><h3>Problem with undercomplete autoencoder</h3><p>An autoencoder is useless when it reconstructs its inputs exactly. Meaning it memorizes training data as it is without learning any useful structure or pattern or information from data.</p><p>Under complete autoencoder restricts the model from memorizing input data, by limiting the number of neurons in the hidden layer and the size of encoder, decoder components.</p><p>In the above example, the input layer dimension was 42 (after preprocessing data and selecting only numerical features), I used lesser neurons (32–2 -32) in the hidden layers, and also the capacity of the encoder and decoder components was very limited. Used only 3 hidden layers. This is one way to ensure that model is not simply memorizing the exact input data.</p><p>Another way to limit autoencoder from being simply memorizing input data is <strong>by adding a regularizationion term in the loss function. I will demonstrate this in my next story.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4b5824670d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[t-SNE Dimensionality Reduction Algorithm]]></title>
            <link>https://nazrul-miya91.medium.com/t-sne-dimensionality-reduction-algorithm-2612564aeacc?source=rss-a0a9a26a10d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2612564aeacc</guid>
            <category><![CDATA[how-to-interpret-t-sne]]></category>
            <category><![CDATA[t-sne-in-python]]></category>
            <category><![CDATA[how-t-sne-works]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[t-sne-explained]]></category>
            <dc:creator><![CDATA[Nazrul Miya]]></dc:creator>
            <pubDate>Fri, 18 Jun 2021 17:46:00 GMT</pubDate>
            <atom:updated>2021-06-18T17:47:07.532Z</atom:updated>
            <content:encoded><![CDATA[<p>In a simple sentence t-SNE (t-distributed Stochastic Neighbourhood Embedding) is a dimensionality reduction technique or algorithm which reduces the number of dimensions in a dataset, by mapping data points from high dimensional space into a location in a lower-dimensional space.<br>Hence t-SNE algorithm can help to solve two real problems faced by data scientist in a project,</p><ol><li>Reduce the dimension of a large dataset. Helps to improve the performance of a model in a cost-effective manner.</li><li>Visualizing high-dimensional data. Heps to visualize high dimensional data in 2D or 3D space.</li></ol><p>Let&#39;s decode what do words <strong><em>Neighbourhood</em></strong>, <strong><em>Embedding</em></strong>, <strong><em>Stochastic</em></strong> and <strong><em>t-Distributed</em></strong> means.</p><p><strong>Neighbourhood</strong>:<br>The neighbourhood of a data point in an N-dimensional space is a set of other nearest data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*9Ye4etrPP5PUr75wRNkNyw.png" /></figure><p><strong>Embedding</strong>:<br>The mapping of a point from one vector space to another vector space is called embedding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*QJNvbJmGwqmCJhu7Btu6aA.png" /></figure><p><strong>Stochastic</strong>:<br>The approach to embedding data points used by the t-SNE algorithm is a probabilistic approach. The algorithm uses the probability of similarities between datapoints in the embedding approach.</p><p><strong>t-Distributed</strong>:<br>It is a type of probability distribution, near similar to bell-shaped normal distribution except the tails in this distribution are heavier. This type of distribution arises when estimating the mean of a normally distributed population where the sample size is low and the standard deviation of a population is not known.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*iw55CbSjAWTWZ__9pahKKQ.png" /></figure><p><strong>High-Level intuition</strong></p><p>the t-SNE algorithm maps high dimensional data objects into a much lower dimensional space such that the mapping preserves both local and global structures of higher-dimensional data as much as possible in lower-dimensional space.</p><p>Distance between data points within a cluster represents a <em>local geometric structure</em>. Preserving this structure meaning after mapping data objects into lower-dimensional space, these distances within-cluster elements does not change.</p><p>Distance between data points from two different clusters represents <em>global geometric structure</em>.</p><p>In a simple way to say, the following steps are involved in this algorithm.</p><p>1. Measures similarities between data points in a high dimensional space. (Probability Measure)</p><p>2. Measures similarities of data points, mapped to lower-dimensional space. (Probability Measure)</p><p>3. Compare these similarity measurements.</p><p>If data points in higher dimensional space are correctly modelled in lower dimensional space such that local structure and global structure are preserved, then these similarity measurements will be equal.</p><p><strong>Low-Level Intuition</strong></p><p>Step 1:</p><p>Euclidean distance between two high-dimensional data points <em>x_i</em> and <em>x_j</em> is computed as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*S-MK-fHUJuc8Yg97aXW8tw.png" /></figure><p>The t-SNE algorithm calculates <strong>scaled squared </strong><em>Euclidean Distance</em> <em>(d_{ij}²)</em> between two high dimensional data points as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*9JQB8NcrMG-_OnIhqXkuOA.png" /></figure><p>where <em>sigma_i</em> is the variance of normal distribution of data points centred at point <em>x_i</em>.</p><p>Step 2:</p><p>A conditional probability <em>(p_{j|i})</em> is then calculated from scaled squared distances between points in high dimensional space. This measures the probability that a data point <em>x_i</em> will pick another data point <em>x_j</em> as its neighbour data point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*9N7BN-7iW5wcLnkxYrdEyA.png" /></figure><p>Where <em>k </em>is an input to the algorithm that measures an effective number of local neighbours.</p><p>Step 3:</p><p>Similarly in low dimensional space, a conditional probability <em>(q_{j|i})</em> that a data point <em>y_i</em> in low dimensional space will pick another data point <em>y_j</em> as its neighbour, is computed.</p><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*ewXjuWeQwNh5Fvc7KhtYUw.png" /></figure><p>In low dimensional space, a fixed variance (<em>1/2)</em> is used and a t-distribution of neighbour data points centred at point <em>y_i</em> is used.</p><p>Step 4:</p><p>conditional probabilities <em>(p_{j|i}) and (q_{j|i})</em> of all data points , resembles a probability distribution respectively. the t-SNE algorithm tries to match these two probability distributions as much as possible. To compare these two probability distributions, the algorithm uses <strong>Kullback–Leibler divergence</strong>. KL Divergence <em>D_{kl}(p_{j|i}||q_{j|i})</em> is a measure of how one probability distribution is different from a second one and is computed as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*5Tqw8I9tLk5LLL1IX-aQWw.png" /></figure><p>t-SNE algorithm tries to minimize <em>D_{kl}(p_{j|i}||q_{j|i})</em> which is the cost function of t-SNE algorithm.</p><p><strong>How to do it in python?</strong></p><p>sklearn module <strong>sklearn.manifold.TSNE</strong> helps to achieve t-distributed stochastic neighbour embedding.</p><p>We will perform t-SNE on <strong>KDD 2009</strong> dataset (a smaller version of it), which has 230 features, 190 numerical and 40 categorical variables. Before we execute t-SNE on 230-dimensional dataset we will execute the below steps,</p><p>1. Filter only numerical features. (Note: categorical features needs to be encoded to numerical form so that can be sent to the t-SNE algorithm, for this example we are ignoring categorical features)</p><p>2. Missing Value Filter: features with a missing value greater than 90% will be removed.</p><p>3. Missing Value Treatment: missing values in each numerical features will be filled with the mean value.</p><p>4. Standardization: features will be standardized to bring all of them in a common range.</p><p>Finally will reduce dimensionality by t-SNE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*5Bzn2zws_v8u2eMQEOCFbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*SlGMDwG4MXhQuPdR-YEHDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*UyWrVLnXNnQkpTnLj-9H2g.png" /><figcaption>2-D Visualisation</figcaption></figure><p>The t-SNE algorithm can be run multiple times for various combinations of parameters such as <strong>perplexity, n_iter, learning_rate etc.</strong></p><p><strong>t-SNE </strong>reports different results for each run, because the cost function is <strong>non-convex </strong>and the function is optimized through the popular approach <strong>Gradient Descent which initializes randomly on every run, hence can return different optimal KL divergence. </strong>To select the right visualisation of the high dimensional dataset, we can run t-SNE multiple times with the same K, same data, and other parameters. Select the visualisation for which t-SNE reports the lowest KL divergence value.</p><p>Check FAQs in <a href="https://lvdmaaten.github.io/tsne/">https://lvdmaaten.github.io/tsne/</a> for useful information on t-SNE.</p><p><strong>t-SNE can be computationaly expensive for large dataset. Also finding right combination of hyperparameters is really tricky.</strong></p><p>t-SNE can report misleading results. Check out this great article <a href="https://distill.pub/2016/misread-tsne/"><strong>https://distill.pub/2016/misread-tsne/</strong></a><strong> </strong>for more clarity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2612564aeacc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PCA Explained with an Example]]></title>
            <link>https://nazrul-miya91.medium.com/pca-explained-with-an-example-779732925f2d?source=rss-a0a9a26a10d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/779732925f2d</guid>
            <dc:creator><![CDATA[Nazrul Miya]]></dc:creator>
            <pubDate>Tue, 15 Jun 2021 19:43:58 GMT</pubDate>
            <atom:updated>2021-06-15T19:43:58.879Z</atom:updated>
            <content:encoded><![CDATA[<p>PCA is a dimensionality reduction method that transforms data points in a larger dimensional space into much lower-dimensional space. For example, the 10-dimensional dataset can be reduced to 2 dimensions.<br>Main purpose of PCA is to project large dimensional data points into lower dimensional space without losing much information.</p><p><strong>How PCA works?</strong><br>Mathematical concepts such as <strong>Covariance</strong>, <strong>Eigen Vectors,</strong> and <strong>Eigen Values</strong> are the backbone of PCA.</p><p>Will explain these concepts by a small example where we will project a 2-D dataset into one-dimensional space.</p><p>Consider a small house dataset with two features Bedroom_Count and Bathroom_Count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*uDIDqJt-4cf63_pYsTzEBw.png" /><figcaption>House Data Set</figcaption></figure><p><strong>Step 1</strong>: Standardization<br>The standardization is a feature scaling technique that scales features to a common range. In a dataset features may vary in different scales and ranges, for example, one feature may range between 10 to 20, another feature may range between 1000 to 2000. These differently ranged features may influence machine learning algorithms and leads to a biased algorithm. To solve this all the features should be in the same range. Standardization brings the features in a common range between −1 and 1.<br>The formula used to standardize a data variable X with a mean μ and standard deviation σ is, (X−μ)/σ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*dXCozFDNeuFOlZCnQDpMsg.png" /></figure><p><strong>Step 2:</strong> Finding Covariance Matrix<br><strong>Variance</strong> is a measure of the variability of a single variable and <strong>Covariance</strong> is a measure of joint variability between two variables. For example variance of feature Bathroom_Count measures how to spread out are data values in this feature. Covariance between features Bedroom_Count and Bathroom_Count measures how spread data points along Bedroom_Count feature and how spread data points along Bathroom_Count feature.</p><p>Variance is calculated as <strong><em>varX=∑(xi−μ)2/n−1.</em></strong> (Sum of squared deviation from mean divided by mean of variable X).</p><p>Covariance is calculated as, <strong><em>cov(x,y)=∑(xi−μx)(yi−μy)/n−1</em></strong></p><p>The below figure shows variance and covariance calculation for the housing dataset,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*d7R9Ob5seG7KpQcJssCGng.png" /></figure><p><strong>Covariance Matrix</strong> is a matrix of n * n dimension where n is the number of features, and is represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*F5hcsjHyvczCBiyKkP8jlw.png" /><figcaption>Covariance Matrix</figcaption></figure><p>Covariance matrix formed from house dataset is as below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*7VRRE6GRhNcRXvG8lSEjYw.png" /><figcaption>Covariance Matrix (House Datset)</figcaption></figure><p><strong>Step 3: Determine Eigenvectors and Eigenvalues</strong><br>In this step eigenvectors and eigenvalues are calculated from the covariance matrix.<br>Eigenvectors represent the direction of the axes where there is most variance,<br>Eigenvalues are the amount of variance along that axes. If we have a <em>p*p</em> matrix we are going to have p eigenvalues. They are obtained by solving the equation given in the expression below:<br><strong><em>det(A−λ.I)=0</em></strong></p><p>corresponding eigenvectors are obtained by solving the below expression,<br><strong><em>(A−λiI)vi→=0</em></strong></p><p>In our house dataset example, we found covariance matrix,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*h6bH8BnxXETDyXvA1OIGPg.png" /></figure><p>Then the expression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*ah5L3UmHg1OyOi5JPwt0Dw.png" /></figure><p>will result in two eigenvalues as λ1=2.21539462 and λ2=0.07031967</p><p>And below two expressions,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*pcorsUXEcK5vLFIfloEXnA.png" /></figure><p>will give two eigenvectors as,<br>e1=[0.707106, 0.707106],<br>e2=[−0.707106. 0.707106]</p><p>These eigenvectors are the direction in which house data points will be transformed or projected. And eigenvalues are the magnitude of these eigenvectors which quantify the scale of the transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*OSqGi6sATMESwu4_eUMakg.png" /></figure><p>These eigenvectors are orthogonal vectors meaning they are perpendicular to each other. The orthogonality preserves the non-correlation between principal components.</p><p>Imagine an axis towards the direction of the eigenvector. this is a known principal component. For a 2-D dataset, two eigenvectors are determined, therefore two principal components. An N-Dimensional dataset produces N Principal components.</p><p><strong>Step 4: Projection</strong><br>Once direction of transformation (eigenvectors) are found , next step is to project standardized data points towards these directions. This is called <strong>Transformation or Projection</strong>. Transformation can be achieved by a matrix dot product between standardized data matrix A and the eigenvectors E.<br>The following figures show the transformation of standardized house data points towards the direction of eigenvectors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*uTn4uGqMg-ZxssTlR9wBog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*oRdh7oIo-74NAoOyCx8Whg.png" /></figure><p><strong>Analysis of Principal Components (PCA)</strong></p><p>An N-Dimensional dataset produces N orthogonal principal components. Each principal component is associated with an eigenvector and an eigenvalue.</p><p>To reduce the dimensionality from N dimensions to n dimension where n&lt;N percentages of variance accounted by each eigenvector are calculated.<br>Eigenvalues quantify the scale of transformation, which is the same as a variance. Eigenvalue λ1 quantifies variance in the direction of eigenvector e1 and eigenvalue λ2 quantifies variance in the direction of the eigenvector of e2.<br>For house data points calculated λ1=2.21539462 and λ2=0.07031967 , It can be interpreted that variance along principal component 1 is more than variance principal component 2. Hence first principal component carries more information than the second principal component. Dividing the eigenvalue of each principal component by sum of eigenvalues gives a percentage of variance. For λ1=2.21539462 and λ2=0.07031967, variance percentages are Var(pc1)=97% and Var(pc2)=3% respectively.</p><p>These percentages of variance can be visualized using <strong>Scree Plot</strong>.<br>Following figure plots variance ratios against each principal components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*k6VoUbHMG2ry2CjABf1VfA.png" /></figure><p><strong>Selecting the Right Number of dimensions</strong><br>The number of principal components is equal to the number of features in a dataset. The final goal is to reduce the dimensions in a dataset. Meaning n principal components need to be selected from a set of N components. Now how to choose the right number of n? <strong>Scree plot</strong> helps to select n.<br>Consider the below scree plot,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*y-G5w8H3uYczP0xvwrKKow.png" /></figure><p>from the plot above we can understand that components PC1 , PC2 , PC3 and PC4 has much higher variance ratios , therefore carries more information. Also, the variance ratio decreasing scale became stable from PC5 onwards. Hence we can choose PC1, PC2, PC3, and PC4 as the final set of dimensions for the dataset, therefore n=4.</p><h4>How to find PCAs in python?</h4><p>sklearn.decomposition.PCA finds principal components from an N-dimensional dataset.</p><p>We will find principal components from KDD 2009 large dataset. Before performing PCA, we will execute below preprocessing steps,</p><ol><li>Missing Value Filter: features with a missing value greater than 90% will be removed.</li><li>Missing Value Treatment: missing values in each numerical feature will be filled with the mean values.</li><li>Standardization: features will be standardized to bring all of them in a common range.</li><li>Finally will find Principal components and will select n high variance principal components.</li></ol><p><strong>Code Snippet</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*xsgZuOVzPSWBlhgHO7tmqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*xTS_v24SUYoD49jk2rqrpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*1yNCjfr7Z9SOBNMRN5YoIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*K6xkWlHKZ8pTx3GnzAwrDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*_XdTZXdYScwsGK8hukSIOg.png" /></figure><p>reduced_dataset has a shape of (50000, 5). (Note: Only the numerical features have been transformed into 5-dimensional space using PCA).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=779732925f2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>