<?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 Mirza Rahim Baig on Medium]]></title>
        <description><![CDATA[Stories by Mirza Rahim Baig on Medium]]></description>
        <link>https://medium.com/@mirzarahim2197?source=rss-be6714caafb2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Z4Na_y6tEkUVYBlHHD69Ng.jpeg</url>
            <title>Stories by Mirza Rahim Baig on Medium</title>
            <link>https://medium.com/@mirzarahim2197?source=rss-be6714caafb2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:24:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mirzarahim2197/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[Of Cobras and KPIs]]></title>
            <link>https://medium.com/@mirzarahim2197/of-cobras-and-kpis-d1b87ff75db7?source=rss-be6714caafb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1b87ff75db7</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kpi]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Mirza Rahim Baig]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 17:44:53 GMT</pubDate>
            <atom:updated>2021-08-04T17:44:53.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGFh0lsyLHbqjudLZOXUPA.jpeg" /></figure><p>During the British rule in India, the city of Delhi was once facing a problem of venomous cobras. In an attempt to solve this, the governing authorities offered a bounty on cobra skins — get a cobra skin, get money. Here is what followed -</p><ul><li>It began well with locals handing in cobra skins and getting rewards.</li><li>Soon, the amount of cobra skins coming in had increased several times.</li><li>It turns out that people had started farming cobras just for the bounty.</li><li>Authorities realized this and scrapped the scheme.</li><li>Due to lack of a market, the farmers released the cobras into the wild.</li><li>The cobra menace, instead of getting solved, worsened significantly.</li></ul><p><strong>Another story, much closer, from LinkedIn</strong></p><p>LinkedIn introduced endorsements around 2012 — a product that touches upon social as well as hiring aspects of the platform. Endorsements are used as one input to rank search results for skill experts, so that recruiters can find candidates with the right skills. The North Star metric was ‘Total Endorsements’. To improve this metric, LinkedIn designed interventions that allowed users to very easily endorse another user. Soon, the volume of endorsements increased significantly. By 2017, there were more than 10 billion endorsements with more than 43 million endorsements given each week. This was not a resounding success, though. The value of endorsements diluted and recruiters could not trust these endorsements as a measure of expertise.</p><p><strong>The Cobra Effect and ‘gaming’ of KPIs</strong></p><p>There are several more examples of what is called the ‘<a href="https://en.wikipedia.org/wiki/Perverse_incentive#The_original_cobra_effect">Cobra Effect</a>’ — referring to unintended consequences of your success metric. Choosing KPIs and especially the North Star is never easy. This is indeed one of the most important choices we must make — we have heard, ‘you can’t improve what you can’t measure’ (Peter Drucker) and also, ‘<a href="https://hbr.org/2010/06/column-you-are-what-you-measure">you are what you measure</a>’ (Dan Ariely; HBR 2010). There are many considerations, and the topic is too involved for a single article. An additional question that you need to ask is — can the KPI be ‘gamed’?</p><p>‘Gaming’ doesn’t necessarily have to done be by the Product Manager who can influence it to make the product appear successful. It could very well be the behaviours of the end customers that don’t serve your purpose. It could even be bugs in the system that improve certain metrics while degrading the overall customer experience.</p><p>At Bing, the Microsoft owned search engine, an important KPI was ‘queries per user’. Once, out of the blue, without any improvement/intervention in the experience, the queries per user shot up. Big success? Shortly after, a bug surfaced that had degraded the search relevance. It didn’t take long to realize that due to poor relevance the users ended up making more queries and ‘improving’ the KPI for a degraded customer experience. The team reconsidered the metric and switched to ‘sessions per user’ instead.</p><p><strong>Towards better performance tracking</strong></p><p>Is there a KPI that can never be gamed? Unlikely. Part of the solution is in choosing better KPIs that are less likely to be gamed. Another part is in having the right set of supporting metrics and reviewing KPIs.</p><ul><li>To begin, when you and your team are brainstorming over the right KPIs to track, prefer KPIs that measure ‘quality’. KPIs that measure volume/count aren’t often great and are more prone to gaming. KPIs measuring quality are often ratios.</li><li>Choose KPIs that are closest to the intended behaviour / ‘perfect experience’ of the user. The KPIs should take a hit when the experience degrades. YouTube chose watching minutes as its North Star. Many online retail platforms choose Customer Lifetime Value (CLV).</li><li>Keep reviewing KPIs and ensure they are aligned with business objectives. Objectives keep changing at different stages of maturity of an organization/product. Indeed, it is common that many products/organizations initially have a customer acquisition objective and later focus on retention.</li><li>Segment your KPIs. De-aggregate your views and don’t miss out on pockets where the performance is cause for concern. Alerts for performance drops for all segmentations may be overkill, but can help in the case of some key segment views.</li><li>Have strong guardrail metrics. Some guardrail metrics should be those sacrosanct metrics that must never be degraded. Others could be metrics that understand and capture the dependence between key metrics.</li><li>Track system performance metrics and enable alerts for bugs.</li><li>Track input metrics and driver metrics. Not all of these may be in your control and aren’t therefore actionable. But tracking helps quickly isolate issues. The best input metrics are those you can influence and are good leading indicators of the output.</li></ul><p>The points above don’t guarantee safety from the ‘Cobra effect’, but adhering to these may significantly reduce your chances of falling prey to it. Additionally, they should give you a ‘reliable’ view of performance that you can base decisions on.</p><p>If you are looking for a good, quick read on KPIs in general, this <a href="https://www.forbes.com/sites/theyec/2018/12/04/you-are-what-you-measure/">Forbes article</a> by Jacob Drucker is a good starting point. Read some other interesting examples of Cobra effect <a href="https://en.wikipedia.org/wiki/Perverse_incentive#Further_historical_examples">here</a>.</p><p>Got any interesting examples of the Cobra effect that you came across?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1b87ff75db7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beautiful visual model interpretation of classification strategies- Kannada MNIST Digits…]]></title>
            <link>https://medium.com/data-science/kannada-visual-model-952cc6ec3a72?source=rss-be6714caafb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/952cc6ec3a72</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[inside-ai]]></category>
            <category><![CDATA[mnist]]></category>
            <dc:creator><![CDATA[Mirza Rahim Baig]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 14:39:52 GMT</pubDate>
            <atom:updated>2019-09-12T12:30:13.784Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beautiful visual model interpretation of classification strategies— Kannada MNIST Digits Recognition</h3><h4>subtitle here</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*x2tyhY_sgaHcL-YoxyrpIQ.png" /><figcaption>Kannada handwritten digits</figcaption></figure><p>The Kannada MNIST dataset is a great recent work (<a href="https://arxiv.org/abs/1908.01242">details here</a>), and I’m delighted that it is available to the public as well. I’m sure pretty soon the community here would be posting state of the art accuracy numbers on this dataset. Which is why, I’m doing something different.</p><p>Instead, we will try to visualize, try to see what the model sees, assess things pixel by pixel. Our goal would be interpretability. I’ll start with the ‘simplest’, easiest to interpret algorithm in this article. Hopefully, I’ll post results with other modeling techniques in later article.</p><p><strong>To reiterate and clarify: I will not be focusing on getting best possible performance. Rather, I’ll focus on visualizing the output, making sense of the model, and understanding where it failed and why. Which is more interesting to assess when the model isn’t working extremely well. :)</strong></p><h3>Visualizing the digits data</h3><h4>Function to plot one random digit along with its label</h4><pre>def plot_random_digit():<br>    random_index = np.random.randint(0,X_train.shape[0])<br>    plt.imshow(X_train[random_index], cmap=&#39;BuPu_r&#39;)<br>    plt.title(y_train[random_index])<br>    plt.axis(&quot;Off&quot;)</pre><pre>plt.figure(figsize=[2,2])<br>plot_random_digit()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*FZe5kDGIwclevx46vvFY7g.png" /><figcaption>A random Kannada digit plotted as image</figcaption></figure><h4>Looking at 50 samples at one go</h4><pre>plt.figure(figsize=[10,6])<br>for i <strong>in</strong> range(50):<br>    plt.subplot(5, 10, i+1)<br>    plt.axis(&#39;Off&#39;)<br>    if i &lt; 10:<br>        plt.title(y_train[i])<br>    plt.imshow(X_train[i], cmap=&#39;BuPu_r&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*ZyqEcvv0IShIljVfbvSTLw.png" /></figure><p>As someone who is not good at reading Kannada script, to me the symbols seem somewhat similar for -</p><ul><li>3 and 7</li><li>6 and 9</li></ul><p>At the onset, I would expect that the predictors could be somewhat confused between these pairs. Although this isn’t necessarily true — maybe our model can identify the digits better than I can.</p><h3>Reshaping the datasets for predictive model building</h3><p>The individual examples are 28 X 28. For most predictive modeling methods in scikit learn, we need to get flatten the examples to a 1D array.<br>We’ll use the reshape method of numpy arrays.</p><pre>X_train_reshape = X_train.reshape(X_train.shape[0], 784)<br>X_test_reshape = X_test.reshape(X_test.shape[0], 784)</pre><h3>Building and understanding the Logistic regression model</h3><p>Let’s build a Logistic regression model for our multiclass classification problem.</p><p><strong>Note again that we’ll not be focusing on getting the best possible performance, but on how to understand what the model has learnt.</strong></p><p>A logistic regression model will be easy and interesting to analyse the coefficients to understand what the model has learnt.<br>The formulation of a multi-class classification can be done in a couple of ways in SciKit-learn. They are -</p><ul><li>One vs Rest</li><li>Multinomial</li></ul><p><strong>1. One vs Rest:</strong></p><p>Also known as one-vs-all, this strategy consists in fitting one classifier per class. For each classifier, the class is fitted against all the other classes. One advantage of this approach is its interpretability.</p><p>Since each class is represented by one and one classifier only, it is possible to gain knowledge about the class by inspecting its corresponding classifier. This is the most commonly used strategy for multi-class classification and is a fair default choice.</p><p>For our case, it would mean building 10 different classifiers.</p><p>Read more about it here:<br><a href="https://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html">https://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html</a></p><p><strong>2. Multinomial:</strong></p><p>In this strategy, we model the logarithm of the probability of seeing a given output using the linear predictor.<br>For multinomial the loss minimised is the multinomial loss fit across the entire probability distribution. The softmax function is used to find the predicted probability of each class.</p><p>Read more about this here:<br><a href="https://en.wikipedia.org/wiki/Multinomial_logistic_regression#As_a_log-linear_model">https://en.wikipedia.org/wiki/Multinomial_logistic_regression#As_a_log-linear_model</a></p><p><strong>Note</strong>: This distinction is important, and needs you to interpret the coefficients differently for the models.</p><h3>First, let’s built our model using the One vs. Rest scheme</h3><pre>from sklearn.linear_model import LogisticRegression<br>lr1 = LogisticRegression(solver=&quot;liblinear&quot;, multi_class=&quot;ovr&quot;)<br><br><em># Fitting on first 10000 records for faster training  </em><br>lr1.fit(X_train_reshape[:10000], y_train[:10000])</pre><h4>Assessing performance on the train set</h4><p>The predictions of the model for the training data</p><pre>from sklearn.metrics import confusion_matrix, accuracy_score, classification_report<br>y_train_pred = lr1.predict(X_train_reshape[:10000])</pre><pre>cm = confusion_matrix(y_train[:10000], y_train_pred[:10000])<br><br>plt.figure(figsize=[7,6])<br>sns.heatmap(cm, cmap=&quot;Reds&quot;, annot=True, fmt=&#39;.0f&#39;)<br>plt.show()</pre><h4>That’s VERY high training accuracy! Overfitting?</h4><p>Also, looks like the model is <strong>NOT</strong> very confused between 3 and 7, 6 and 9, at least not on the train set.</p><h3>Error Analysis: Checking out the mis-classified cases</h3><p>We’ll covert to a Pandas series for ease of indexing, isolate the mis-classification cases, plot some examples.</p><h4>11 cases were mis-classified</h4><ul><li>Studying some cases</li><li>Picking 9 random cases — we’ll plot the digits, along with the true and predicted labels</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*9CBhzWeAszdWTR3qt-WWJQ.png" /><figcaption>The mis-classified cases</figcaption></figure><p>Can you see why the model was confused?<br>Let’s see how the model fares on the test set.</p><h4>Confusion matrix on the test set</h4><p>Making predictions on the test data, and plotting the confusion matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*dR2-IDglg12eP4QXXBRyLg.png" /><figcaption>Confusion Matrix on test set — smells like over-fitting</figcaption></figure><h4>Looking at the confusion matrix and the classification report -</h4><p>Recall is least for 3, 7 — model is confused between them significantly. Similarly, there is confusion between 4 and 5. Also, many 0s are mistaken for 1 and 3.</p><p>Okay! So it looks like the performance has fallen sharply on the test set. There’s a very good chance we’re over-fitting on the train set.</p><p>We acknowledge that the model could be improved.</p><p>But, let’s not worry about that for now. <strong>Let’s focus on the way to understand what the model learnt.</strong></p><h3>Model interpretation</h3><h4>Understanding the contribution of each pixel</h4><p>The coefficients we learnt right now for each pixel, are based on the One vs Rest scheme.</p><p>Let’s go ahead and analyze the coefficients for our OVR model.</p><p>The shape for the coefficients ‘lr1.coef_.shape’ is (10. 784) i.e. we have 784 coefficients for each label — coefficients for each pixel for each digit!</p><p>A positive coefficient means a high value on that pixel increases the chances of this label, <strong>compared to ALL other classes</strong>. The coefficients therefore tell us how this pixel differentiates this label from all the other labels together.</p><h4>Extracting the pixel coefficients and plotting on a heat-map for the label 0</h4><pre>plt.figure(figsize=[3,3])<br>coefs = lr1.coef_[0].reshape(28,28)<br>plt.imshow(coefs,cmap=&quot;RdYlGn&quot;,vmin=-np.max(coefs),vmax=np.max(coefs)) <em>#setting mid point to 0</em><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*rzVhJinLdvboN9yqwjdtPA.png" /><figcaption>Heatmap for 0 — OVR</figcaption></figure><p>I’ve used a divergent colour scheme to differentiate between the positive and negative signs.</p><p>In the image above, pixels with green colour are positive value pixels. The image tells us that values in certain pixels help classify the digit as 0. As expected, the red colour in the center indicates that presence of values in that range means lower chances of the digit being a zero. Yellow is close to 0 — meaning the pixel doesn’t help differentiate in any way.</p><h4><strong>Making such pixel heatmaps for all the digits</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*H7I7yR75A4TNeA8Crjp8bw.png" /><figcaption>Heatmap — all digits — OVR scheme</figcaption></figure><p>Have a good look at these heatmaps. This will reveal what the model has learnt. Be mindful that we have ‘One vs. Rest’ formulation, especially when comparing with heatmaps of other digits.</p><h3>Now, let’s build a model using the multinomial scheme.</h3><ul><li>We need to specify the multi_class parameter as &quot;multinomial&quot;</li><li>The ‘liblinear’ solver doesn’t support this, so we choose the “sag” solver.</li></ul><pre>lr2 = LogisticRegression(random_state=42, multi_class=&quot;multinomial&quot;, solver=&quot;sag&quot;)<br>lr2.fit(X_train_reshape[:10000], y_train[:10000])</pre><h4>Assessing performance on the test set</h4><p>Plotting the confusion matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*JoK7HFob96EVBsRL16QOoQ.png" /></figure><h3>Understanding the contribution of each pixel</h3><p>We have 784 coefficients for each label — coefficients for each pixel.</p><p>Now, a positive coefficient would mean what makes this label what it is! But, if 3 labels have similar presence in particular pixel, the coefficients for all 3 may have similar values.</p><h4>Extracting the pixel coefficients and plotting on a heatmap for the label 0</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*9m_zHD8GNteuUe5q_uR0vg.png" /></figure><p>How different/similar is this to the heatmap from the OVR model?<br>Let’s make the heatmaps for all pixels.</p><h4>Making such pixel heatmaps for all the digits</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*_Jz1EX8KWIwLmMCEAtQXsA.png" /></figure><h4>How does these heatmaps compare to the mean images for each label?</h4><p>Plotting the average image for each digit.</p><pre>plt.figure(figsize=(10, 4))<br>for i <strong>in</strong> range(10):<br>    plt.subplot(2,5,i+1), plt.title(i)<br>    plt.imshow(np.mean(X_train[y_train==i],axis=0),cmap=&#39;gray&#39;)<br>plt.suptitle(&#39;Mean images for each digit&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*JBQFSWZiQOnadIZ6cuiSyA.png" /></figure><h3>Plotting them all together — have a good look.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*dTczfKHRGKbogiEpxZGk4g.png" /><figcaption>Mean images vs. OVR vs. Mutinomial</figcaption></figure><h3>Exercise -</h3><p>You’ve seen the heatmaps for the OVR method, as well as the multinomial method. And you also have the average image for each label.</p><ul><li>Compare and contrast the heatmaps with the mean images.</li><li>What do think is going on? Can you try to understand what the models have learnt for each digit?</li><li>Why are the models not performing so well on certain digits? Can the heatmap help understand?</li></ul><h3>Possible next steps for those interesting in trying out more things -</h3><p>I suggest you try the following -</p><ol><li>Use Logistic regression with regularization (ridge, lasso, elasticnet) and hyper-parameter optimization using cross validation to reduce overfitting.</li><li>Use SVD/PCA to denoise and reconstruct the original data; follow it up with a tuned Logistic regression model.</li></ol><p>Well, that’s all for our little demo here! I’ll soon share more demos with different modeling techniques, ways to interpret them and more experiments with the same dataset with supervised and unsupervised techniques.</p><h3>Found this interesting? Stay tuned for more such demos.</h3><h4>Do share your remarks/comments/suggestions!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952cc6ec3a72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/kannada-visual-model-952cc6ec3a72">Beautiful visual model interpretation of classification strategies- Kannada MNIST Digits…</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>