<?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 Xafar Nasim on Medium]]></title>
        <description><![CDATA[Stories by Xafar Nasim on Medium]]></description>
        <link>https://medium.com/@xafar.nasim?source=rss-8ea3e7c88ab8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9WoKZnA7P78PoP314FX4zA.jpeg</url>
            <title>Stories by Xafar Nasim on Medium</title>
            <link>https://medium.com/@xafar.nasim?source=rss-8ea3e7c88ab8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:16:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xafar.nasim/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[The Power Of Fastai]]></title>
            <link>https://medium.com/@xafar.nasim/the-power-of-fastai-732c19782cb5?source=rss-8ea3e7c88ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/732c19782cb5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Xafar Nasim]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 10:23:32 GMT</pubDate>
            <atom:updated>2025-06-25T11:25:05.103Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are looking for a powerful library that takes care of all the data loading, preprocessing, training and evaluating a model — basically all the painstaking tasks and allows you to do the real work that you want to focus on, then worry no more. Fastai is here to rescue you. With just a few elegant lines of code, you’ll see how effortlessly Fastai handles the nitty-gritty — splitting, labelling, transforming, and batching — so you can focus more on modelling and less on wrestling with your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfFlO_y6SUywgHcf49lhOQ.png" /></figure><p>Before we begin, make sure to have the appropriate dependencies installed:</p><pre>pip install fastai scikit-learn matplotlib seaborn</pre><p>In this tutorial, we will utilise the Fastai library to train a multi-class image classifier that actually <em>cares</em> about all classes, not just the popular majority ones. Using a ResNet50 backbone, clever metrics like balanced accuracy and ROC AUC, weighted loss, and some early stopping wisdom, you’ll learn how to build a model that’s both smart and fair. The tutorial is divided into the following sections:</p><ol><li>Downloading the dataset</li><li>Dataset Overview</li><li>Training a classifier</li></ol><p>Feel free to skip some of the initial sections if you are interested in just training the classifier.</p><h4>Downloading the dataset</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F16867608&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Flagreca-busted-open-download-fassa-busted-gif-16867608&amp;image=https%3A%2F%2Fmedia.tenor.com%2F4-AxnUpVV-cAAAAN%2Flagreca-busted-open.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fcded3c9ec1c13db57dc72e1bdf18b5/href">https://medium.com/media/8fcded3c9ec1c13db57dc72e1bdf18b5/href</a></iframe><p>We leverage the Kaggle API to download the dataset. You need to have an account on <a href="https://www.kaggle.com/">Kaggle</a> and create a new token for Kaggle’s beta API via the settings. Upon successful creation, you would be able to download a JSON file with the following contents:</p><pre>{&quot;username&quot;:&quot;yourUsername&quot;,&quot;key&quot;:&quot;UUIDgeneratedKey&quot;}</pre><p>We download the <a href="https://www.kaggle.com/datasets/sujaykapadnis/emotion-recognition-dataset/data">Facial Emotion Recognition</a> dataset from Kaggle. The key part is the subprocess.run() command, which runs the Kaggle CLI tool directly from Python. It downloads and unzips the Emotion Recognition dataset from Kaggle into the specified folder. This is a handy way to automate dataset downloads within your scripts, so you don’t have to do it manually through the browser or terminal every time. It also prevents redundant downloads if the dataset already exists. Make sure to copy your Kaggle credentials to the command line before executing the code. Here is the code snippet:</p><pre># Set your Kaggle API credentials using the cmd on terminal:<br>#export KAGGLE_USERNAME=your_kaggle_username<br>#export KAGGLE_KEY=your_kaggle_api_key<br><br>if __name__ == &quot;__main__&quot;:<br>    DATASET_DIRECTORY = &#39;/your/path/to/datasets&#39;<br>    DOWNLOAD_PATH = f&quot;{DATASET_DIRECTORY}/facial&quot;<br><br>    # Create directory if it doesn&#39;t exist<br>    os.makedirs(DOWNLOAD_PATH, exist_ok=True)<br><br>    # Check if directory is empty<br>    if not os.listdir(DOWNLOAD_PATH):<br>        subprocess.run([<br>            &#39;kaggle&#39;, &#39;datasets&#39;, &#39;download&#39;,<br>            &#39;-d&#39;, &#39;sujaykapadnis/emotion-recognition-dataset&#39;,<br>            &#39;--path&#39;, DOWNLOAD_PATH,<br>            &#39;--unzip&#39;<br>        ])<br>        print(f&quot;Downloaded Facial Emotion Recognition dataset to {DOWNLOAD_PATH} successfully&quot;)<br>    else:<br>        print(f&quot;Dataset already exists in {DOWNLOAD_PATH}, skipping download.&quot;)</pre><h4>Dataset Overview</h4><p>Before we dive in and start squeezing every drop of insight from our dataset (read: torturing it until it confesses), there’s an often-skipped but super valuable step — <strong>preliminary analysis</strong>. Think of it as saying a polite “hello” before interrogating your data. This quick once-over can save you hours of head-scratching later on. It offers a sneak peek into what you’re dealing with, uncovers any red flags, and can gently nudge you in the right direction.</p><p>We start by exploring the <strong>data card</strong> — that humble little summary often overlooked like terms and conditions. It can hold key details about the dataset’s origin, structure, intended use, and any known limitations. Trust me, your future self will thank you. What we are looking for is:</p><ul><li>Description: What is the dataset about?</li><li>Classes: How many classes are there?</li><li>Size: How big is the dataset in terms of memory size and total images?</li><li>Is there any <strong>train/test</strong> split already?</li><li>What is the <strong>class distribution</strong> for the dataset?</li></ul><p>From the data card, we learn that the dataset features <strong>six distinct facial emotions</strong>: <em>Happy, Angry, Sad, Neutral, Surprise</em> and Ahegao. With roughly 15,000 images and weighing in at around <strong>2.13 GB</strong>, the dataset is not a heavyweight, but enough to keep us busy. A quick snoop into the download directory reveals there’s <strong>no pre-defined train/test split</strong>. So, we’ll be rolling up our sleeves and doing that part ourselves. Furthermore, the images are in different formats (i.e .png, .jpg) and of different resolutions.</p><p>Before we dive into any modelling wizardry, let’s take a look at the <strong>class distribution</strong>. Here’s a quick code snippet to help us get a sense of what we’re working with:</p><pre>def get_class_distribution(dls):<br>    # Using list comprehension instead of .map()<br>    labels = [parent_label(x) for x in dls.train_ds.items]<br>    # Count occurrences of each label<br>    label_count = pd.Series(labels).value_counts()<br>    return label_count<br><br>path = Path(f&#39;{DATASET_DIRECTORY}/facial/dataset&#39;)<br><br>    # List of image formats to check<br>    image_extensions = [&#39;*.jpg&#39;, &#39;*.jpeg&#39;, &#39;*.png&#39;]<br><br>    # Get the class labels from the subdirectory names<br>    class_labels = [d.name for d in path.iterdir() if d.is_dir()]<br><br>    # Initialize a dictionary to hold counts<br>    label_counts = {}<br><br>    # Counting images in each class folder<br>    for label in class_labels:<br>        # Collect all files matching the image formats<br>        files = []<br>        for ext in image_extensions:<br>            files.extend(list((path / label).glob(ext)))<br><br>        label_counts[label] = len(files)<br>        print(f&quot;{label}: {label_counts[label]} images found&quot;)  # Debug print<br><br>    # Create a DataFrame for easier handling<br>    label_count_df = pd.Series(label_counts)<br><br>    # Normalizing the counts<br>    normalized_values = label_count_df / label_count_df.sum()<br><br>    # Plotting the class distribution<br>    fig, ax1 = plt.subplots(figsize=(10, 6))<br><br>    # Bar plot for counts<br>    color = &#39;mediumseagreen&#39;<br>    ax1.set_ylabel(&#39;Number of Images&#39;, color=&#39;black&#39;)<br>    bars = ax1.bar(label_count_df.index, label_count_df.values, color=color, alpha=0.7, label=&#39;Count&#39;)<br>    ax1.tick_params(axis=&#39;y&#39;, labelcolor=&#39;black&#39;)<br><br>    # Adding count labels on the bars with normalized values in brackets<br>    for i, bar in enumerate(bars):<br>        yval = bar.get_height()<br>        normalized_val = normalized_values[i]<br>        ax1.text(<br>            bar.get_x() + bar.get_width() / 2, yval,<br>            f&#39;{int(yval)} ({normalized_val:.2f})&#39;,<br>            ha=&#39;center&#39;, va=&#39;bottom&#39;,<br>            fontsize=14, fontweight=&#39;bold&#39;<br>        )<br><br>    # Set y-tick colors to black<br>    ax1.yaxis.set_tick_params(color=&#39;black&#39;)<br>    ax1.tick_params(axis=&#39;y&#39;, labelcolor=&#39;black&#39;, labelsize=16)<br>    ax1.tick_params(axis=&#39;x&#39;, labelsize=16)<br><br>    plt.title(&#39;Class Distribution&#39;, fontsize=16)<br>    fig.tight_layout()  # To prevent clipping of y-labels<br><br>    # Save the plot to a file<br>    plt.savefig(&#39;facial_dataset.png&#39;)</pre><p>This iterates through each of the class directories, counting the number of samples per class. We then generate a bar plot with normalised values on top of each bar. This results in the following plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9vvmECuSx7LyozlKnuOgLQ.png" /><figcaption>Class distribution for Facial Emotion Recognition Dataset</figcaption></figure><p>Looking at the class distribution plot, one thing becomes crystal clear: <strong>Sad, Happy, and Neutral</strong> are running the show. These three emotions dominate the dataset, while <strong>Angry, Ahegao, and Surprise</strong> are more like background characters — present, but not getting much screen time.</p><p>To get a clearer picture, we look at the <strong>normalised values</strong> instead of raw counts. And sure enough, the dataset is <strong>imbalanced</strong>. The top three emotions make up nearly 75% of the total samples, leaving the remaining three to share the last 25% like leftovers at a party.</p><p>This imbalance isn’t just a fun fact — it has real consequences. We can’t blindly trust <strong>accuracy </strong>as our go-to metric. Instead, we’ll need to choose our evaluation metrics wisely, or our model might just learn to play favourites with the majority classes. What we really want is a model that <strong>generalises well across <em>all</em> classes</strong>, not just the popular ones.</p><h4>Training a classifier</h4><p>Now that we have gone through the preliminaries, let&#39;s get to the good part and unleash the fury of Fastai on this dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*1Grf9wLa9xbPpXA1-jupgQ.gif" /><figcaption>Lets get to the good part</figcaption></figure><p>We set up the data preprocessing pipeline in the following code snippet, and this is where you get to observe the real magic of Fastai starting to shine:</p><pre> path = Path(f&quot;{DATASET_DIRECTORY}/facial/dataset&quot;)<br>    fnames = get_image_files(path)<br><br>   datablock = DataBlock(<br>        blocks=[ImageBlock, CategoryBlock],<br>        get_items=get_image_files,<br>        get_y=lambda x: x.parent.name,<br>        splitter=RandomSplitter(valid_pct=0.2, seed=62),<br>        item_tfms=[Resize(128)],<br>        batch_tfms=[*aug_transforms(<br>            do_flip=True, flip_vert=False, max_rotate=15.0,<br>            max_zoom=1.2, max_lighting=0.15, max_warp=0.15<br>        ), Normalize.from_stats(*imagenet_stats)]<br>    )</pre><p>This code snippet sets up a facial image classification pipeline using Fastai’s high-level API. It begins by pointing to the dataset directory and collecting image file paths. A DataBlock is then defined to specify how the data should be processed: images and their corresponding labels (inferred from folder names) are loaded, split into training and validation sets randomly, resized to 128×128 pixels, and augmented with a variety of transformations like flipping, rotation, zoom, lighting changes, and warping to improve model generalization. All of this happens <strong>in-memory and on-the-fly</strong>, so there’s no need to clutter up your disk with transformed copies. The images are also normalised using ImageNet statistics. The train/test ratio in this case is 80:20 as specified by the valid_pct parameter. We define a seed value so that the results of the split are reproducible. This is handy when debugging issues.</p><p>Since we are dealing with an image classification task, we choose the block combination as [ImageBlock, CategoryBlock]. Think of it as telling Fastai, <em>“Hey, I’m feeding you images, and I want a single class label in return.”</em> The get_items=get_image_files searches recursively for image files under the given path.</p><p>We use the lambda expression get_y=lambda x: x.parent.name to fetch the class label of each image. For Path(“data/happy/img1.jpg”), x.parent gives the folder “happy”, and we then extract its name. It’s a clean and elegant way to let Fastai know: <em>“Hey, the folder names are the classes!”</em></p><p>If we had a Multi-label Classification problem (a single image belonging to multiple labels), we could use the [ImageBlock, MultiCategoryBlock]. Similarly, for tabular data, Fastai provides the [TabularBlock, CategoryBlock]. The takeaway? <strong>Choose your blocks based on your data.</strong></p><p>A quick heads-up: Up to this point, we haven’t actually <em>fed</em> the dataset path into our DataBlock yet. Think of the DataBlock as a detailed <strong>blueprint</strong>—it lays out all the rules and logic to find images, grab their labels, and apply transformations. But no images have been touched or loaded yet. It’s like having a recipe without the ingredients on the counter.</p><p>The next step is to <strong>apply this blueprint to the actual dataset path</strong>, which creates something known as the <strong>DataLoader</strong>. This is where the magic starts happening — dls.train becomes our training DataLoader, and dls.valid is the validation DataLoader. It is also responsible for shuffling the images and for loading the dataset in batches.</p><pre># DataLoaders<br>    dls = datablock.dataloaders(path, bs=512)<br>    dls.show_batch(max_n=16, figsize=(12, 10))<br>    plt.savefig(&quot;sample_batch.png&quot;).</pre><p>We view the images to ensure that everything is working correctly. It yields the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*1rNHNEO3Djh0KX2ZfJ1YgQ.png" /><figcaption>Is that a Sad Kendall up there?</figcaption></figure><p>With the preprocessing pipeline setup, we are ready to train the model. With Fastai, we do this by setting up an learner object. This is THE fundamental Fastai’s all-in-one wrapper object that wraps your model, dataloaders, loss function, metrics, and optimiser. This is how we set it up:</p><pre># Define balanced accuracy metric<br>def balanced_accuracy(pred, targ):<br>    pred_classes = pred.argmax(dim=1)<br>    return balanced_accuracy_score(targ.cpu().numpy(), pred_classes.cpu().numpy())<br><br># Define the learner  <br>learn = vision_learner(<br>        dls,<br>        resnet50,  # You can change to resnet50 or efficientnet_b0<br>        metrics=[<br>            balanced_accuracy,<br>            error_rate<br>        ],<br>        #loss_func=CrossEntropyLossFlat(),<br>        loss_func=CrossEntropyLossFlat(weight=class_weights),<br>        cbs=[<br>            EarlyStoppingCallback(monitor=&#39;valid_loss&#39;, min_delta=2e-5, patience=5)<br>        ]<br>    )<br><br>learn.fine_tune(15) #Train for 15 epochs</pre><p>The line vision_learner(...) is where everything comes together. It instantiates the learner object, which bundles everything together. We configure over here the following things: <em>what</em> we’re training(our model architecture), <em>how</em> we’re measuring success (the metrics), and <em>how</em> the model should learn (the loss function and optimiser). It’s like giving your model the playbook, the scoreboard, and the coach’s strategy — all in one spot.</p><p>We chose the resnet50 as our model architecture. It&#39;s a deep convolutional neural network with 50 layers, pretrained on ImageNet (a dataset consisting of 14 million images). Next, we do not train just blindly. We supply it with some metrics on which we want to monitor progress. Instead of relying on the usual “accuracy” that claps even when your model just guesses the dominant class, we’re going with balanced_accuracy. Why? Because we like justice. This metric ensures that each class, even the poor, neglected underdog class with five examples, gets an equal say in the final score.</p><p>Now to the loss function. We use the weighted version of CrossEntropyLossFlat to offer justice to the underrepresented, minority classes. We could experiment with the magnitude of how much we want to lean towards a certain class by adjusting its respective weight. One logical way would be to take the inverse of frequencies — Remember the normalised class distribution bar plot that we looked at earlier? We use it to calculate class weights (manually in this case, but can be done programmatically).</p><pre>#Use inverse frequency weighting<br>#Weights ∝ 1 / class frequency<br>freqs = [0.25, 0.24, 0.09, 0.26, 0.08, 0.08]<br>weights = [1/f for f in freqs]<br># weights = [4.0, 4.17, 11.11, 3.85, 12.5, 12.5]</pre><p>The weights act like a fairness enforcer, ensuring that the model gets more scolding when it misclassifies minority classes. It’s tough love — but the kind that builds strong, unbiased classifiers. No favouritism allowed.</p><p>Next, we sprinkle in a bit of regularisation with the aid of EarlyStoppingCallback. It gives an ultimatum to the model: “Either you improve the validation loss by at least 2e-5 in the last 3 epochs or I’ll shut you down”. This helps ensure no extra GPU resources are burned once the model has converged and prevents <strong>overfitting</strong>.</p><p>Finally, we call learn.fine_tune(15). Lots of things happen under the hood. First, it <strong>freezes</strong> the earlier layers of the model — the part that came pretrained from ImageNet. That part already knows how to spot low-level features like edges, textures, and shapes. These layers are kept untouched. Then, only the last few layers, the task-specific ones, are trained for the first epoch. This lets the model adjust to our data without messing up its ImageNet knowledge. For the remaining epochs, the whole model is unfreezed and all the layers are trained together. This lets the earlier layers adjust, or rather, <em>fine-tune </em>themselves. It’s kind of like onboarding a new employee. You don’t dump the entire workload on them on day one — you let them ease in, get familiar with the environment, and then ramp them up to full speed.</p><p>With balanced accuracy to treat all classes fairly, weighted loss to guide learning responsibly, and early stopping to save time, we’ve successfully trained a pretty capable image classifier — all in just a few lines of code.</p><p>Let&#39;s see how well our training went. The following snippet shows the <strong>overall training progress</strong>, including training and validation losses:</p><pre>epoch     train_loss  valid_loss  balanced_accuracy  error_rate  time  <br>0         2.258573    1.322898    0.545027           0.487702    00:17     <br>epoch     train_loss  valid_loss  balanced_accuracy  error_rate  time  <br>1         1.464953    1.054469    0.624563           0.419094    00:18     <br>2         1.332102    0.952802    0.654121           0.376375    00:19     <br>3         1.185593    0.870330    0.679263           0.356311    00:18     <br>4         1.050331    0.776484    0.717971           0.308738    00:19     <br>5         0.916103    0.720079    0.739225           0.288026    00:19     <br>6         0.809862    0.669769    0.752199           0.275081    00:19     <br>7         0.728111    0.651762    0.759107           0.267314    00:19     <br>8         0.651435    0.633772    0.764556           0.259223    00:19     <br>9         0.596350    0.624853    0.770767           0.255340    00:18     <br>10        0.546412    0.615158    0.770622           0.254045    00:18     <br>11        0.510842    0.608150    0.776764           0.249191    00:19     <br>12        0.483607    0.605477    0.782771           0.241100    00:19     <br>13        0.459557    0.603901    0.778848           0.243366    00:19     <br>14        0.450227    0.604780    0.780232           0.241748    00:19</pre><p>By the end of training, we achieve a balanced accuracy of 0.78 — not bad for a model trained under a few minutes 🥳. Early stopping did not kick in, which means our model kept improving steadily without plateauing (nice!).</p><p>But we’re not done just yet. We evaluate our model on different metrics to see how good it is. At this point, though, the fundamental part is already done, and these are just cosmetic upgrades.</p><p>We next visualise the images which the model found the most challenging. This is achieved via the following lines:</p><pre>interp = ClassificationInterpretation.from_learner(learn)<br>    #Visualize hardest-to-classify samples<br>    interp.plot_top_losses(9, nrows=3)<br><br>    plt.savefig(&#39;top_losses.png&#39;, dpi=100)<br>    plt.close()</pre><p>It yields the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*K3Hoq6SuSGyCq8gAX2DRNA.png" /><figcaption>Top 9 images which confused the model the most</figcaption></figure><p>These are the images in which the model turned out to be overconfidently wrong.</p><p><strong>Images 1 and 3?</strong> Clearly mislabelled. The model actually predicted them correctly, but wasn’t rewarded for it. Why? Because <strong>life is unfair</strong> — and so are datasets sometimes.</p><p><strong>Images 5 and 9?</strong> Yep, these are genuine mistakes. The model swung… and missed.</p><p><strong>And the last image?</strong> That’s the universal <em>“you-stole-my-lollipop”</em> face. And no, that is <em>not</em> the look of a happy child — yet it may have been labelled as such.</p><p>The rest of the images are just <strong>hard to classify</strong>. They share features with multiple emotions — like a face that’s half surprised, half confused. So it’s no surprise the model was ‘emotionally’ confused.</p><p>We next generate a customised confusion matrix:</p><pre>    preds, targs = learn.get_preds()<br><br>    # Convert predicted probabilities to class indices<br>    y_pred = preds.argmax(dim=1).numpy()<br>    y_true = targs.numpy()<br><br>    # Now call the function<br>    generate_confusion_matrix(y_true, y_pred, learn)<br><br>def generate_confusion_matrix(y_true, y_pred,learn):<br>    cm = confusion_matrix(y_true, y_pred)<br>    cm_normalized = cm.astype(&#39;float&#39;) / cm.sum(axis=1)[:, np.newaxis]<br><br>    # Get class labels<br>    labels = learn.dls.vocab<br>    # Create annotations: counts + bold normalized percentages<br>    annot = np.empty_like(cm).astype(str)<br>    for i in range(cm.shape[0]):<br>        for j in range(cm.shape[1]):<br>            count = cm[i, j]<br>            percent = cm_normalized[i, j] * 100<br>            annot[i, j] = f&#39;{count}\n{percent:.1f}%&#39;<br><br>    # Plot heatmap with normalized values for coloring<br>    plt.figure(figsize=(10, 8))<br>    ax = sns.heatmap(<br>        cm_normalized,<br>        annot=annot,<br>        fmt=&#39;&#39;,<br>        cmap=&#39;RdYlGn&#39;,<br>        xticklabels=labels,<br>        yticklabels=labels,<br>        cbar=True,<br>        linewidths=0.5,<br>        linecolor=&#39;gray&#39;,<br>        annot_kws={&quot;size&quot;: 14, &quot;weight&quot;: &quot;bold&quot;},<br>        square=True<br>    )<br><br>    # Add colorbar label<br>    colorbar = ax.collections[0].colorbar<br>    colorbar.set_label(&#39;Proportion per True Label&#39;, fontsize=14)<br><br>    plt.xlabel(&#39;Predicted Label&#39;, fontsize=18)<br>    plt.ylabel(&#39;True Label&#39;, fontsize=18)<br>    plt.title(&#39;Confusion Matrix&#39;, fontsize=20)<br><br>    plt.xticks(fontsize=15)<br>    plt.yticks(fontsize=15)<br>    plt.tight_layout()<br><br>    # Save plot<br>    plt.savefig(&quot;confusion_matrix_with_percentages.png&quot;, dpi=300)<br>    plt.close()</pre><p>Again, since this is an imbalanced dataset, the <strong>normalised values</strong> are far more insightful than raw counts. For better interpretability, we use a <strong>colour-coded confusion matrix</strong>:</p><ul><li><strong>Green on the diagonal</strong> = correct predictions</li><li><strong>Red off-diagonal</strong> = misclassifications</li></ul><p>We want the diagonal elements to be green and the off-diagonal elements to be red. This turns out to be true, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kK5hEshmFSk_YF-zennHFw.png" /><figcaption>Overall model generalises well for all classes apart from Sad class — -thats sad</figcaption></figure><p>Sadly (😟 — pun intended), the <strong>sad</strong> class turns out to be the model’s Achilles heel, racking up the <strong>most misclassifications</strong>, <em>despite</em> being one of the majority classes. Maybe sadness really is harder to read. On the other hand, the <strong>Surprise </strong>😲 and <strong>Ahegao </strong>classes — both minority classes — had the <strong>highest correct prediction rates</strong>. It looks like the weighted loss did its job — giving the smaller voices a fairer shot.</p><p>⚠️ <strong>Quick sidenote:</strong> If you are not a big fan of this verbose code to generate the customised confusion matrix, you could skip these modifications and get a barebone working confusion matrix by calling the Fastai out-of-the-box method: interp.plot_confusion_matrix(figsize=(10,10)).</p><p>Lastly, to wrap things up, we view the Area Under the Curve of the Receiver Operating Characteristic curve. It’s a metric that evaluates how well your model separates the positive class from the negative class. The closer to 1, the better our model’s classification abilities. We achieve it via the following magic lines:</p><pre>roc_auc = roc_auc_score(<br>        y_true,<br>        preds,<br>        multi_class=&#39;ovr&#39;,<br>        average=&#39;macro&#39;<br>    )<br>    logger.info(f&quot;✅ ROC AUC (macro, OVR): {roc_auc:.4f}&quot;)</pre><p>This results in the following output:</p><pre>2025-05-27 23:13:43,250 - INFO - ✅ ROC AUC (macro, OVR): 0.9512</pre><p>A ROC AUC score of 0.95 is quite impressive — the ✅ emoji is 100% deserved.</p><p>Lastly, we play around with some other network architectures to see which of them proved to be the best for our dataset. We get the following outcome:</p><pre><br>| Architecture     | ROC AUC | Balanced Accuracy  |<br>|------------------|---------|--------------------|<br>| ResNet50         | 0.951   | 0.780              |<br>| EfficientNet-B0  | 0.887   | 0.634              |<br>| VGG16            | 0.941   | 0.747              |<br>| Alexnet          | 0.942   | 0.754              |<br>| DenseNet121      | 0.962   | 0.817              |</pre><p>On the scoreboard, we see that <strong>DenseNet121 </strong>clearly steals the spotlight here with superior results on both metrics, proving it’s not just dense in name but also in performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*igz0-Q4vsxFgJBsD-lYCtQ.gif" /><figcaption>DenseNet121 wins the gold!</figcaption></figure><p>Before I put my pen down, here are a few thought-provoking questions to tickle your data science brain:</p><ul><li>🤔 Why did DenseNet121 outperform the others?</li><li>🛠️ How could the other architectures be improved?</li><li>🔁 Would we see the same results if we changed the dataset? If not, why?</li></ul><p>These questions can be hard to answer. Answering them means putting on your data scientist hat, rolling up your sleeves, and diving deeper into model behaviour, dataset nuances, and architectural quirks.</p><p>But hey… maybe some other day. 😅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*cqpNKhPtjMqGscrUV57SYQ.gif" /><figcaption>Lets put on our data-scientist hat</figcaption></figure><p>And that’s a wrap! 🎉. We covered a lot of ground in this article. We took full advantage of Fastai’s powerful built-in methods to guide our model to a full spiritual journey: We began confused and biased, stumbled our way through imbalanced data, and slowly gained wisdom via a weighted loss function, trained under the supervision of balanced accuracy and evaluated under tough conditions posed by ROC AUC. The model knew when to train and when to stop (thanks, EarlyStopping), and most importantly, when to treat all classes with respect. It’s no longer just making predictions — it’s making <em>responsible</em> predictions. You can check out the whole code <a href="https://github.com/ZafarNaqv/Fastai-Demo">here</a>. Happy experimenting!</p><p>If you learned a thing or two, or just simply enjoyed this piece of writing, kindly hit the clap or subscribe button. I’d absolutely love to hear your thoughts, so feel free to drop a comment below. Don’t forget to check out my other stories<strong> </strong>too. Stay curious, stay kind, and stay blessed! 🙌✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=732c19782cb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gitlab Pipelines for Beginners]]></title>
            <link>https://medium.com/@xafar.nasim/gitlab-pipelines-for-beginners-62d16efd2869?source=rss-8ea3e7c88ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/62d16efd2869</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[Xafar Nasim]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 14:18:29 GMT</pubDate>
            <atom:updated>2024-09-15T10:16:29.290Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will focus on the essentials of creating a minimal GitLab pipeline, designed to trigger whenever a merge request is updated. We’ll start by exploring the benefits of using a CI/CD pipeline and then walk through building a basic one on GitLab.</p><p><strong><em>Why do we need a CI/CD pipeline in the first place?</em></strong></p><p>CI/CD pipelines significantly improve software development by automating repetitive tasks, enhancing code quality, and accelerating release cycles. They ensure every commit or merge triggers a consistent process, such as running tests and building code. By incorporating automated testing into the pipeline, developers can catch bugs or issues early, leading to more stable code. This automation gives developers confidence that their changes won’t break existing functionality or introduce compilation errors.</p><p>Before diving into the details, I strongly recommend reviewing the official <a href="https://docs.gitlab.com/ee/ci/pipelines/">GitLab documentation</a>. It’s thorough and provides a comprehensive understanding of the platform. Now, let’s walk through the steps to implement the pipeline.</p><p>GitLab automatically searches for a file named .gitlab-ci.yml in the root of your repository. You can create this file manually or use GitLab’s built-in online <a href="https://docs.gitlab.com/ee/ci/pipeline_editor/">pipeline editor</a>. The editor performs basic logical checks and offers helpful tips for troubleshooting any issues that arise.</p><p>Below is a minimal blueprint of the typical contents of .gitlab-ci.yml. While it can become much more complex as you incorporate additional tasks and functionality, this basic version will give you a brief overview of what to expect:</p><pre>stages:<br>  - name_of_stage1<br>  - name_of_stage2<br><br>job_name:<br>  stage: name_of_stage_in_which_this_job_needs_to_run<br>  image: optional_parameter_to_include_docker_image<br>  script:<br>    #Includes what this job should do<br>  rules:<br>   #When should this job be triggered</pre><p>The pipeline consists of multiple stages, each designed to perform a specific task. Within these stages, we define ‘jobs,’ which are the automated tasks we want to execute. A single stage can contain multiple jobs, and these jobs can run in parallel, without needing to wait for the completion of others in the same stage.</p><p>Pipelines stages will be displayed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*bj3LLlSLvnUWgbU_2MWDuw.png" /></figure><p>GitLab continuously updates the status of each stage, showing which stages and their associated jobs have passed or failed.</p><p>Now, let’s move on to setting up the pipeline. In this example, we’ll be compiling a Maven project on GitLab. For those unfamiliar with Maven, it’s a powerful dependency management tool. It uses a pom.xml file, located in the root of the repository, to list all the third-party libraries required for the project—such as loggers, testing frameworks, REST clients, parsers, and countless others. Maven auto-magically downloads these dependencies and includes them in the project’s classpath. The primary command we’ll run in our pipeline is:</p><pre>mvn clean compile</pre><p>Locally, everything works perfectly because I have Java and Maven installed and configured in my environment variables. However, on GitLab’s cloud, these tools are not available by default. This is where Docker comes into play.</p><p>Docker is an open-source platform that simplifies application management using containers — isolated, self-contained environments that package everything needed to run an application (code, libraries, dependencies, etc.). This eliminates the classic “works on my machine” problem caused by differences in software versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*N0YJRx9_G8yXTKQ1EHNm3Q.png" /><figcaption>Docker has made “It works on my machine” jokes obsolete</figcaption></figure><p>You don’t need to worry about creating a custom Docker container for this task. Below is the complete content of the .gitlab-ci.yml file:</p><pre>stages:<br>  - build<br>variables:<br>  MAVEN_OPTS: &quot;-Xmx512m&quot;  # Optional: Adjust Maven options as needed<br>compile:<br>  stage: build<br>  image: maven:3.8.5-openjdk-17  # Use a Maven image with JDK 17<br>  script:<br>    - echo &quot;Compiling Java project....&quot;<br>    - mvn clean compile  # Compile the Java code<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;  # Trigger when a merge request is created or updated</pre><p>For this project, we have a single stage called ‘build.’ The image key specifies the use of the maven:3.8.5-openjdk-17 image from Docker Hub, a public repository for Docker images. This image comes preconfigured with Maven (version 3.8.5) and OpenJDK (version 17), saving time and effort by eliminating the need to manually set up these tools for each build job.</p><p>Under the script section, we execute our primary Maven command, which is the core reason for setting up the pipeline. The rules section defines when a job should be triggered. In our case, we&#39;ve set a single rule to trigger the pipeline whenever a merge request is created or updated.</p><p>This is it. Your pipeline is ready to serve you! Commit the changes and view the ‘Pipelines’ tab on Gitlab. Here is how the tab should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*DhTwSY9KZPJHV1lmkRaiRQ.png" /><figcaption>Successful execution of a pipeline with a single job</figcaption></figure><p>Here are the abridged logs for the pipeline:</p><pre>Running with gitlab-runner 17.4.0~pre.110.g27400594 (27400594)<br>  on blue-1.saas-linux-small.runners-manager.gitlab.com/default j1aLDqxS, system ID: s_ccdc2f364be8<br>Preparing the &quot;docker+machine&quot; executor<br>00:18<br>Using Docker executor with image maven:3.8.5-openjdk-17 ...<br>Pulling docker image maven:3.8.5-openjdk-17 ...<br>Using docker image sha256:db741528e48aea788f63f806230fd5b3f0edcd0508dedd00357f069bc0c37ea0 for maven:3.8.5-openjdk-17 with digest maven@sha256:3a9c30b3af6278a8ae0007d3a3bf00fff80ec3ed7ae4eb9bfa1772853101549b ...<br>Preparing environment<br>00:04<br>Running on runner-j1aldqxs-project-61354551-concurrent-0 via runner-j1aldqxs-s-l-s-amd64-1725971624-95c605e4...<br>Getting source from Git repository<br>00:01<br>Fetching changes with git depth set to 20...<br>Initialized empty Git repository in /builds/xafar.nasim/booker/.git/<br>Created fresh repository.<br>Checking out 6459bb1b as detached HEAD (ref is refs/merge-requests/2/head)...<br>Skipping Git submodules setup<br>$ git remote set-url origin &quot;${CI_REPOSITORY_URL}&quot;<br>Executing &quot;step_script&quot; stage of the job script<br>00:11<br>Using docker image sha256:db741528e48aea788f63f806230fd5b3f0edcd0508dedd00357f069bc0c37ea0 for maven:3.8.5-openjdk-17 with digest maven@sha256:3a9c30b3af6278a8ae0007d3a3bf00fff80ec3ed7ae4eb9bfa1772853101549b ...<br>$ echo &quot;Compiling Java project....&quot;<br>Compiling Java project....<br>$ mvn clean compile<br>[INFO] Scanning for projects...<br>Downloading from central: https://repo.maven.apache.org/maven2/org/junit/junit-bom/5.11.0/junit-bom-5.11.0.pom<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/junit/junit-bom/5.11.0/junit-bom-5.11.0.pom (5.6 kB at 16 kB/s)<br>[INFO] <br>[INFO] -----------------------&lt; org.dasti.coder:Booker &gt;-----------------------<br>[INFO] Building Booker 1.0-SNAPSHOT<br>[INFO] --------------------------------[ jar ]---------------------------------<br>Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/3.4.0/maven-clean-plugin-3.4.0.pom<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/3.4.0/maven-clean-plugin-3.4.0.pom (5.5 kB at 124 kB/s)<br>Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-plugins/39/maven-plugins-39.pom<br>[INFO] <br>[INFO] --- maven-clean-plugin:3.4.0:clean (default-clean) @ Booker ---<br>Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/4.0.1/plexus-utils-4.0.1.pom<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/4.0.1/plexus-utils-4.0.1.pom (7.8 kB at 253 kB/s)<br>Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus/17/plexus-17.pom<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus/17/plexus-17.pom (28 kB at 939 kB/s)<br>Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/4.0.1/plexus-utils-4.0.1.jar<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/4.0.1/plexus-utils-4.0.1.jar (193 kB at 4.8 MB/s)<br>[INFO] <br>[INFO] --- maven-resources-plugin:3.3.1:resources (default-resources) @ Booker ---<br>Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-interpolation/1.26/plexus-interpolation-1.26.pom<br>Downloading from central: https://repo.maven.apache.org/maven2/commons-io/commons-io/2.11.0/commons-io-2.11.0.jar<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.5.1/plexus-utils-3.5.1.jar (269 kB at 5.1 MB/s)<br>[INFO] Copying 3 resources from src/main/resources to target/classes<br>[INFO] <br>[INFO] --- maven-compiler-plugin:3.13.0:compile (default-compile) @ Booker ---<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/2.15.0/plexus-compiler-manager-2.15.0.jar (5.2 kB at 79 kB/s)<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-xml/3.0.0/plexus-xml-3.0.0.jar (93 kB at 1.3 MB/s)<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/2.15.0/plexus-compiler-javac-2.15.0.jar (26 kB at 367 kB/s)<br>Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/4.0.0/plexus-utils-4.0.0.jar (192 kB at 2.3 MB/s)<br>[INFO] Recompiling the module because of changed dependency.<br>[INFO] Compiling 12 source files with javac [debug release 17] to target/classes<br>[INFO] ------------------------------------------------------------------------<br>[INFO] BUILD SUCCESS<br>[INFO] ------------------------------------------------------------------------<br>[INFO] Total time:  9.410 s<br>[INFO] Finished at: 2024-09-10T12:34:59Z<br>[INFO] ------------------------------------------------------------------------<br>Cleaning up project directory and file based variables<br>00:01<br>Job succeeded</pre><p>We see that initially it pulls the docker image maven:3.8.5-openjdk-17, prepares the environment and creates a fresh repository. It then executes our script and later cleans up the project directory.</p><p>Keep in mind that with each update to a merge request, the image is pulled again and Maven dependencies are <strong>re-downloaded</strong>. This is a small project where these steps took less than a minute but in practical scenarios, we might want to avoid these redundant steps and implement a caching mechanism. GitLab CI/CD supports caching in the .gitlab-ci.yml file, and while it&#39;s straightforward to configure, that&#39;s a topic for another discussion.</p><p>We could further extend this pipeline by adding a test stage to execute the mvn clean test command, provided the necessary dependencies are included.</p><p>In this discussion, we covered the advantages of having a CI/CD pipeline, reviewed a basic .gitlab-ci.yml blueprint, and implemented a simple, barebones pipeline for compiling Maven projects. This is just the beginning—there’s a lot more to explore. We could manage artefacts, include environment-specific variables, handle secrets, configure conditional jobs, and much more. As we delve deeper, we’ll find that the possibilities are virtually endless.</p><p>Lastly, if you felt you learned something today, kindly hit the clap/follow button. I would love to hear your feedback via comments. Stay Blessed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62d16efd2869" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering recursion]]></title>
            <link>https://medium.com/@xafar.nasim/mastering-recursion-c199bad1efa0?source=rss-8ea3e7c88ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c199bad1efa0</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[fibonacci]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[flood-fill]]></category>
            <dc:creator><![CDATA[Xafar Nasim]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 08:39:29 GMT</pubDate>
            <atom:updated>2025-06-25T11:51:09.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DhAqXhuQGJvgx_6oIhkKEg.gif" /><figcaption>Recursion is scary unless you embrace it</figcaption></figure><p>You might have been introduced to recursion while studying your first programming course. It may be the case that you have seldom used it in your everyday software development job. Chances are that you may have tried to avoid it and have gone with its “loops” alternative because tracking deep recursive calls can quickly get messy and tedious. However, you get a technical coding interview call from a well-reputed organisation, and you realise you need to step up your programming skills to another level. You will eventually find that recursion is one of the fundamental skills required to ace interviews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rFU9s63zoxdd-dF4iUOYA.png" /><figcaption>Google appreciating the beauty of recursion</figcaption></figure><p>In this blog, I expect the audience to have some basic knowledge about recursive calls. The main aim of this piece of writing is to help you get more familiar with it and try to remove your hesitance when adopting a recursive solution. All you need is fifteen, well-focused minutes and a sincere dedication towards learning something new. Grab a paper and pen. We will look into some programming problems. Try to give yourself a go first without reading further. I’ll try to :</p><ul><li>Diagnose whether applying recursion to a problem is a feasible option or not.</li><li>Highlight some of the decisions that one needs to consider when going for a recursive solution.</li><li>Look into some coding problems.</li></ul><p>Starting from scratch,<em> recursion is when a function calls itself</em>. Naturally to prevent the function calls to be stuck in an endless infinite loop, we plug in a base condition which on being met, terminates the function call. Writing a ‘bad base condition’ or missing an edge case may result in the notorious <strong>StackOverFlow </strong>error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*A5i2wr9KjlGzm7jE" /><figcaption>Why stack overflow occurs</figcaption></figure><p>Before we dive deep into actual use cases, let&#39;s digress for a moment to understand how the recursive calls are handled by the system. The underlying data structure to handle such calls is Stacks, the LIFO-flag bearer (Last in, First Out). To get the results of the initial first call, the latest function call has to be processed to the fullest. The variable values are saved before calling the next recursive call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*b5FBLVnrhdNCAudWQQr7gw.png" /><figcaption>Recursive calls handled by stack</figcaption></figure><p><em>So</em><strong><em> </em></strong><em>when is a problem, a good fit for recursion?</em></p><p>Generally, if you can break a problem into smaller pieces which are similar in nature and require similar processing, then recursion is a suitable candidate to be used. It should be kept in mind that an alternate iterative approach also exists for its recursive counterpart.</p><p>When coding a recursive function, we should ask ourselves the following questions:</p><ul><li>What should be the function parameters and return type?</li><li>What is the base/terminating condition?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFP2XEXXbJ2VlSTQ4hPutw.png" /></figure><p>It is my personal experience that when writing a recursive solution, one should directly start writing the problem with incremental steps without worrying about what&#39;s going to happen in the deeper function calls. If we start debugging deeper levels initially, chances are we would get confused about which variable state corresponds to which function call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*tajfPdyhQvmu-O6AuZpa7g.png" /><figcaption>Recursive one-liner</figcaption></figure><h3>Climbing the stairs problem</h3><p>We look into the following <a href="https://leetcode.com/problems/climbing-stairs/?envType=study-plan&amp;id=dynamic-programming-i">Leetcode problem of climbing the stairs</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*17kpfbf6zeBkDXtmzgec6A.png" /><figcaption>Leetcode Climbing staircase problem</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*EjBl3JxGKjOYV1AVtM0IVw.png" /><figcaption>Climbing Stairs problem with examples</figcaption></figure><p>Pause for a moment, and try to give yourself a go first before proceeding further.</p><p>To climb 1 step, you have 1 unique way.<br>To climb 2 steps, you have 2 unique ways.<br>To climb 3 steps, you have 3 unique ways. (2+1)<br>To climb 4 steps, you have 5 unique ways. (3+2)<br>To climb 5 steps, you have 8 unique ways. (5+3)</p><p>Did you notice a pattern in the number of unique ways per step? We notice that to calculate the number of steps (n) we simply sum up the total number of ways required to climb one step less than the required step (n-1) and two steps less than the required steps (n-2) which is none other than the Fibonacci series in disguise. Observe how the actual problem cleverly avoided the term ‘Fibonacci series’ in the question and left it for the candidates to decode. This is one of the tricks that the interviewer may use to test your sharpness.</p><p><em>The </em><strong><em>Fibonacci Sequence</em></strong><em> is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … The next number is found by adding up the two numbers before it.</em></p><p>For any number n, we need the result of its two previous numbers in the sequence, that is n-1 and n-2, then Fibannaci(n) can simply be calculated by summing them up. We realise that the only <em>parameter </em>required is the current index of the series. The <em>return type</em> is the actual number calculated. However, unlike the Fibonacci series which starts from 0, the climbing stairs sequence starts from 1,2,3,5 and so on. We assume n is a positive integer. We deduce two base conditions on the above argument:</p><ul><li>If n is equal to 1, we return 1.</li><li>If n is equal to 2, we return 2.</li></ul><p>Hence we arrive at the following code solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*l-IFhzTUtDh-lD3ibe6Uqg.png" /><figcaption>Code for climbing stairs</figcaption></figure><p>We can refactor the code in a slightly smart way to reduce the number of lines :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*E_90Bo0Ug_3u6MypupU5Bg.png" /><figcaption>Reducing lines because lines are money</figcaption></figure><h3>Flood Fill</h3><p>We now look into a slightly complicated Leetcode problem: <a href="https://leetcode.com/problems/flood-fill/?envType=study-plan&amp;id=algorithm-i">Flood Fill</a></p><pre>An image is represented by an m x n integer grid image where image[i][j]<br>represents the pixel value of the image.<br><br>You are also given three integers sr, sc, and color. You should perform a<br>flood fill on the image starting from the pixel image[sr][sc].<br><br>To perform a flood fill, consider the starting pixel, plus any pixels<br>connected 4-directionally to the starting pixel of the same color as the<br>starting pixel, plus any pixels connected 4-directionally to those pixels<br>(also with the same color), and so on. Replace the color of all of the<br>aforementioned pixels with color.<br><br>Return the modified image after performing the flood fill.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*supZmv_1MYjL3U7yoopTIw.png" /><figcaption>Flood fill example</figcaption></figure><p><em>Is this a good candidate to write a recursive solution?</em></p><p>No matter which index position we are at, we need to check if it has the same colour as the starting colour, if that is true, we look into all four directions. For this recursion sounds like a good idea.</p><p>Looking into the problem, we get the idea that we need to traverse the array from the initial index in all four directions given that certain conditions are met. Traversing in all directions means that there are chances we may get out of bounds from the 2d-array so every time we are stepping into some direction, we need to first check whether that particular index is within the boundaries defined by the 2d-array.</p><p>This time I created a helper function which will play the role of a recursive function. Initially, we check if the starting index has the same colour as the new colour, if that is true, we return the image as it is. If not, we call the recursive function. We directly assign the index the new colour. Then we go in each direction doing the exact same thing. For example, to go up, we decrement one from its column. Incrementing and decrementing rows and columns alternatingly will enable us to ‘walk’ in all four directions.</p><p>This yields the following code snippet:</p><pre>public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {<br>  int startingColor = image[sr][sc];<br>  if(startingColor==newColor) return image;<br>  helper(image,sr,sc,startingColor,newColor);<br>  return image;<br>}<br><br><br>public int[][] helper(int[][] image, int sr, int sc,int startingColor,int newColor) {<br>  image[sr][sc] = newColor;<br>          if (sr  &lt; image.length-1 &amp;&amp; image[sr+1][sc]==startingColor) {//down<br>              floodFill(image, sr + 1, sc, newColor);<br>          }<br>          if (sc &lt; image[0].length-1 &amp;&amp; image[sr][sc+1]==startingColor){//right<br>              floodFill(image, sr, sc + 1, newColor);<br>          }<br>          if (sr  &gt; 0  &amp;&amp; image[sr-1][sc]==startingColor) {//up<br>              floodFill(image, sr - 1, sc, newColor);<br>          }<br>          if (sc  &gt; 0 &amp;&amp; image[sr][sc-1]==startingColor) {//left<br>              floodFill(image, sr, sc - 1, newColor);<br>          }<br>  return image;<br>}</pre><p><em>How does ‘flood fill’ happen?</em></p><p>The code flow proceeds in such a way that we keep on going down and down until and unless ‘the next down step’ goes out of bounds or the next index colour is not the starting colour — a dead end. Next, we try to move towards the ‘right’. If it is possible then we again start to step down. In a similar fashion, we move up and left respectively. After we have exhausted all four directions, the latest function call is complete and then we <em>‘</em><strong><em>backtrack</em></strong><em>’. </em>That automatically happens when the current function call is complete, removed from the stack and the control resumes from the previous function call.</p><p>Notice how I have passed the starting colour and new colour in each function call. You can avoid this by setting them up as instance variables enabling them to be accessible by each function call. We pass the image as a parameter because we want each function call to have the latest version of the grid. We just did <strong><em>Depth First Search</em></strong><em>, </em>an algorithm used for graph traversals. Notice how this term is not mentioned at all in the question. (You can use other traversal methods to achieve the goal also). The solution is complete.</p><h3>Max Area of Island</h3><p>Finally, we look into yeh another problem: the <a href="https://leetcode.com/problems/max-area-of-island/?envType=study-plan&amp;id=algorithm-i">Max Area of the Island</a>. Here&#39;s the situation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*so3zorwhRE5zX6hcvHU95w.png" /><figcaption>Max Area of Island</figcaption></figure><p><em>Is this a good candidate to write a recursive solution?</em></p><p>We basically need to find the island with the biggest area i.e most number of 1s. An area is considered an island if it has 1s connected four-directionally. This again is a naturally recursive problem. No matter where we are on the grid, we need to check and move in all 4-possible directions. We will apply depth-first search again to rescue us. However, there will be some modifications compared to flood-fill.</p><p>We first need to visit all the nodes/indices irrespective of whether they are islands or not. This is because islands are isolated from each other, we never know whether the current biggest island is truly the biggest until and unless we have explored all the indices. In flood fill, we were only interested in the ‘region of influence’ of the initial starting pixel. So it was highly likely that there might be undiscovered nodes as well.</p><pre>public int maxAreaOfIsland(int[][] grid) {<br>        visited = new int[grid.length][grid[0].length];<br>        for (int i = 0; i &lt; grid.length; i++) {<br>            for (int j = 0; j &lt; grid[i].length; j++) {<br>                 currentIsland=0;<br>                if(isAllNodesVisited())<br>                    return maxIsland;<br>                 dfSearch(i,j);<br>            }<br><br>        }<br>        return maxIsland;<br>    }</pre><p>The nested loops allow us to traverse the whole grid. If we have visited all the nodes, we return the biggest island size. Otherwise, we do a depth-first search.</p><pre>public boolean isAllNodesVisited(){<br>        for (int i = 0; i &lt; visited.length; i++) {<br>            for (int j = 0; j &lt; visited[0].length; j++) {<br>                if (visited[i][j] != 1) ;<br>                return false;<br>            }<br>        }<br>        return true;<br>    }</pre><p>We keep track of the nodes visited in a new 2D array. If there exists an index with ‘0’ in it, it means all nodes are not visited. We use nested loops to traverse and check the array.</p><p>The whole code is given below:</p><pre>public class DFS {<br>    public static final String ANSI_RED = &quot;\u001B[31m&quot;;<br>    public static final String ANSI_RESET = &quot;\u001B[0m&quot;;<br>    <br>    int[][] grid;<br>    int maxIsland;<br>    int currentIsland;<br>    int[][] visited;<br><br>    public DFS(int[][] grid){<br>        this.grid = grid;<br>    }<br>    public int maxAreaOfIsland(int[][] grid) {<br>        visited = new int[grid.length][grid[0].length];<br>        for (int i = 0; i &lt; grid.length; i++) {<br>            for (int j = 0; j &lt; grid[i].length; j++) {<br>                 currentIsland=0;<br>                if(isAllNodesVisited())<br>                    return maxIsland;<br>                 dfSearch(i,j);<br>            }<br><br>        }<br>        return maxIsland;<br>    }<br><br>private void dfSearch(int i,int j) {<br>    if(visited[i][j]==0) {<br>        visited[i][j] = 1;<br>        if (grid[i][j] == 1) {<br>            currentIsland++;<br>            if (i + 1 &lt; grid.length &amp;&amp; visited[i + 1][j] == 0 &amp;&amp; grid[i + 1][j] == 1) {//down<br>                dfSearch(i + 1, j);<br>            }<br>            if (j + 1 &lt; grid[0].length &amp;&amp; visited[i][j + 1] == 0 &amp;&amp; grid[i][j + 1] == 1) {//right<br>                dfSearch(i, j + 1);<br>            }<br>            if (i - 1 &gt;= 0 &amp;&amp; visited[i - 1][j] == 0 &amp;&amp; grid[i - 1][j] == 1) {//up<br>                dfSearch(i - 1, j);<br>            }<br>            if (j - 1 &gt;= 0 &amp;&amp; visited[i][j - 1] == 0 &amp;&amp; grid[i][j - 1] == 1) {//left<br>                dfSearch(i, j - 1);<br>            }<br>            maxIsland = Math.max(currentIsland,maxIsland);<br>        }<br>    }<br><br>}<br><br>public void printGrid(){<br>    System.out.println(&quot;Original Image:&quot;);<br>    for (int i = 0; i &lt; grid.length; i++) {<br>        for (int j = 0; j &lt; grid[i].length; j++) {<br>            if(grid[i][j]==1){<br>                System.out.print(ANSI_RED +  grid[i][j]+ &quot; &quot; + ANSI_RESET);<br>            }else {<br>                System.out.print(grid[i][j] + &quot; &quot;);<br>            }<br>        }<br>        System.out.println();<br>    }<br><br>}<br><br>    public boolean isAllNodesVisited(){<br>        for (int i = 0; i &lt; visited.length; i++) {<br>            for (int j = 0; j &lt; visited[0].length; j++) {<br>                if (visited[i][j] != 1) ;<br>                return false;<br>            }<br>        }<br>        return true;<br>    }<br><br>  public static void main(String args[])<br>  {<br>      int[][] grid =  {{0,0,1,0,0,0,0,1,0,0,0,0,0},{0,0,0,0,0,0,0,1,1,1,0,0,0},{0,1,1,0,1,0,0,0,0,0,0,0,0},<br>              {0,1,0,0,1,1,0,0,1,0,1,0,0},{0,1,0,0,1,1,0,0,1,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,1,0,0},<br>              {0,0,0,0,0,0,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,1,1,0,0,0,0}};<br>      //int[][] grid = {{0,1},{1,1}};<br>      DFS dfsObj = new DFS(grid);<br>      dfsObj.printGrid();<br>      System.out.println(dfsObj.maxAreaOfIsland(grid));<br>  }<br><br>}</pre><p>The function ‘dfSearch’ is similar to the flood-fill, we check the array bounds and keep on moving in all four directions given that we are walking on the island (indices with ‘1’). Before moving to another index, we update the ‘visited’ array, move to a new position, increment the current index and compare the maxIsland with the currentIsland size and update it if possible.</p><p><em>The return type of the recursive flood fill function was integer while in this case, it&#39;s void. Why?</em></p><p>This depends on how one codes. In flood fill, we didn’t use any instance variables, so we supplied them as function parameters. In the max island case, we use instance variables ‘currentIsland’ and ‘maxIsland’ to keep track of the data in which we are interested. Each function call has access to them so there is no need to supply them via parameters.</p><p>Well, that’s it, folks. Recursion can be confusing and difficult to grasp for newbies. There are times when you are stuck on a problem for hours. The only way forward is to be persistent and keep practising. Also, my recommendation is to go through other people’s codes for the same problem. You will see clever ideas coded in an intricate manner, some optimised, and some unoptimised. When you do feel confident writing recursive solutions, head towards your next challenge: <em>dynamic programming,</em> which goes hand in hand with recursion.</p><p>Kindly like, subscribe, and share the article. Let me know in the comments below your thoughts about this piece of writing. I will be waiting. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c199bad1efa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Living in Germany-a perspective from a Pakistani]]></title>
            <link>https://medium.com/@xafar.nasim/living-in-germany-a-perspective-from-a-pakistani-bffb8cff992?source=rss-8ea3e7c88ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bffb8cff992</guid>
            <category><![CDATA[germany]]></category>
            <category><![CDATA[living-abroad]]></category>
            <category><![CDATA[study-abroad]]></category>
            <category><![CDATA[pakistan]]></category>
            <category><![CDATA[life-in-germany]]></category>
            <dc:creator><![CDATA[Xafar Nasim]]></dc:creator>
            <pubDate>Sun, 03 Apr 2022 13:56:19 GMT</pubDate>
            <atom:updated>2025-06-25T13:59:31.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxkcwOPzM8bJcMa-fsYdSw.png" /></figure><p>It&#39;s been a while since I moved to Germany. I met people from different cultural backgrounds, got my opinions changed and overall learned a great deal. I wanted to share my views since when one is new, they notice small details which go unnoticed by someone who has already spent a lot of time here. I will go with an alternating pro-con detail to maintain balance. However do note that these are my opinions, I can be wrong and you can all agree to disagree with me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*r-TDfhzeO5eG3-I1w5ijVA.png" /><figcaption>Pro: Despite the language barrier, Germany attracts a lot of international students mainly due to their quality education system</figcaption></figure><p><strong>Free Public Education</strong></p><p>I found the German educational system to be amazing. It&#39;s simply awesome to see that you get to have such state of the art facilities at your disposal at the expense of little to almost no fees (for a public university). The faculty members are well experienced, they do not digress from the topics under discussion and their lectures are well planned. The system is strong enough to distinguish between a hard-working student from one who studies at the last minute. If you think you can catch onto a course by studying during the last two weeks then I am sorry but you are misguided (Of course you can point you some exceptions but I am just talking about the majority). Shallow readers (students who study from slides only) will always find a hard time here than those who take the pain of opening the books.</p><p>Conversely, your grade is decided solely on your exams which I feel is unfair since you may end up with a bad grade if you get a brain freeze during the exam. An overall grade accumulated from mid-term exams, assignments, quizzes and final exam is a much better estimation of the true ability of a pupil. However some universities do follow a different grading scheme.</p><p><strong>Mediocre customer service</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*-L6NK0E8q_Gje9c0C4GdTw.png" /><figcaption>Con : Average customer service</figcaption></figure><p>You go to a restaurant, you do not get free water which comes as a bit of a shock. Similarly, when you order fries or pommes (in German), you expect them to come with ketchup. But no!!!. You only get what you ordered. You need to pay extra for the ketchup. It&#39;s like buying bread without butter or a toothbrush without toothpaste. Similarly when I went to open an account in a local bank ( I couldn’t make an appointment online since it was all German) the person only made me an appointment for the next day and I was not entertained further. Had I wanted to open a bank account in my home country, I would not require any appointment, the person would have offered me tea and asked me how can they be of service. Moreover, we had to wait an entire week for our internet connection to be fixed (the technician came on the fourth day after the complaint!). Unfortunately the saying “Customer is the king” is not well known here.</p><p><strong>Marvellous transportation system</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MR50_izePYpB9mqP9l2G_g.png" /><figcaption>Snapshot from the youtube video Getting Past German Immigration | Foil Arms and Hog appreciates the punctuality of the German transport system</figcaption></figure><p>I was pretty much impressed with the transport system. People, especially students can dwell without a car and still be satisfied. The trains/buses/HBahns are almost always on time. You get empty seats to sit on (some people would rather choose to stand during their entire journey). There is no conductor, the bus driver is the conductor :).Unlike in Pakistan, buses only stop at their designed stops. Public transport are clean and offer charging ports for your devices. You do not have to bang on the doors to indicate you want to get off, you simply press the stop button. A small detail to note is that upon stopping, the buses slightly “bend” down a bit from one side making it easier for the passengers to get off.</p><p><strong>A bit of a cultural shock</strong></p><p>According to one local that I met, “English is good but the German language goes through the heart of the people”. I certainly agree with them. Sooner you will realise in order to fully understand the culture, one has to learn the local language. And that is absolutely logical, locals should promote their own language. The Friday prayer sermons are also in German, which is another reason to learn the language. That being said, learning a language needs commitment and time. You can’t expect someone to start speaking fluent German in a month. Speaking a new language makes you feel like a child all over again, with less confidence and completely out of your comfort zone. Moreover, sometimes it can be difficult as when you are struggling with German, some locals may switch to English to make yourself comfortable (which is good for getting tasks done but bad for the linguistic part).</p><p>Also, I found the locals quite reserved and not willing to engage in small talk with strangers. This is ethically good but it makes it harder to get to know their culture. Keep in mind this does not mean that Germans are not helpful, when you ask them for help i.e directions, they will try their best to assist you even with the language barrier.</p><p>Beers, smoking and alcohol are pretty much common. I was surprised to find alcohol even in bread. If you do not consume alcohol, you should either read the ingredients carefully or use an application that scans the barcode to distinguish whether the item is worth consuming. However, this is pretty much expected in a non-Muslim country.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dCjy7PGe3po8ZFqFTHEsw.png" /><figcaption>Most people would be engrossed in mobile phones rather than engaging in conversations-even on long-distance journeys</figcaption></figure><p>I found German people to be disciplined, punctual and law-abiding. They take care of the environment and avoid littering. They are and expect other people to be on time for meetings and other planned activities. They give importance to their health: You will find them cycling, exercising in the gym or even jogging along the road. They follow the traffic rules religiously and show respect to the pedestrians -they will slow down their vehicle even when the pedestrian is far away and will allow them to cross the road first. On the other hand, some of their habits are culturally and religiously prohibited from an Islamic point of view. Hence in my opinion the best way to learn from their culture is to adopt a hybrid lifestyle: Discard your own bad habits, retain your good ones and adopt only their good qualities.</p><p>Lastly, I would like to state what I found out what Germans know about Pakistan. Even though my interaction was a bit limited due to Covid restrictions and online classes, I found what they know about us by engaging them through social platforms. In the majority of the cases (like 5 out of 5 :) ), they tend to confuse us with Indians, mainly due to our similar facial characteristics. When I informed them that I came from Pakistan, a couple of them said “Oh wow, strong army, destroy India,grapppe”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tBoDY22geliLR1px46XEQ.png" /><figcaption>A viral video that made its way to Germany</figcaption></figure><p>That was just embarrassing for me. We can’t even imagine how far these stupid and nonsense videos can travel and influence people. It shows such a bad image of our country and portrays our mindset in a negative way.</p><p>In summary, I would say experiencing a different culture is worth it. You get to be independent, see so many unique things and most important of all, learn to own your decisions. Of course, every country has got its good and bad side. It&#39;s up to us what we choose and what we reject. Below are some more small details that couldn’t be described in detail.</p><p>◙ When you buy a plastic bottle, you get charged extra. You earn them back when you return them to recycling machines.</p><p>◙ Major supermarkets and stores are closed on Sundays.</p><p>◙ To use a trolley in a supermarket, you need to insert a 50cent/1 Euro coin. You get the coin back once you “attach” the trolley back to other trollies.</p><p>◙ For the majority of your travelling within inter-city, you would not be checked for a ticket. However, don’t get cocky. If caught, you will be fined 60 Euros.</p><p>◙ Many people especially foreign students drink tap water.</p><p>◙ Waste has to be discarded separately depending on its type i.e biodegradable, plastic, glass. The waste bins are colour coded.</p><p>◙ You will find people putting their expensive phones in the back pocket of their pants. If you do not understand the uniqueness of this, try doing it in Pakistan and you will understand it within a week.</p><p>If I missed anything or you want to share your opinion, kindly let me know in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bffb8cff992" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DBScan Inside Out]]></title>
            <link>https://medium.com/@xafar.nasim/dbscan-inside-out-e9192bae7dc7?source=rss-8ea3e7c88ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9192bae7dc7</guid>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dbscan]]></category>
            <dc:creator><![CDATA[Xafar Nasim]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 11:41:57 GMT</pubDate>
            <atom:updated>2022-02-14T11:41:57.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWL-DnRB80i9fH1AFyWd3g.png" /><figcaption>(From Ester et al. 1996) Clusters of different sizes, shapes and densities</figcaption></figure><p>In this article, we are going to explore some of the weaknesses of the K-means clustering algorithm and how much success does DBScan gain in attempting to solve them.</p><p>Here’s a brief overview of how the K-means algorithm works:<br>1. We choose K, which are the number of clusters the dataset will be broken down into.</p><p>2. We randomly choose K points as centroids. This random initialisation leads to different clustering results as K-means can get trapped in a local maximum.</p><p>3. For every point we calculate its distance from the K centroids. Whichever centroid has the smallest distance, that point is assigned to that centroid’s cluster. Since all points are assigned to one of the clusters, there are no noise points.</p><p>4. We now calculate the mean point for each cluster which may result in a new centroid. We then repeat from Step 3 until the centroids no longer change.</p><p>Often when introducing clustering, K-means is the first method we are taught. That’s because K means is super easy to implement, often used to get an insight of the data in a short amount of time before investing time<br>on any other algorithm. However despite being dead simple, one of the crucial drawbacks of K-means is deducing the ‘K’ parameter<br>by the user. That ‘K’ is responsible to find out the total number of clusters in the dataset. It&#39;s like asking someone “Ask me a question” and they reply by saying “Okay. What do I ask?”. The original reason to employ an unsupervised algorithm in the task was to find out how many clusters existed. And if we are going to do that critical decision making ourselves then K-means is just a mere function in which you input the clusters you need and it&#39;s going to output the dataset into that number of clusters forcefully, even if the dataset does not have to be ‘grouped into that many clusters’.</p><p>Let&#39;s try to see how k-means performs on the following dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*2D-jCDKKHREkwewVXz5d5A.png" /><figcaption>Scatterplot for a random dataset</figcaption></figure><p>Intuitively, two clusters can clearly be identified. Let&#39;s plug in K=2 and evaluate the results. After all, what could go wrong?.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*MTo4fCVr3kXfqCHqlY1bNg.png" /><figcaption>Scatterplot with k=2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*kWcCKHUhYzSDKe8MYjHTqw.png" /><figcaption>That was….unexpected</figcaption></figure><p>Hmmm…That’s weird, instead of identifying the smaller lower cluster, K-means split up the bigger one into two chunks. Moreover, data points that are slightly far from both clusters are also allocated to some clustering, in other words, no noise points.</p><p>Let’s experiment with some more values of k.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1SAaYrAOszY4qVd4JWvyA.png" /><figcaption>Scatterplots with different values of k. k=3 (Top Left), k=4 (Top Right), k=5 (Bottom Left) , k=10 (Bottom Right)</figcaption></figure><p>Instead of cleaning up the mess, increasing the value for k splits up the bigger cluster into smaller and smaller pieces. On k=10 the original lower cluster seems to be recognised as an individual cluster, but by that time the bigger cluster has been completely butchered.</p><p>Some more key points to note for K-means are:</p><ol><li>All the data points in a cluster are centred around the cluster mean resulting in spherically shaped clusters.</li><li>K-means cannot identify arbitrary shaped or non-convex clusters (Shapes with an inwards edge).</li></ol><h3>DBScan to the rescue</h3><p>I may have been a bit too harsh on K-means. It&#39;s a good algorithm that does its job when it&#39;s required to do so. However, this toy example is all we need to motivate ourselves to understand DBScan, another un-supervised algorithm that overcomes the need of specifying the doomed parameter K.</p><p><strong>DBSCAN</strong> stands for <strong>D</strong>ensity-<strong>B</strong>ased <strong>S</strong>patial <strong>C</strong>lustering of <strong>A</strong>pplications with <strong>N</strong>oise. The main idea of DBScan is to label those areas as clusters where the data points are dense. Data points that are close to each other in a small region contribute to a cluster. The “dense-ness” of a point is defined by these two user-defined parameters:</p><ol><li>ε-radius: This is the maximum distance for a single data point till which we are going to consider its neighbourhood.</li><li>MinPoints: This is the minimum number of data points that need to exist for a given point in order to form a cluster.</li></ol><p>A few common terminologies used to specify the type of data points in DBScan are:</p><ol><li>Core point: A point is called a core point if it has greater than or equal to MinPoints within its vicinity. The vicinity is the ε-radius.</li><li>Border point: A point that is included in the neighbourhood of a core point, but it doesn’t itself contains data points equal or greater than MinPoints is labelled as a border point.</li><li>Noise: A data point that is not within the ε-radius of a core point and does not have neighbouring data points equal to or greater than MinPoints is considered as a noise object.</li></ol><p>Let’s digress for a moment and try to understand this through an analogy. Every person has a sphere of influence through which they can convince people to do something. A celebrity (core object) has to have a certain number of followers (MinPoints) in order to be considered popular, hence having some influence amongst them. These followers have their own sphere of influence. They have to be well-connected with each other within a region (ε-radius) in order to establish unity. Together they all contribute to a strong fan-following (cluster). Border objects can be considered those followers which do not ‘propagate the influence of the celebrity’ to other people. On the other hand, noise are those people who are neither fans nor do they have a strong friend circle.</p><p>For better understanding we will dry run DBScan on the given data points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*gTu3SIEm3YKXjxFZTsRNgg.png" /></figure><p>For this example,<strong> we will consider ε-radius to be 2 and MinPoints to be 3</strong>. When counting the MinPoints of a data point, we will <strong>include</strong> that data point itself also. We will use the Manhattan distance to find out the distances between two points. We iterate over all the points, identifying their neighbours and finding out the type of the datapoint. If the data point is a core object then we put all its neighbours into a cluster (if they aren’t already assigned to one). For ease, we start our iteration in ascending order, but that doesn’t always have to be the case.</p><p>For point 1:</p><p>It has data points 2,3,4 within its ε-radius<strong> </strong>neighbourhood. It has total of 4 neighbours (including itself) and exceeds the MinPoints threshold. Hence it is regarded as a core object and 1,2,3,4 are included in cluster 1.</p><p>For point 2: It has data points 1,3,4 as its neighbour. It is also a core point. Since the data point neighbours and the data point itself are already included in cluster c1, we will not do any action for point 2.</p><p>The results are summarised in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*raph3NVHr2vSncmKnCb04A.png" /><figcaption>DBScan in action</figcaption></figure><p>Point 7 which belongs to cluster C1 is a border point since it has only 2 neighbours which are less than MinPoints.Point 8 also has 2 neighbours but since it is not included in any cluster, it will be labelled as a noise object. Hence there are two clusters with points (1,2,3,4,5,6,7) and (10,11,12,13,14).</p><p>One small detail to note here is that had we first started our iteration from point 7 it would have been classified as a noise point. But as soon as we process its core neighbour(s) i.e in this case point 6, point 7 will be updated from a noise point to a border object. In this way, the overall result of the clustering remains unchanged.</p><p>Coming back to the original dataset, let&#39;s run DBScan on it and evaluate the results to see whether it can identify the two clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*A0xYfIz_Z4zCz9cuiHKUbQ.png" /><figcaption>DBScan result on the original dataset</figcaption></figure><p>Viola!. DBScan has successfully identified the two clusters. Moreover, unlike K-means, noise objects which do not fulfil the ε-radius and MinPoints criteria have also been detected and are labelled as black.</p><p>DBScan can accurately identify non-convex and arbitrary shaped clusters. It can separate the noise objects from the clusters. It doesn’t require the number of clusters to find as input. It has resolved the dreaded K-parameter issue. However, in trying to do so, it has introduced its own parameters,ε-radius and MinPoints. DBScan became the very thing, it was trying to destroy :P. Experimenting with these two parameters can greatly affect the clustering result. Therefore the user is again in the dilemma of choosing the right values for these params to figure out the ideal clustering.</p><h3>Conclusion</h3><p>We reviewed how K-means work, explored its weaknesses and saw how it performed badly in a seemly innocent dataset. We then introduced DBScan and worked on a small problem. Finally, we executed DBScan on the original dataset and found out that it correctly identified the clustering which the K-means was unable to find. However, it too falls prey to parameter tuning.</p><p>I hope you gained some valuable knowledge from this piece of writing. If there are any shortcomings or suggestions that you would like to offer, kindly post them in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9192bae7dc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>