<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" 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">
    <channel>
        <title>Gopal Verma</title>
        <link>https://gopalverma.com</link>
        <description>Gopal Verma's Portfolio</description>
        <lastBuildDate>Thu, 12 Nov 2026 09:57:08 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>Gopal Verma</title>
            <url>https://gopalverma.com/og.jpg</url>
            <link>https://gopalverma.com</link>
        </image>
        <copyright>CC BY-NC-SA 4.0 2026 © Gopal Verma</copyright>
        <atom:link href="https://gopalverma.com/feed.xml" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[Every Ending Has a Doorway]]></title>
            <link>https://gopalverma.com/diary/blogs/every-ending-has-a-doorway</link>
            <guid>https://gopalverma.com/diary/blogs/every-ending-has-a-doorway</guid>
            <pubDate>Tue, 10 Nov 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[A reflection on what remains when something ends: the silence, the space it leaves, and the person who walks out the other side, stronger, sharper, and ready for whatever comes next.]]></description>
            <content:encoded><![CDATA[<p>Nobody tells you that endings are quiet.</p>
<p>We expect something loud: a final scene, a closing line, a moment where the music swells and we know it's over. In reality, the end is usually small. A door clicks shut. A routine stops repeating. One day you realise you haven't done something for a week, then a month, and the absence has quietly become the new normal.</p>
<h1>The last time is never announced</h1>
<p>Think of the last time you walked a street you used to walk every day. You didn't know it was the last time. You were probably looking at your phone, or thinking about dinner. Nothing marked it as special.</p>
<p>That is the strange cruelty of endings. The moments we would most like to memorise pass without ceremony. We only learn they were final in hindsight, when we try to go back and find the door has changed.</p>
<p>I spent months turning this over. At first with a heaviness I couldn't name, then with a kind of puzzled attention, the way you look at a familiar room after the furniture has been taken out. Everything is where it was, but the shape of the space is different.</p>
<h1>The silence after the song</h1>
<p>There is a pause at the end of a good album. The last note fades, and for a few seconds the room feels larger than it did before. You are still holding the music, but it is no longer there.</p>
<p>Most of us rush to fill that silence. We press play again, open another app, stay busy. I did all of that. For a while I treated silence as a problem to be solved.</p>
<p>But silence is not emptiness. It is room. It is the part of the page that lets the words mean something. And space is the one thing nothing new can grow without.</p>
<h1>The hard middle</h1>
<p>I won't pretend the middle was gentle.</p>
<p>There were days that felt like standing in a storm with no shelter and no map. Days when the old routine reached for me out of habit and found nothing there. Days when I was sure I had lost more than I could ever rebuild.</p>
<p>That stretch has no glamour. No one applauds you for getting through an ordinary Tuesday while carrying something heavy. But those were the days that did the real work. Quietly, without witnesses, something was being taken apart and put back together.</p>
<h1>What a forest knows</h1>
<p>In a forest, a tree falls. From a distance it looks like loss. A great shape that held up the sky is now lying on the ground.</p>
<p>Look closer a year later. The trunk is soft with moss. Fungi and seedlings have made a home in it. Light reaches the forest floor for the first time in decades, and things begin to grow that never could have in the shade.</p>
<p>The forest doesn't see the fall as failure. It treats it as a transfer, one form of life turning into the conditions for another. Nature has never had a word for &quot;the end&quot; that means <em>nothing comes after</em>. That idea belongs to us.</p>
<h1>We don't grieve midnight</h1>
<p>Every day ends. At midnight, an entire day, with all its plans and small victories, closes for good. Yet we don't stand at the clock in mourning. We sleep, and we wake into a morning.</p>
<p>The only difference between midnight and the endings that hurt is that midnight is expected. We trust it because we have seen the morning come a thousand times.</p>
<p>Maybe the work of growing up is extending that same trust to the endings that arrive without warning. Not pretending they don't hurt, but believing, on evidence, that the morning is coming.</p>
<p>For me, it came.</p>
<h1>Who walked out</h1>
<p>Here is the part I couldn't have believed back then.</p>
<p>The person who walked into that chapter is not the person who walked out of it. I don't mean slightly improved. I mean rebuilt.</p>
<p>I am calmer, and not because things got easier, but because I now know what I can survive. I am sharper, because pain is a ruthless teacher and I paid attention. I listen better. I know exactly what I need, what I refuse to tolerate, and what I am no longer willing to shrink myself for. My standards moved up. My fear moved down. My sense of self stopped depending on anyone's approval.</p>
<p>I am more in every sense: more patient, more focused, more honest, more dangerous in the best way. The version of me that stood in the wreckage would barely recognise the one writing this.</p>
<p>Nothing was wasted. Every hour of that chapter, even the hardest ones, became material. I walked out carrying tools I didn't have when I walked in.</p>
<h1>The doorway</h1>
<p>I used to picture endings as walls. Solid, final, impossible to pass through. You hit one, you stop, and you stand there looking at what is no longer reachable.</p>
<p>Now I picture them as doorways. Heavy, unfamiliar, a little frightening. But a doorway is, by definition, a way to somewhere else.</p>
<p>And I have stepped through. I'm no longer waiting at the threshold for the old room to change. The light on this side is different, softer in some places, sharper in others, and I am walking toward it with my head up.</p>
<h1>The next storm</h1>
<p>I know what's coming, because life doesn't run out of storms. There will be another challenge, another battle, another moment where everything I've built is tested again. Maybe soon. Maybe when I least expect it.</p>
<p>Let it come.</p>
<p>I'm not afraid of it the way I once would have been. I have already been broken open and rebuilt, and I know now that I can walk into the thing that scares me and come out the other side stronger. That knowledge is something no one can take from me.</p>
<p>So here is where I stand. The old chapter is closed, and I closed it on my own terms. The person I am today is stronger than the one who started it, and the one I'll be tomorrow will be stronger still.</p>
<p>Every ending is a beginning in disguise. Mine just took its disguise off.</p>
<p>Bring on the next one. I'm ready to win it.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Introduction to Scikit-Learn]]></title>
            <link>https://gopalverma.com/diary/notes/ml-intro-scikit-learn</link>
            <guid>https://gopalverma.com/diary/notes/ml-intro-scikit-learn</guid>
            <pubDate>Tue, 10 Nov 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Quick summary to Scikit-Learn]]></description>
            <content:encoded><![CDATA[<p>This note is inspired by the <a href="https://github.com/jakevdp/PythonDataScienceHandbook/tree/master">Python Data Science Handbook by Jake VanderPlas</a>.<br>
Thanks <a href="https://x.com/jakevdp">@jakevdp</a>!</p>
<p>There are several Python libraries that provide solid implementations of a range of machine learning algorithms.<br>
One of the best known is <a href="http://scikit-learn.org">Scikit-Learn</a>, a package that provides efficient versions of a large number of common algorithms.<br>
Scikit-Learn is characterized by a clean, uniform, and streamlined API, as well as by very useful and complete online documentation.<br>
A benefit of this uniformity is that once you understand the basic use and syntax of Scikit-Learn for one type of model, switching to a new model or algorithm is straightforward.</p>
<p>This chapter provides an overview of the Scikit-Learn API. A solid understanding of these API elements will form the foundation for understanding the deeper practical discussion of machine learning algorithms and approaches in the following chapters.</p>
<p>We will start by covering data representation in Scikit-Learn, then delve into the Estimator API, and finally go through a more interesting example of using these tools for exploring a set of images of handwritten digits.</p>
<h2>Data Representation in Scikit-Learn</h2>
<p>Machine learning is about creating models from data: for that reason, we'll start by discussing how data can be represented.<br>
The best way to think about data within Scikit-Learn is in terms of <em>tables</em>.</p>
<p>A basic table is a two-dimensional grid of data, in which the rows represent individual elements of the dataset, and the columns represent quantities related to each of these elements.<br>
For example, consider the <a href="https://en.wikipedia.org/wiki/Iris_flower_data_set">Iris dataset</a>, famously analyzed by Ronald Fisher in 1936.<br>
We can download this dataset in the form of a Pandas <code>DataFrame</code> using the <a href="http://seaborn.pydata.org/">Seaborn</a> library, and take a look at the first few items:</p>
<p>Here each row of the data refers to a single observed flower, and the number of rows is the total number of flowers in the dataset.<br>
In general, we will refer to the rows of the matrix as <em>samples</em>, and the number of rows as <code>n_samples</code>.</p>
<p>Likewise, each column of the data refers to a particular quantitative piece of information that describes each sample.<br>
In general, we will refer to the columns of the matrix as <em>features</em>, and the number of columns as <code>n_features</code>.</p>
<h3>The Features Matrix</h3>
<p>The table layout makes clear that the information can be thought of as a two-dimensional numerical array or matrix, which we will call the <em>features matrix</em>.<br>
By convention, this matrix is often stored in a variable named <code>X</code>.<br>
The features matrix is assumed to be two-dimensional, with shape <code>[n_samples, n_features]</code>, and is most often contained in a NumPy array or a Pandas <code>DataFrame</code>, though some Scikit-Learn models also accept SciPy sparse matrices.</p>
<p>The samples (i.e., rows) always refer to the individual objects described by the dataset.<br>
For example, a sample might represent a flower, a person, a document, an image, a sound file, a video, an astronomical object, or anything else you can describe with a set of quantitative measurements.</p>
<p>The features (i.e., columns) always refer to the distinct observations that describe each sample in a quantitative manner.<br>
Features are often real-valued, but may be Boolean or discrete-valued in some cases.</p>
<h3>The Target Array</h3>
<p>In addition to the feature matrix <code>X</code>, we also generally work with a <em>label</em> or <em>target</em> array, which by convention we will usually call <code>y</code>.<br>
The target array is usually one-dimensional, with length <code>n_samples</code>, and is generally contained in a NumPy array or Pandas <code>Series</code>.<br>
The target array may have continuous numerical values, or discrete classes/labels.<br>
While some Scikit-Learn estimators do handle multiple target values in the form of a two-dimensional, <code>[n_samples, n_targets]</code> target array, we will primarily be working with the common case of a one-dimensional target array.</p>
<p>A common point of confusion is how the target array differs from the other feature columns. The distinguishing characteristic of the target array is that it is usually the quantity we want to <em>predict from the features</em>: in statistical terms, it is the dependent variable.<br>
For example, given the preceding data we may wish to construct a model that can predict the species of flower based on the other measurements; in this case, the <code>species</code> column would be considered the target array.</p>
<p>With this target array in mind, we can use Seaborn (discussed in <a href="04.14-Visualization-With-Seaborn.ipynb">Visualization With Seaborn</a>) to conveniently visualize the data (see the following figure):</p>
<p>For use in Scikit-Learn, we will extract the features matrix and target array from the <code>DataFrame</code>, which we can do using some of the Pandas <code>DataFrame</code> operations discussed in <a href="03.00-Introduction-to-Pandas.ipynb">Part 3</a>:</p>
<p>To summarize, the expected layout of features and target values is visualized in the following figure.</p>
<p><img src="images/05.02-samples-features.png" alt=""><br>
<a href="https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/06.00-Figure-Code.ipynb#Features-and-Labels-Grid">figure source in Appendix</a></p>
<p>With this data properly formatted, we can move on to consider Scikit-Learn's Estimator API.</p>
<h2>The Estimator API</h2>
<p>The Scikit-Learn API is designed with the following guiding principles in mind, as outlined in the <a href="http://arxiv.org/abs/1309.0238">Scikit-Learn API paper</a>:</p>
<ul>
<li>
<p><em>Consistency</em>: All objects share a common interface drawn from a limited set of methods, with consistent documentation.</p>
</li>
<li>
<p><em>Inspection</em>: All specified parameter values are exposed as public attributes.</p>
</li>
<li>
<p><em>Limited object hierarchy</em>: Only algorithms are represented by Python classes; datasets are represented<br>
in standard formats (NumPy arrays, Pandas <code>DataFrame</code> objects, SciPy sparse matrices) and parameter<br>
names use standard Python strings.</p>
</li>
<li>
<p><em>Composition</em>: Many machine learning tasks can be expressed as sequences of more fundamental algorithms,<br>
and Scikit-Learn makes use of this wherever possible.</p>
</li>
<li>
<p><em>Sensible defaults</em>: When models require user-specified parameters, the library defines an appropriate default value.</p>
</li>
</ul>
<p>In practice, these principles make Scikit-Learn very easy to use, once the basic principles are understood.<br>
Every machine learning algorithm in Scikit-Learn is implemented via the Estimator API, which provides a consistent interface for a wide range of machine learning applications.</p>
<h3>Basics of the API</h3>
<p>Most commonly, the steps in using the Scikit-Learn Estimator API are as follows:</p>
<ol>
<li>Choose a class of model by importing the appropriate estimator class from Scikit-Learn.</li>
<li>Choose model hyperparameters by instantiating this class with desired values.</li>
<li>Arrange data into a features matrix and target vector, as outlined earlier in this chapter.</li>
<li>Fit the model to your data by calling the <code>fit</code> method of the model instance.</li>
<li>Apply the model to new data:
<ul>
<li>For supervised learning, often we predict labels for unknown data using the <code>predict</code> method.</li>
<li>For unsupervised learning, we often transform or infer properties of the data using the <code>transform</code> or <code>predict</code> method.</li>
</ul>
</li>
</ol>
<p>We will now step through several simple examples of applying supervised and unsupervised learning methods.</p>
<h3>Supervised Learning Example: Simple Linear Regression</h3>
<p>As an example of this process, let's consider a simple linear regression—that is, the common case of fitting a line to $(x, y)$ data.<br>
We will use the following simple data for our regression example (see the following figure):</p>
<p>With this data in place, we can use the recipe outlined earlier. Let's walk through the process:</p>
<h4>1. Choose a class of model</h4>
<p>In Scikit-Learn, every class of model is represented by a Python class.<br>
So, for example, if we would like to compute a simple <code>LinearRegression</code> model, we can import the linear regression class:</p>
<p>Note that other more general linear regression models exist as well; you can read more about them in the <a href="http://Scikit-Learn.org/stable/modules/linear_model.html"><code>sklearn.linear_model</code> module documentation</a>.</p>
<h4>2. Choose model hyperparameters</h4>
<p>An important point is that <em>a class of model is not the same as an instance of a model</em>.</p>
<p>Once we have decided on our model class, there are still some options open to us.<br>
Depending on the model class we are working with, we might need to answer one or more questions like the following:</p>
<ul>
<li>Would we like to fit for the offset (i.e., <em>y</em>-intercept)?</li>
<li>Would we like the model to be normalized?</li>
<li>Would we like to preprocess our features to add model flexibility?</li>
<li>What degree of regularization would we like to use in our model?</li>
<li>How many model components would we like to use?</li>
</ul>
<p>These are examples of the important choices that must be made <em>once the model class is selected</em>.<br>
These choices are often represented as <em>hyperparameters</em>, or parameters that must be set before the model is fit to data.<br>
In Scikit-Learn, hyperparameters are chosen by passing values at model instantiation.<br>
We will explore how you can quantitatively choose hyperparameters in <a href="05.03-Hyperparameters-and-Model-Validation.ipynb">Hyperparameters and Model Validation</a>.</p>
<p>For our linear regression example, we can instantiate the <code>LinearRegression</code> class and specify that we would like to fit the intercept using the <code>fit_intercept</code> hyperparameter:</p>
<p>Keep in mind that when the model is instantiated, the only action is the storing of these hyperparameter values.<br>
In particular, we have not yet applied the model to any data: the Scikit-Learn API makes very clear the distinction between <em>choice of model</em> and <em>application of model to data</em>.</p>
<h4>3. Arrange data into a features matrix and target vector</h4>
<p>Previously we examined the Scikit-Learn data representation, which requires a two-dimensional features matrix and a one-dimensional target array.<br>
Here our target variable <code>y</code> is already in the correct form (a length-<code>n_samples</code> array), but we need to massage the data <code>x</code> to make it a matrix of size <code>[n_samples, n_features]</code>.<br>
In this case, this amounts to a simple reshaping of the one-dimensional array:</p>
<h4>4. Fit the model to the data</h4>
<p>Now it is time to apply our model to the data.<br>
This can be done with the <code>fit</code> method of the model:</p>
<p>This <code>fit</code> command causes a number of model-dependent internal computations to take place, and the results of these computations are stored in model-specific attributes that the user can explore.<br>
In Scikit-Learn, by convention all model parameters that were learned during the <code>fit</code> process have trailing underscores; for example in this linear model, we have the following:</p>
<p>These two parameters represent the slope and intercept of the simple linear fit to the data.<br>
Comparing the results to the data definition, we see that they are close to the values used to generate the data: a slope of 2 and intercept of –1.</p>
<p>One question that frequently comes up regards the uncertainty in such internal model parameters.<br>
In general, Scikit-Learn does not provide tools to draw conclusions from internal model parameters themselves: interpreting model parameters is much more a <em>statistical modeling</em> question than a <em>machine learning</em> question.<br>
Machine learning instead focuses on what the model <em>predicts</em>.<br>
If you would like to dive into the meaning of fit parameters within the model, other tools are available, including the <a href="http://statsmodels.sourceforge.net/"><code>statsmodels</code> Python package</a>.</p>
<h4>5. Predict labels for unknown data</h4>
<p>Once the model is trained, the main task of supervised machine learning is to evaluate it based on what it says about new data that was not part of the training set.<br>
In Scikit-Learn, this can be done using the <code>predict</code> method.<br>
For the sake of this example, our &quot;new data&quot; will be a grid of <em>x</em> values, and we will ask what <em>y</em> values the model predicts:</p>
<p>As before, we need to coerce these <em>x</em> values into a <code>[n_samples, n_features]</code> features matrix, after which we can feed it to the model:</p>
<p>Finally, let's visualize the results by plotting first the raw data, and then this model fit (see the following figure):</p>
<p>Typically the efficacy of the model is evaluated by comparing its results to some known baseline, as we will see in the next example.</p>
<h3>Supervised Learning Example: Iris Classification</h3>
<p>Let's take a look at another example of this process, using the Iris dataset we discussed earlier.<br>
Our question will be this: given a model trained on a portion of the Iris data, how well can we predict the remaining labels?</p>
<p>For this task, we will use a simple generative model known as <em>Gaussian naive Bayes</em>, which proceeds by assuming each class is drawn from an axis-aligned Gaussian distribution (see <a href="05.05-Naive-Bayes.ipynb">In Depth: Naive Bayes Classification</a> for more details).<br>
Because it is so fast and has no hyperparameters to choose, Gaussian naive Bayes is often a good model to use as a baseline classification, before exploring whether improvements can be found through more sophisticated models.</p>
<p>We would like to evaluate the model on data it has not seen before, so we will split the data into a <em>training set</em> and a <em>testing set</em>.<br>
This could be done by hand, but it is more convenient to use the <code>train_test_split</code> utility function:</p>
<p>With the data arranged, we can follow our recipe to predict the labels:</p>
<p>Finally, we can use the <code>accuracy_score</code> utility to see the fraction of predicted labels that match their true values:</p>
<p>With an accuracy topping 97%, we see that even this very naive classification algorithm is effective for this particular dataset!</p>
<h3>Unsupervised Learning Example: Iris Dimensionality</h3>
<p>As an example of an unsupervised learning problem, let's take a look at reducing the dimensionality of the Iris data so as to more easily visualize it.<br>
Recall that the Iris data is four-dimensional: there are four features recorded for each sample.</p>
<p>The task of dimensionality reduction centers around determining whether there is a suitable lower-dimensional representation that retains the essential features of the data.<br>
Often dimensionality reduction is used as an aid to visualizing data: after all, it is much easier to plot data in two dimensions than in four dimensions or more!</p>
<p>Here we will use <em>principal component analysis</em> (PCA; see <a href="05.09-Principal-Component-Analysis.ipynb">In Depth: Principal Component Analysis</a>), which is a fast linear dimensionality reduction technique.<br>
We will ask the model to return two components—that is, a two-dimensional representation of the data.</p>
<p>Following the sequence of steps outlined earlier, we have:</p>
<p>Now let's plot the results. A quick way to do this is to insert the results into the original Iris <code>DataFrame</code>, and use Seaborn's <code>lmplot</code> to show the results (see the following figure):</p>
<p>We see that in the two-dimensional representation, the species are fairly well separated, even though the PCA algorithm had no knowledge of the species labels!<br>
This suggests to us that a relatively straightforward classification will probably be effective on the dataset, as we saw before.</p>
<h3>Unsupervised Learning Example: Iris Clustering</h3>
<p>Let's next look at applying clustering to the Iris data.<br>
A clustering algorithm attempts to find distinct groups of data without reference to any labels.<br>
Here we will use a powerful clustering method called a <em>Gaussian mixture model</em> (GMM), discussed in more detail in <a href="05.12-Gaussian-Mixtures.ipynb">In Depth: Gaussian Mixture Models</a>.<br>
A GMM attempts to model the data as a collection of Gaussian blobs.</p>
<p>We can fit the Gaussian mixture model as follows:</p>
<p>As before, we will add the cluster label to the Iris <code>DataFrame</code> and use Seaborn to plot the results (see the following figure):</p>
<p>By splitting the data by cluster number, we see exactly how well the GMM algorithm has recovered the underlying labels: the <em>setosa</em> species is separated perfectly within cluster 0, while there remains a small amount of mixing between <em>versicolor</em> and <em>virginica</em>.<br>
This means that even without an expert to tell us the species labels of the individual flowers, the measurements of these flowers are distinct enough that we could <em>automatically</em> identify the presence of these different groups of species with a simple clustering algorithm!<br>
This sort of algorithm might further give experts in the field clues as to the relationships between the samples they are observing.</p>
<h2>Application: Exploring Handwritten Digits</h2>
<p>To demonstrate these principles on a more interesting problem, let's consider one piece of the optical character recognition problem: the identification of handwritten digits.<br>
In the wild, this problem involves both locating and identifying characters in an image. Here we'll take a shortcut and use Scikit-Learn's set of preformatted digits, which is built into the library.</p>
<h3>Loading and Visualizing the Digits Data</h3>
<p>We can use Scikit-Learn's data access interface to take a look at this data:</p>
<p>The images data is a three-dimensional array: 1,797 samples each consisting of an 8 × 8 grid of pixels.<br>
Let's visualize the first hundred of these (see the following figure):</p>
<p>In order to work with this data within Scikit-Learn, we need a two-dimensional, <code>[n_samples, n_features]</code> representation.<br>
We can accomplish this by treating each pixel in the image as a feature: that is, by flattening out the pixel arrays so that we have a length-64 array of pixel values representing each digit.<br>
Additionally, we need the target array, which gives the previously determined label for each digit.<br>
These two quantities are built into the digits dataset under the <code>data</code> and <code>target</code> attributes, respectively:</p>
<p>We see here that there are 1,797 samples and 64 features.</p>
<h3>Unsupervised Learning Example: Dimensionality Reduction</h3>
<p>We'd like to visualize our points within the 64-dimensional parameter space, but it's difficult to effectively visualize points in such a high-dimensional space.<br>
Instead, we'll reduce the number of dimensions, using an unsupervised method.<br>
Here, we'll make use of a manifold learning algorithm called Isomap (see <a href="05.10-Manifold-Learning.ipynb">In-Depth: Manifold Learning</a>) and transform the data to two dimensions:</p>
<p>We see that the projected data is now two-dimensional.<br>
Let's plot this data to see if we can learn anything from its structure (see the following figure):</p>
<p>This plot gives us some good intuition into how well various numbers are separated in the larger 64-dimensional space. For example, zeros and ones have very little overlap in the parameter space.<br>
Intuitively, this makes sense: a zero is empty in the middle of the image, while a one will generally have ink in the middle.<br>
On the other hand, there seems to be a more or less continuous spectrum between ones and fours: we can understand this by realizing that some people draw ones with &quot;hats&quot; on them, which causes them to look similar to fours.</p>
<p>Overall, however, despite some mixing at the edges, the different groups appear to be fairly well localized in the parameter space: this suggests that even a very straightforward supervised classification algorithm should perform suitably on the full high-dimensional dataset.<br>
Let's give it a try.</p>
<h3>Classification on Digits</h3>
<p>Let's apply a classification algorithm to the digits data.<br>
As we did with the Iris data previously, we will split the data into training and testing sets and fit a Gaussian naive Bayes model:</p>
<p>Now that we have the model's predictions, we can gauge its accuracy by comparing the true values of the test set to the predictions:</p>
<p>With even this very simple model, we find about 83% accuracy for classification of the digits!<br>
However, this single number doesn't tell us where we've gone wrong. One nice way to do this is to use the <em>confusion matrix</em>, which we can compute with Scikit-Learn and plot with Seaborn (see the following figure):</p>
<p>This shows us where the mislabeled points tend to be: for example, many of the twos here are misclassified as either ones or eights.</p>
<p>Another way to gain intuition into the characteristics of the model is to plot the inputs again, with their predicted labels.<br>
We'll use green for correct labels and red for incorrect labels; see the following figure:</p>
<p>Examining this subset of the data can give us some insight into where the algorithm might be not performing optimally.<br>
To go beyond our 83% classification success rate, we might switch to a more sophisticated algorithm such as support vector machines (see <a href="05.07-Support-Vector-Machines.ipynb">In-Depth: Support Vector Machines</a>), random forests (see <a href="05.08-Random-Forests.ipynb">In-Depth: Decision Trees and Random Forests</a>), or another classification approach.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Kernel Density Estimation]]></title>
            <link>https://gopalverma.com/diary/notes/ml-kernel-density-estimation</link>
            <guid>https://gopalverma.com/diary/notes/ml-kernel-density-estimation</guid>
            <pubDate>Tue, 10 Nov 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Quick summary to Kernel Density Estimation]]></description>
            <content:encoded><![CDATA[<p>This note is inspired by the <a href="https://github.com/jakevdp/PythonDataScienceHandbook/tree/master">Python Data Science Handbook by Jake VanderPlas</a>.<br>
Thanks <a href="https://x.com/jakevdp">@jakevdp</a>!</p>
<p><em>Kernel density estimation</em> (KDE) is in some senses an algorithm that takes the mixture-of-Gaussians idea to its logical extreme: it uses a mixture consisting of one Gaussian component <em>per point</em>, resulting in an essentially nonparametric estimator of density.<br>
In this chapter, we will explore the motivation and uses of KDE.</p>
<p>We begin with the standard imports:</p>
<h2>Motivating Kernel Density Estimation: Histograms</h2>
<p>As mentioned previously, a density estimator is an algorithm that seeks to model the probability distribution that generated a dataset.<br>
For one-dimensional data, you are probably already familiar with one simple density estimator: the histogram.<br>
A histogram divides the data into discrete bins, counts the number of points that fall in each bin, and then visualizes the results in an intuitive manner.</p>
<p>For example, let's create some data that is drawn from two normal distributions:</p>
<p>We have previously seen that the standard count-based histogram can be created with the <code>plt.hist</code> function.<br>
By specifying the <code>density</code> parameter of the histogram, we end up with a normalized histogram where the height of the bins does not reflect counts, but instead reflects probability density (see the following figure):</p>
<p>Notice that for equal binning, this normalization simply changes the scale on the y-axis, leaving the relative heights essentially the same as in a histogram built from counts.<br>
This normalization is chosen so that the total area under the histogram is equal to 1, as we can confirm by looking at the output of the histogram function:</p>
<p>One of the issues with using a histogram as a density estimator is that the choice of bin size and location can lead to representations that have qualitatively different features.<br>
For example, if we look at a version of this data with only 20 points, the choice of how to draw the bins can lead to an entirely different interpretation of the data!<br>
Consider this example, visualized in the following figure:</p>
<p>On the left, the histogram makes clear that this is a bimodal distribution.<br>
On the right, we see a unimodal distribution with a long tail.<br>
Without seeing the preceding code, you would probably not guess that these two histograms were built from the same data. With that in mind, how can you trust the intuition that histograms confer?<br>
And how might we improve on this?</p>
<p>Stepping back, we can think of a histogram as a stack of blocks, where we stack one block within each bin on top of each point in the dataset.<br>
Let's view this directly (see the following figure):</p>
<p>The problem with our two binnings stems from the fact that the height of the block stack often reflects not the actual density of points nearby, but coincidences of how the bins align with the data points.<br>
This misalignment between points and their blocks is a potential cause of the poor histogram results seen here.<br>
But what if, instead of stacking the blocks aligned with the <em>bins</em>, we were to stack the blocks aligned with the <em>points they represent</em>?<br>
If we do this, the blocks won't be aligned, but we can add their contributions at each location along the x-axis to find the result.<br>
Let's try this (see the following figure):</p>
<p>The result looks a bit messy, but it's a much more robust reflection of the actual data characteristics than is the standard histogram.<br>
Still, the rough edges are not aesthetically pleasing, nor are they reflective of any true properties of the data.<br>
In order to smooth them out, we might decide to replace the blocks at each location with a smooth function, like a Gaussian.<br>
Let's use a standard normal curve at each point instead of a block (see the following figure):</p>
<p>This smoothed-out plot, with a Gaussian distribution contributed at the location of each input point, gives a much more accurate idea of the shape of the data distribution, and one that has much less variance (i.e., changes much less in response to differences in sampling).</p>
<p>What we've landed on in the last two plots is what's called kernel density estimation in one dimension: we have placed a &quot;kernel&quot;—a square or &quot;tophat&quot;-shaped kernel in the former, a Gaussian kernel in the latter—at the location of each point, and used their sum as an estimate of density.<br>
With this intuition in mind, we'll now explore kernel density estimation in more detail.</p>
<h2>Kernel Density Estimation in Practice</h2>
<p>The free parameters of kernel density estimation are the <em>kernel</em>, which specifies the shape of the distribution placed at each point, and the <em>kernel bandwidth</em>, which controls the size of the kernel at each point.<br>
In practice, there are many kernels you might use for kernel density estimation: in particular, the Scikit-Learn KDE implementation supports six kernels, which you can read about in the <a href="http://scikit-learn.org/stable/modules/density.html">&quot;Density Estimation&quot; section</a> of the documentation.</p>
<p>While there are several versions of KDE implemented in Python (notably in the SciPy and <code>statsmodels</code> packages), I prefer to use Scikit-Learn's version because of its efficiency and flexibility.<br>
It is implemented in the <code>sklearn.neighbors.KernelDensity</code> estimator, which handles KDE in multiple dimensions with one of six kernels and one of a couple dozen distance metrics.<br>
Because KDE can be fairly computationally intensive, the Scikit-Learn estimator uses a tree-based algorithm under the hood and can trade off computation time for accuracy using the <code>atol</code> (absolute tolerance) and <code>rtol</code> (relative tolerance) parameters.<br>
The kernel bandwidth can be determined using Scikit-Learn's standard cross-validation tools, as we will soon see.</p>
<p>Let's first show a simple example of replicating the previous plot using the Scikit-Learn <code>KernelDensity</code> estimator (see the following figure):</p>
<p>The result here is normalized such that the area under the curve is equal to 1.</p>
<h2>Selecting the Bandwidth via Cross-Validation</h2>
<p>The final estimate produced by a KDE procedure can be quite sensitive to the choice of bandwidth, which is the knob that controls the bias–variance trade-off in the estimate of density.<br>
Too narrow a bandwidth leads to a high-variance estimate (i.e., overfitting), where the presence or absence of a single point makes a large difference. Too wide a bandwidth leads to a high-bias estimate (i.e., underfitting), where the structure in the data is washed out by the wide kernel.</p>
<p>There is a long history in statistics of methods to quickly estimate the best bandwidth based on rather stringent assumptions about the data: if you look up the KDE implementations in the SciPy and <code>statsmodels</code> packages, for example, you will see implementations based on some of these rules.</p>
<p>In machine learning contexts, we've seen that such hyperparameter tuning often is done empirically via a cross-validation approach.<br>
With this in mind, Scikit-Learn's <code>KernelDensity</code> estimator is designed such that it can be used directly within the package's standard grid search tools.<br>
Here we will use <code>GridSearchCV</code> to optimize the bandwidth for the preceding dataset.<br>
Because we are looking at such a small dataset, we will use leave-one-out cross-validation, which minimizes the reduction in training set size for each cross-validation trial:</p>
<p>Now we can find the choice of bandwidth that maximizes the score (which in this case defaults to the log-likelihood):</p>
<p>The optimal bandwidth happens to be very close to what we used in the example plot earlier, where the bandwidth was 1.0 (i.e., the default width of <code>scipy.stats.norm</code>).</p>
<h2>Example: Not-so-Naive Bayes</h2>
<p>This example looks at Bayesian generative classification with KDE, and demonstrates how to use the Scikit-Learn architecture to create a custom estimator.</p>
<p>In <a href="05.05-Naive-Bayes.ipynb">In Depth: Naive Bayes Classification</a> we explored naive Bayesian classification, in which we create a simple generative model for each class, and use these models to build a fast classifier.<br>
For Gaussian naive Bayes, the generative model is a simple axis-aligned Gaussian.<br>
With a density estimation algorithm like KDE, we can remove the &quot;naive&quot; element and perform the same classification with a more sophisticated generative model for each class.<br>
It's still Bayesian classification, but it's no longer naive.</p>
<p>The general approach for generative classification is this:</p>
<ol>
<li>
<p>Split the training data by label.</p>
</li>
<li>
<p>For each set, fit a KDE to obtain a generative model of the data.<br>
This allows you, for any observation $x$ and label $y$, to compute a likelihood $P(x~|~y)$.</p>
</li>
<li>
<p>From the number of examples of each class in the training set, compute the <em>class prior</em>, $P(y)$.</p>
</li>
<li>
<p>For an unknown point $x$, the posterior probability for each class is $P(y~|~x) \propto P(x~|~y)P(y)$.<br>
The class that maximizes this posterior is the label assigned to the point.</p>
</li>
</ol>
<p>The algorithm is straightforward and intuitive to understand; the more difficult piece is couching it within the Scikit-Learn framework in order to make use of the grid search and cross-validation architecture.</p>
<p>This is the code that implements the algorithm within the Scikit-Learn framework; we will step through it following the code block:</p>
<h3>Anatomy of a Custom Estimator</h3>
<p>Let's step through this code and discuss the essential features:</p>
<pre><code class="language-python">from sklearn.base import BaseEstimator, ClassifierMixin

class KDEClassifier(BaseEstimator, ClassifierMixin):
    &quot;&quot;&quot;Bayesian generative classification based on KDE
    
    Parameters
    ----------
    bandwidth : float
        the kernel bandwidth within each class
    kernel : str
        the kernel name, passed to KernelDensity
    &quot;&quot;&quot;
</code></pre>
<p>Each estimator in Scikit-Learn is a class, and it is most convenient for this class to inherit from the <code>BaseEstimator</code> class as well as the appropriate mixin, which provides standard functionality.<br>
For example, here the <code>BaseEstimator</code> contains (among other things) the logic necessary to clone/copy an estimator for use in a cross-validation procedure, and <code>ClassifierMixin</code> defines a default <code>score</code> method used by such routines.<br>
We also provide a docstring, which will be captured by IPython's help functionality (see <a href="01.01-Help-And-Documentation.ipynb">Help and Documentation in IPython</a>).</p>
<p>Next comes the class initialization method:</p>
<pre><code class="language-python">    def __init__(self, bandwidth=1.0, kernel='gaussian'):
        self.bandwidth = bandwidth
        self.kernel = kernel
</code></pre>
<p>This is the actual code that is executed when the object is instantiated with <code>KDEClassifier</code>.<br>
In Scikit-Learn, it is important that <em>initialization contains no operations</em> other than assigning the passed values by name to <code>self</code>.<br>
This is due to the logic contained in <code>BaseEstimator</code> required for cloning and modifying estimators for cross-validation, grid search, and other functions.<br>
Similarly, all arguments to <code>__init__</code> should be explicit: i.e., <code>*args</code> or <code>**kwargs</code> should be avoided, as they will not be correctly handled within cross-validation routines.</p>
<p>Next comes the <code>fit</code> method, where we handle training data:</p>
<pre><code class="language-python">    def fit(self, X, y):
        self.classes_ = np.sort(np.unique(y))
        training_sets = [X[y == yi] for yi in self.classes_]
        self.models_ = [KernelDensity(bandwidth=self.bandwidth,
                                      kernel=self.kernel).fit(Xi)
                        for Xi in training_sets]
        self.logpriors_ = [np.log(Xi.shape[0] / X.shape[0])
                           for Xi in training_sets]
        return self
</code></pre>
<p>Here we find the unique classes in the training data, train a <code>KernelDensity</code> model for each class, and compute the class priors based on the number of input samples.<br>
Finally, <code>fit</code> should always return <code>self</code> so that we can chain commands. For example:</p>
<pre><code class="language-python">label = model.fit(X, y).predict(X)
</code></pre>
<p>Notice that each persistent result of the fit is stored with a trailing underscore (e.g., <code>self.logpriors_</code>).<br>
This is a convention used in Scikit-Learn so that you can quickly scan the members of an estimator (using IPython's tab completion) and see exactly which members are fit to training data.</p>
<p>Finally, we have the logic for predicting labels on new data:</p>
<pre><code class="language-python">    def predict_proba(self, X):
        logprobs = np.vstack([model.score_samples(X)
                              for model in self.models_]).T
        result = np.exp(logprobs + self.logpriors_)
        return result / result.sum(axis=1, keepdims=True)
        
    def predict(self, X):
        return self.classes_[np.argmax(self.predict_proba(X), 1)]
</code></pre>
<p>Because this is a probabilistic classifier, we first implement <code>predict_proba</code>, which returns an array of class probabilities of shape <code>[n_samples, n_classes]</code>.<br>
Entry <code>[i, j]</code> of this array is the posterior probability that sample <code>i</code> is a member of class <code>j</code>, computed by multiplying the likelihood by the class prior and normalizing.</p>
<p>The <code>predict</code> method uses these probabilities and simply returns the class with the largest probability.</p>
<h3>Using Our Custom Estimator</h3>
<p>Let's try this custom estimator on a problem we have seen before: the classification of handwritten digits.<br>
Here we will load the digits and compute the cross-validation score for a range of candidate bandwidths using the <code>GridSearchCV</code> meta-estimator (refer back to <a href="05.03-Hyperparameters-and-Model-Validation.ipynb">Hyperparameters and Model Validation</a>):</p>
<p>Next we can plot the cross-validation score as a function of bandwidth (see the following figure):</p>
<p>This indicates that our KDE classifier reaches a cross-validation accuracy of over 96%, compared to around 80% for the naive Bayes classifier:</p>
<p>One benefit of such a generative classifier is interpretability of results: for each unknown sample, we not only get a probabilistic classification, but a <em>full model</em> of the distribution of points we are comparing it to!<br>
If desired, this offers an intuitive window into the reasons for a particular classification that algorithms like SVMs and random forests tend to obscure.</p>
<p>If you would like to take this further, here are some ideas for improvements that could be made to our KDE classifier model:</p>
<ul>
<li>You could allow the bandwidth in each class to vary independently.</li>
<li>You could optimize these bandwidths not based on their prediction score, but on the likelihood of the training data under the generative model within each class (i.e. use the scores from <code>KernelDensity</code> itself rather than the global prediction accuracy).</li>
</ul>
<p>Finally, if you want some practice building your own estimator, you might tackle building a similar Bayesian classifier using Gaussian mixture models instead of KDE.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Principal Component Analysis]]></title>
            <link>https://gopalverma.com/diary/research/Principal-Component-Analysis</link>
            <guid>https://gopalverma.com/diary/research/Principal-Component-Analysis</guid>
            <pubDate>Tue, 10 Nov 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Short intro to Principal Component Analysis]]></description>
            <content:encoded><![CDATA[<p>This note is inspired by the <a href="https://github.com/jakevdp/PythonDataScienceHandbook/tree/master">Python Data Science Handbook by Jake VanderPlas</a>.<br>
Thanks <a href="https://x.com/jakevdp">@jakevdp</a>!</p>
<h1>Principal Component Analysis</h1>
<p>Up until now, we have been looking in depth at supervised learning estimators: those estimators that predict labels based on labeled training data.<br>
Here we begin looking at several unsupervised estimators, which can highlight interesting aspects of the data without reference to any known labels.</p>
<p>In this chapter we will explore what is perhaps one of the most broadly used unsupervised algorithms, principal component analysis (PCA).<br>
PCA is fundamentally a dimensionality reduction algorithm, but it can also be useful as a tool for visualization, noise filtering, feature extraction and engineering, and much more.<br>
After a brief conceptual discussion of the PCA algorithm, we will explore a couple examples of these further applications.</p>
<p>We begin with the standard imports:</p>
<h2>Introducing Principal Component Analysis</h2>
<p>Principal component analysis is a fast and flexible unsupervised method for dimensionality reduction in data, which we saw briefly in <a href="05.02-Introducing-Scikit-Learn.ipynb">Introducing Scikit-Learn</a>.<br>
Its behavior is easiest to visualize by looking at a two-dimensional dataset.<br>
Consider these 200 points (see the following figure):</p>
<p>By eye, it is clear that there is a nearly linear relationship between the <em>x</em> and <em>y</em> variables.<br>
This is reminiscent of the linear regression data we explored in <a href="05.06-Linear-Regression.ipynb">In Depth: Linear Regression</a>, but the problem setting here is slightly different: rather than attempting to <em>predict</em> the <em>y</em> values from the <em>x</em> values, the unsupervised learning problem attempts to learn about the <em>relationship</em> between the <em>x</em> and <em>y</em> values.</p>
<p>In principal component analysis, this relationship is quantified by finding a list of the <em>principal axes</em> in the data, and using those axes to describe the dataset.<br>
Using Scikit-Learn's <code>PCA</code> estimator, we can compute this as follows:</p>
<p>The fit learns some quantities from the data, most importantly the components and explained variance:</p>
<p>To see what these numbers mean, let's visualize them as vectors over the input data, using the components to define the direction of the vector and the explained variance to define the squared length of the vector (see the following figure):</p>
<p>These vectors represent the principal axes of the data, and the length of each vector is an indication of how &quot;important&quot; that axis is in describing the distribution of the data—more precisely, it is a measure of the variance of the data when projected onto that axis.<br>
The projection of each data point onto the principal axes are the principal components of the data.</p>
<p>This transformation from data axes to principal axes is an <em>affine transformation</em>, which means it is composed of a translation, rotation, and uniform scaling.</p>
<p>While this algorithm to find principal components may seem like just a mathematical curiosity, it turns out to have very far-reaching applications in the world of machine learning and data exploration.</p>
<h3>PCA as Dimensionality Reduction</h3>
<p>Using PCA for dimensionality reduction involves zeroing out one or more of the smallest principal components, resulting in a lower-dimensional projection of the data that preserves the maximal data variance.</p>
<p>Here is an example of using PCA as a dimensionality reduction transform:</p>
<p>The transformed data has been reduced to a single dimension.<br>
To understand the effect of this dimensionality reduction, we can perform the inverse transform of this reduced data and plot it along with the original data (see the following figure):</p>
<p>The light points are the original data, while the dark points are the projected version.<br>
This makes clear what a PCA dimensionality reduction means: the information along the least important principal axis or axes is removed, leaving only the component(s) of the data with the highest variance.<br>
The fraction of variance that is cut out (proportional to the spread of points about the line formed in the preceding figure) is roughly a measure of how much &quot;information&quot; is discarded in this reduction of dimensionality.</p>
<p>This reduced-dimension dataset is in some senses &quot;good enough&quot; to encode the most important relationships between the points: despite reducing the number of data features by 50%, the overall relationships between the data points are mostly preserved.</p>
<h3>PCA for Visualization: Handwritten Digits</h3>
<p>The usefulness of dimensionality reduction may not be entirely apparent in only two dimensions, but it becomes clear when looking at high-dimensional data.<br>
To see this, let's take a quick look at the application of PCA to the digits dataset we worked with in <a href="05.08-Random-Forests.ipynb">In-Depth: Decision Trees and Random Forests</a>.</p>
<p>We'll start by loading the data:</p>
<p>Recall that the digits dataset consists of 8 × 8–pixel images, meaning that they are 64-dimensional.<br>
To gain some intuition into the relationships between these points, we can use PCA to project them into a more manageable number of dimensions, say two:</p>
<p>We can now plot the first two principal components of each point to learn about the data, as seen in the following figure:</p>
<p>Recall what these components mean: the full data is a 64-dimensional point cloud, and these points are the projection of each data point along the directions with the largest variance.<br>
Essentially, we have found the optimal stretch and rotation in 64-dimensional space that allows us to see the layout of the data in two dimensions, and we have done this in an unsupervised manner—that is, without reference to the labels.</p>
<h3>What Do the Components Mean?</h3>
<p>We can go a bit further here, and begin to ask what the reduced dimensions <em>mean</em>.<br>
This meaning can be understood in terms of combinations of basis vectors.<br>
For example, each image in the training set is defined by a collection of 64 pixel values, which we will call the vector $x$:</p>
<p>$$<br>
x = [x_1, x_2, x_3 \cdots x_{64}]<br>
$$</p>
<p>One way we can think about this is in terms of a pixel basis.<br>
That is, to construct the image, we multiply each element of the vector by the pixel it describes, and then add the results together to build the image:</p>
<p>$$<br>
{\rm image}(x) = x_1 \cdot{\rm (pixel~1)} + x_2 \cdot{\rm (pixel~2)} + x_3 \cdot{\rm (pixel~3)} \cdots x_{64} \cdot{\rm (pixel~64)}<br>
$$</p>
<p>One way we might imagine reducing the dimensionality of this data is to zero out all but a few of these basis vectors.<br>
For example, if we use only the first eight pixels, we get an eight-dimensional projection of the data (the following figure). However, it is not very reflective of the whole image: we've thrown out nearly 90% of the pixels!</p>
<p>The upper row of panels shows the individual pixels, and the lower row shows the cumulative contribution of these pixels to the construction of the image.<br>
Using only eight of the pixel-basis components, we can only construct a small portion of the 64-pixel image.<br>
Were we to continue this sequence and use all 64 pixels, we would recover the original image.</p>
<p>But the pixel-wise representation is not the only choice of basis. We can also use other basis functions, which each contain some predefined contribution from each pixel, and write something like:</p>
<p>$$<br>
image(x) = {\rm mean} + x_1 \cdot{\rm (basis~1)} + x_2 \cdot{\rm (basis~2)} + x_3 \cdot{\rm (basis~3)} \cdots<br>
$$</p>
<p>PCA can be thought of as a process of choosing optimal basis functions, such that adding together just the first few of them is enough to suitably reconstruct the bulk of the elements in the dataset.<br>
The principal components, which act as the low-dimensional representation of our data, are simply the coefficients that multiply each of the elements in this series.<br>
the following figure shows a similar depiction of reconstructing the same digit using the mean plus the first eight PCA basis functions.</p>
<p>Unlike the pixel basis, the PCA basis allows us to recover the salient features of the input image with just a mean, plus eight components!<br>
The amount of each pixel in each component is the corollary of the orientation of the vector in our two-dimensional example.<br>
This is the sense in which PCA provides a low-dimensional representation of the data: it discovers a set of basis functions that are more efficient than the native pixel basis of the input data.</p>
<h3>Choosing the Number of Components</h3>
<p>A vital part of using PCA in practice is the ability to estimate how many components are needed to describe the data.<br>
This can be determined by looking at the cumulative <em>explained variance ratio</em> as a function of the number of components (see the following figure):</p>
<p>This curve quantifies how much of the total, 64-dimensional variance is contained within the first $N$ components.<br>
For example, we see that with the digits data the first 10 components contain approximately 75% of the variance, while you need around 50 components to describe close to 100% of the variance.</p>
<p>This tells us that our 2-dimensional projection loses a lot of information (as measured by the explained variance) and that we'd need about 20 components to retain 90% of the variance.  Looking at this plot for a high-dimensional dataset can help you understand the level of redundancy present in its features.</p>
<h2>PCA as Noise Filtering</h2>
<p>PCA can also be used as a filtering approach for noisy data.<br>
The idea is this: any components with variance much larger than the effect of the noise should be relatively unaffected by the noise.<br>
So, if you reconstruct the data using just the largest subset of principal components, you should be preferentially keeping the signal and throwing out the noise.</p>
<p>Let's see how this looks with the digits data.<br>
First we will plot several of the input noise-free input samples (the following figure):</p>
<p>Now let's add some random noise to create a noisy dataset, and replot it (the following figure):</p>
<p>The visualization makes the presence of this random noise clear.<br>
Let's train a PCA model on the noisy data, requesting that the projection preserve 50% of the variance:</p>
<p>Here 50% of the variance amounts to 12 principal components, out of the 64 original features.<br>
Now we compute these components, and then use the inverse of the transform to reconstruct the filtered digits; the following figure shows the result:</p>
<p>This signal preserving/noise filtering property makes PCA a very useful feature selection routine—for example, rather than training a classifier on very high-dimensional data, you might instead train the classifier on the lower-dimensional principal component representation, which will automatically serve to filter out random noise in the inputs.</p>
<h2>Example: Eigenfaces</h2>
<p>Earlier we explored an example of using a PCA projection as a feature selector for facial recognition with a support vector machine (see <a href="05.07-Support-Vector-Machines.ipynb">In-Depth: Support Vector Machines</a>).<br>
Here we will take a look back and explore a bit more of what went into that.<br>
Recall that we were using the Labeled Faces in the Wild (LFW) dataset made available through Scikit-Learn:</p>
<p>Let's take a look at the principal axes that span this dataset.<br>
Because this is a large dataset, we will use the <code>&quot;random&quot;</code> eigensolver in the <code>PCA</code> estimator: it uses a randomized method to approximate the first $N$ principal components more quickly than the standard approach, at the expense of some accuracy. This trade-off can be useful for high-dimensional data (here, a dimensionality of nearly 3,000).<br>
We will take a look at the first 150 components:</p>
<p>In this case, it can be interesting to visualize the images associated with the first several principal components (these components are technically known as <em>eigenvectors</em>,<br>
so these types of images are often called <em>eigenfaces</em>; as you can see in the following figure, they are as creepy as they sound):</p>
<p>The results are very interesting, and give us insight into how the images vary: for example, the first few eigenfaces (from the top left) seem to be associated with the angle of lighting on the face, and later principal vectors seem to be picking out certain features, such as eyes, noses, and lips.<br>
Let's take a look at the cumulative variance of these components to see how much of the data information the projection is preserving (see the following figure):</p>
<p>The 150 components we have chosen account for just over 90% of the variance.<br>
That would lead us to believe that using these 150 components, we would recover most of the essential characteristics of the data.<br>
To make this more concrete, we can compare the input images with the images reconstructed from these 150 components (see the following figure):</p>
<p>The top row here shows the input images, while the bottom row shows the reconstruction of the images from just 150 of the ~3,000 initial features.<br>
This visualization makes clear why the PCA feature selection used in <a href="05.07-Support-Vector-Machines.ipynb">In-Depth: Support Vector Machines</a> was so successful: although it reduces the dimensionality of the data by nearly a factor of 20, the projected images contain enough information that we might, by eye, recognize the individuals in each image. This means our classification algorithm only needs to be trained on 150-dimensional data rather than 3,000-dimensional data, which, depending on the particular algorithm we choose, can lead to much more efficient classification.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[How I Dealt with Burnout]]></title>
            <link>https://gopalverma.com/diary/blogs/how-i-dealt-with-burnout</link>
            <guid>https://gopalverma.com/diary/blogs/how-i-dealt-with-burnout</guid>
            <pubDate>Mon, 09 Nov 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[I was a front-end developer who loved pixels and ended up in the number-heavy world of banking analytics. It nearly cost me my love for tech. This is how I found my way back through first principles, and how my design and dev background became my biggest advantage.]]></description>
            <content:encoded><![CDATA[<p>At 2:00 AM on a Tuesday, I sat in a dark room with my laptop open. On the screen was a side project I had been excited about for months. My hands were on the keyboard, and I couldn't write a single line.</p>
<p>I knew how. I just didn't care anymore, and that scared me more than any bug ever had.</p>
<h1>Who I was before</h1>
<p>For most of my career I was a front-end person, through and through. I was the developer who lost an evening to a 2-pixel misalignment and didn't consider it wasted. I cared about spring animations, spacing scales and the way a button feels when you press it.</p>
<p>My favorite moment in the job was small. You change a line, save, and the browser reacts. Something that didn't exist ten seconds ago is now alive on the screen, and a real person will touch it and never think about the work behind it. That loop of build, see and feel was my whole world. I would code for sixteen hours and close the laptop energized.</p>
<p>Then, in June 2025, I moved into data science and analytics, in banking.</p>
<h1>The world I walked into</h1>
<p>The change was total, and I underestimated it.</p>
<p>Front-end is warm. Color, motion, layout, feedback. Banking analytics felt like walking out of a studio into a server room. Millions of rows of transactions. Risk matrices. SQL queries that ran for twenty minutes while I stared at a spinner. Nobody in that building cared how smooth a transition was. They cared about basis points, default probabilities, portfolio variance and whether a number tied out to the last decimal.</p>
<p>My first week, I ran a query on a transactions table.</p>
<pre><code class="language-sql">SELECT * FROM transactions;
-- 4,812,903 rows returned
</code></pre>
<p>I scrolled through it for a long time. Grey columns, no context, no story. I remember thinking: <em>What did I just sign up for?</em></p>
<h1>The slow crash</h1>
<p>The first few weeks were fine, because novelty carries you. New role, new team, everyone watching, so you run on adrenaline.</p>
<p>Then the adrenaline ran out.</p>
<p>Meetings were full of terms I half understood. My colleagues had years of context in credit risk, reconciliation and regulatory reporting. I had deep knowledge of the DOM and almost none of what the business actually cared about. I nodded a lot and looked things up afterward, under the table.</p>
<p>That kind of pretending is tiring in a way sleep doesn't fix.</p>
<p>What I later understood as burnout didn't come from long hours. I had done long hours before and loved them. This was something else. It was starvation. I had spent years being fed by the visible result of my work, and now I couldn't see anything. I wrote queries, produced numbers, and sent them into a void.</p>
<p>It came in small steps:</p>
<ul>
<li>Mornings got heavy. I would open the terminal to run another pipeline and feel a knot in my stomach.</li>
<li>I felt like an imposter in both worlds. At work I was surrounded by people fluent in statistics while I quietly missed CSS. At home I was too tired from staring at tables to build anything I loved.</li>
<li>The numbness spread. I stopped tinkering on weekends. I stopped reading about front-end. Eventually I stopped being curious about the new work too.</li>
</ul>
<p>I was doing the job, but I wasn't in it.</p>
<h1>The low point</h1>
<p>There was one week that tipped it.</p>
<p>I spent about six hours on an analysis I was nervous about. I checked it twice and presented it carefully. It was correct, and it still landed flat. Someone said &quot;okay, thanks,&quot; and the meeting moved on.</p>
<p>That evening I opened a job board and scrolled through front-end roles for a long time. My cursor hovered over &quot;Apply.&quot; I didn't click, but I came closer than I want to admit.</p>
<p>What hurt wasn't the missing applause. It was the thought that I had traded something I was good at for something I would only ever be average at. And then came the 2:00 AM night, the cursor blinking in an empty file, and the realization that the burnout had reached the thing I loved most.</p>
<p>I closed the laptop and sat in the dark. I didn't have a plan. I only knew I couldn't keep running from the numbers.</p>
<h1>The weekend with a notebook</h1>
<p>That weekend I did something simple. No laptop, just a pen and a notebook, and one question I wrote at the top of the page:</p>
<p><em>Why do I love front-end so much, and why does this new work feel so dead?</em></p>
<p>On the surface they look like opposites. One is visual and tangible. The other is mathematical and invisible. But I kept stripping things away: the frameworks, the SQL, the jargon, the job titles. I kept asking what each job actually is at the bottom, which is what first principles means.</p>
<p>I put the two answers side by side, and I stared at the page for a while.</p>
<pre><code class="language-js">UI = f(state);
Insight = f(data);
</code></pre>
<p>Front-end takes messy, unpredictable state and turns it into something a person can understand and act on in seconds. Banking analytics takes messy, unpredictable data and turns it into something a person can understand and act on in seconds. The raw material is different. The craft is the same.</p>
<p>I wasn't a front-end developer stranded in finance. I was someone who reduces complexity into clarity, standing in a new room.</p>
<p>Once I started looking for parallels, I found them everywhere:</p>
<ul>
<li>Cleaning dirty banking data was input validation and state normalization.</li>
<li>Feature engineering was removing clutter so only the props that matter remain.</li>
<li>Debugging a skewed distribution in a credit model was the same detective work as chasing a race condition in React.</li>
<li>Cutting a slow query across a hundred million rows gave me the same quiet thrill as shaving 200ms off a page load.</li>
</ul>
<p>Even the code looked related:</p>
<pre><code class="language-js">// What I had written for years
const totalByCustomer = transactions.reduce((acc, t) =&gt; {
  acc[t.customerId] = (acc[t.customerId] || 0) + t.amount;
  return acc;
}, {});
</code></pre>
<pre><code class="language-python"># What I thought I was starting from scratch to learn
total_by_customer = df.groupby(&quot;customer_id&quot;)[&quot;amount&quot;].sum()
</code></pre>
<p>Same idea, different syntax. I had spent months believing I was a beginner, when I was an experienced person learning a new vocabulary. Those are very different positions, and the second one is much easier to live in.</p>
<table>
<thead>
<tr>
<th style="text-align:left">Core idea</th>
<th style="text-align:left">In front-end</th>
<th style="text-align:left">In banking analytics</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">Raw chaos</td>
<td style="text-align:left">User clicks, API payloads</td>
<td style="text-align:left">Millions of noisy transactions</td>
</tr>
<tr>
<td style="text-align:left">The engine</td>
<td style="text-align:left">Reducers, hooks, state machines</td>
<td style="text-align:left">SQL pipelines, probability, ML models</td>
</tr>
<tr>
<td style="text-align:left">Cutting noise</td>
<td style="text-align:left">Visual hierarchy, clean layout</td>
<td style="text-align:left">Dimensionality reduction, outlier filtering</td>
</tr>
<tr>
<td style="text-align:left">The goal</td>
<td style="text-align:left">Help a user make the right click</td>
<td style="text-align:left">Help a bank make the right decision</td>
</tr>
</tbody>
</table>
<p>That night I slept properly for the first time in weeks. The next morning I opened the laptop and, for the first time since June, felt a small flicker of curiosity. The numbers weren't dead. They were a large, living system I hadn't learned to see yet.</p>
<h1>Learning to see the math</h1>
<p>Curiosity made me brave enough to learn properly.</p>
<p>Finance-flavored data science gets abstract fast. Covariance matrices, tail-risk distributions, Gaussian mixtures. Most people I worked with read these through summary output: <code>mean: 0.42</code>, <code>std: 1.18</code>, <code>p-value: 0.003</code>.</p>
<p>My brain wouldn't work that way. I needed to see it.</p>
<p>So I used what I already had. I plotted decision boundaries instead of reading coefficients. I animated how a distribution shifted over time. I treated probability curves like terrain. When I could see the shape of the data, the Greek letters stopped being a wall and started being a landscape I could walk through.</p>
<p>My design eye, which I had been hiding, turned out to be a microscope for the math. I learned concepts faster, and I remembered them longer, because I had literally watched them happen.</p>
<h1>The gap nobody was filling</h1>
<p>As I got more comfortable, I started noticing how analysis was delivered around me.</p>
<p>The analysts were sharp. They built strong models. But then it came time to present, and the output was a dense table, a chart that needed a manual, or the one finding that mattered buried on slide fourteen. A brilliant insight that nobody can read is worth very little.</p>
<p>On the other side were people who could build beautiful interfaces but couldn't tell you why an average was lying because of a bimodal distribution.</p>
<p>Very few people stood in the middle. I realized I could.</p>
<p>That was the moment I stopped hiding my past. For months I had tried to act like a traditional finance analyst, and playing someone else's game on their ground will always make you average. So I started playing mine:</p>
<ul>
<li><strong>Design-driven analytics.</strong> I used hierarchy, whitespace and color so a complex story was clear in three seconds, instead of fifteen competing colors on a dashboard.</li>
<li><strong>Software-grade work.</strong> I wrote modular, reusable code rather than one-off notebooks that broke the following week, and I built small internal tools that felt like products.</li>
<li><strong>Owning the last mile.</strong> I stopped treating the handoff as someone else's job. If the reader couldn't understand it, the work wasn't finished.</li>
</ul>
<p>One small example was a risk indicator, so a manager could scan hundreds of accounts and find the ones that needed attention without asking me a thing:</p>
<pre><code class="language-jsx">function RiskBadge({ score }) {
  const level = score &gt; 80 ? &quot;high&quot; : score &gt; 50 ? &quot;medium&quot; : &quot;low&quot;;
  return (
    &lt;span className={`badge badge--${level}`}&gt;
      {level} ({score})
    &lt;/span&gt;
  );
}
</code></pre>
<p>It's a tiny component. The reaction was not tiny. People stopped saying &quot;okay, thanks.&quot; They started asking how it was built, and whether I could do the same for their reports.</p>
<p>That did more for my confidence than any formal feedback ever had.</p>
<h1>Before and after</h1>
<p>If I picture the two versions of myself, the difference is easy to see.</p>
<p>Before, I opened my laptop and saw a grey table, millions of rows with no meaning, a question I didn't understand, and a clock moving too slowly. I felt like a front-end developer in the wrong building.</p>
<p>Now I open it and see a system. The same rows have shape, and somewhere in them is a story waiting to be made clear. I still don't know everything, and I still have days where I'm the newest person in the room. But I read that feeling differently. It isn't proof I chose wrong. It's what building range feels like.</p>
<p>What changed wasn't the job. It was how I understood my own background. I had been treating my past as baggage, and it was leverage.</p>
<h1>Looking back from here</h1>
<p>It's November 2026 now. When I think about that 2:00 AM night, I'm almost grateful for it. Burnout broke the idea that my career had to fit inside one neat box. It showed me that what I love was never tied to a framework, a browser window or a job title. It was always the act of turning complexity into something a person can feel and use.</p>
<p>If you're burned out because your work seems worlds away from what you love, here is what helped me:</p>
<ol>
<li><strong>Go down to first principles.</strong> Strip the tools and jargon until you find the core problem underneath. Systems are systems, and logic is logic.</li>
<li><strong>Don't bury your strange background.</strong> A designer in data, a developer in finance, an artist in engineering: don't sand down your edges to fit in. Combine your worlds, because that combination is hard for anyone else to copy.</li>
<li><strong>Be patient with the middle.</strong> The early months feel like failure, but they are mostly a translation period. Skill compounds slowly, then quickly.</li>
</ol>
<p>I thought moving into financial data science meant losing my identity. It turned out that refusing to let go of it was what saved me.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Rendering Jupyter Notebooks in Next.js]]></title>
            <link>https://gopalverma.com/diary/notes/render-ipynb-in-nextjs</link>
            <guid>https://gopalverma.com/diary/notes/render-ipynb-in-nextjs</guid>
            <pubDate>Mon, 09 Nov 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[A complete guide to parsing and rendering Jupyter Notebook (.ipynb) files natively in a Next.js App Router website with server-side Shiki syntax highlighting, KaTeX math, Pandas DataFrames, and Matplotlib plots.]]></description>
            <content:encoded><![CDATA[<p>Publishing data science experiments, machine learning research, or mathematical explorations directly from <strong>Jupyter Notebooks (<code>.ipynb</code>)</strong> onto a personal React / Next.js website often feels clunky. Most developers resort to embedding heavy third-party <code>&lt;iframe&gt;</code> viewers (<code>nbviewer</code>, Google Colab embeds) or manually converting notebooks to Markdown every time they make an edit.</p>
<p>In this note, we walk through how <code>.ipynb</code> files are rendered <strong>natively</strong> on this website—giving you server-side <strong>Shiki</strong> syntax highlighting (with instant dark/light mode support), <strong>KaTeX</strong> math equations, <strong>Pandas DataFrame</strong> HTML tables, <strong>Matplotlib / Seaborn</strong> plots, collapsible code cells, and an automatic <strong>Table of Contents</strong>, simply by dropping any <code>.ipynb</code> file into a folder.</p>
<h1>Why Render .ipynb Server-Side in Next.js?</h1>
<ol>
<li><strong>Zero Client-Side Parser Overhead:</strong> Syntax highlighting (<code>shiki</code>) and LaTeX compilation (<code>katex</code>) run on the server at build/request time inside Next.js Server Components.</li>
<li><strong>Native Theme Integration:</strong> Instead of an mismatched white iframe inside a dark-mode site, every Markdown paragraph, code block, table, and output matches your Tailwind CSS design tokens.</li>
<li><strong>Drop-In Workflow:</strong> You don't need an external <code>jupyter nbconvert</code> build step. You drop <code>my-research.ipynb</code> into <code>content/research/</code> and Next.js automatically generates the static route and metadata.</li>
<li><strong>Full SEO &amp; Table of Contents:</strong> Because headings and outputs are rendered into semantic HTML on the server, search engines index your notebooks and your existing TOC component can track section headings.</li>
</ol>
<h1>Understanding the .ipynb File Format</h1>
<p>At its core, a Jupyter Notebook (<code>.ipynb</code>, <code>nbformat v4</code>) is a standard JSON file with three main top-level keys:</p>
<pre><code class="language-json">{
  &quot;metadata&quot;: {
    &quot;kernelspec&quot;: { &quot;display_name&quot;: &quot;Python 3&quot;, &quot;language&quot;: &quot;python&quot; },
    &quot;language_info&quot;: { &quot;name&quot;: &quot;python&quot;, &quot;version&quot;: &quot;3.11.8&quot; }
  },
  &quot;nbformat&quot;: 4,
  &quot;nbformat_minor&quot;: 5,
  &quot;cells&quot;: [
    {
      &quot;cell_type&quot;: &quot;markdown&quot;,
      &quot;metadata&quot;: {},
      &quot;source&quot;: [&quot;# Section Heading\n&quot;, &quot;Some explanation with $E = mc^2$.&quot;]
    },
    {
      &quot;cell_type&quot;: &quot;code&quot;,
      &quot;execution_count&quot;: 1,
      &quot;metadata&quot;: {},
      &quot;source&quot;: [&quot;import numpy as np\n&quot;, &quot;np.arange(5)&quot;],
      &quot;outputs&quot;: [
        {
          &quot;output_type&quot;: &quot;execute_result&quot;,
          &quot;execution_count&quot;: 1,
          &quot;data&quot;: {
            &quot;text/plain&quot;: [&quot;array([0, 1, 2, 3, 4])&quot;]
          }
        }
      ]
    }
  ]
}
</code></pre>
<p>Key quirks to handle when parsing <code>.ipynb</code> JSON:</p>
<ul>
<li><strong><code>source</code> can be <code>string</code> or <code>string[]</code>:</strong> Depending on the editor (VS Code, JupyterLab, Colab), <code>cell.source</code> and <code>output.text</code> may be stored either as an array of line strings or a single string. Always normalize with <code>Array.isArray(s) ? s.join(&quot;&quot;) : String(s)</code>.</li>
<li><strong>Four Output Types:</strong> Code cells can produce:
<ol>
<li><code>stream</code> (<code>stdout</code> or <code>stderr</code> console logs)</li>
<li><code>execute_result</code> (return value of the last expression in a cell, labeled <code>Out [n]:</code>)</li>
<li><code>display_data</code> (rich plots from <code>matplotlib</code>, <code>seaborn</code>, or <code>IPython.display</code>)</li>
<li><code>error</code> (Python exception name <code>ename</code>, message <code>evalue</code>, and ANSI-colored <code>traceback</code>)</li>
</ol>
</li>
<li><strong>Rich MIME Bundles:</strong> Inside <code>execute_result</code> and <code>display_data</code>, <code>output.data</code> is a dictionary keyed by MIME type (<code>image/png</code>, <code>image/svg+xml</code>, <code>text/html</code>, <code>application/json</code>, <code>text/plain</code>). You should render the richest visual representation (e.g., <code>image/png</code> plot or <code>text/html</code> Pandas DataFrame) and fall back to <code>text/plain</code> only when no rich visual exists.</li>
</ul>
<h1>Step-by-Step Implementation</h1>
<h2>1. Install Dependencies</h2>
<p>We use the <code>unified</code> / <code>remark</code> / <code>rehype</code> ecosystem alongside <code>shiki</code> (via <code>rehype-pretty-code</code>) and <code>katex</code> (via <code>rehype-katex</code>):</p>
<pre><code class="language-bash">bun add unified remark-parse remark-gfm remark-math remark-rehype \
  rehype-slug rehype-katex rehype-pretty-code rehype-stringify \
  shiki katex gray-matter
</code></pre>
<p>Make sure to import the KaTeX stylesheet in your root <code>app/layout.tsx</code> so mathematical formulas render properly:</p>
<pre><code class="language-tsx">import &quot;./globals.css&quot;;
import &quot;katex/dist/katex.min.css&quot;;
</code></pre>
<h2>2. Build the Server-Side .ipynb Parser</h2>
<p>Create <code>src/lib/ipynb.ts</code> to read <code>.ipynb</code> files from disk, extract metadata (supporting YAML frontmatter in the first Markdown cell, notebook JSON metadata, or automatic fallback from the first <code># Heading</code>), and compile Markdown and Code cells into HTML:</p>
<pre><code class="language-ts">import fs from &quot;fs&quot;;
import path from &quot;path&quot;;
import matter from &quot;gray-matter&quot;;
import { unified } from &quot;unified&quot;;
import remarkParse from &quot;remark-parse&quot;;
import remarkGfm from &quot;remark-gfm&quot;;
import remarkMath from &quot;remark-math&quot;;
import remarkRehype from &quot;remark-rehype&quot;;
import rehypeSlug from &quot;rehype-slug&quot;;
import rehypeKatex from &quot;rehype-katex&quot;;
import rehypePrettyCode from &quot;rehype-pretty-code&quot;;
import rehypeStringify from &quot;rehype-stringify&quot;;

const RESEARCH_DIR = path.join(process.cwd(), &quot;content&quot;, &quot;research&quot;);

function joinSource(source: string | string[] | undefined): string {
  if (!source) return &quot;&quot;;
  return Array.isArray(source) ? source.join(&quot;&quot;) : String(source);
}

// Strip ANSI escape codes from terminal logs and Python tracebacks
function stripAnsi(str: string): string {
  return str.replace(
    /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=&gt;&lt;]/g,
    &quot;&quot;,
  );
}

async function renderMarkdownToHtml(markdown: string): Promise&lt;string&gt; {
  const file = await unified()
    .use(remarkParse)
    .use(remarkGfm as any)
    .use(remarkMath)
    .use(remarkRehype, { allowDangerousHtml: true })
    .use(rehypeSlug)
    .use(rehypeKatex)
    .use(rehypePrettyCode, {
      theme: {
        dark: &quot;vitesse-dark&quot;,
        light: &quot;vitesse-light&quot;,
      },
      onVisitLine(node: any) {
        if (node.children.length === 0) {
          node.children = [{ type: &quot;text&quot;, value: &quot; &quot; }];
        }
      },
    })
    .use(rehypeStringify, { allowDangerousHtml: true })
    .process(markdown);

  return String(file);
}

async function renderCodeToHtml(
  code: string,
  language: string,
): Promise&lt;string&gt; {
  const fenced = `\`\`\`${language}\n${code.replace(/\n$/, &quot;&quot;)}\n\`\`\``;
  return renderMarkdownToHtml(fenced);
}
</code></pre>
<h3>Normalizing Cell Outputs</h3>
<p>For each code cell, we map its <code>outputs</code> array into a clean serializable structure for our React component:</p>
<pre><code class="language-ts">function parseOutput(output: any) {
  if (output.output_type === &quot;stream&quot;) {
    return {
      outputType: &quot;stream&quot;,
      streamName: output.name || &quot;stdout&quot;,
      text: stripAnsi(joinSource(output.text)),
    };
  }

  if (output.output_type === &quot;error&quot;) {
    return {
      outputType: &quot;error&quot;,
      ename: output.ename || &quot;Error&quot;,
      evalue: output.evalue || &quot;&quot;,
      traceback: (output.traceback || []).map(stripAnsi).join(&quot;\n&quot;),
    };
  }

  const data = output.data || {};
  return {
    outputType: output.output_type,
    executionCount: output.execution_count ?? null,
    svg: data[&quot;image/svg+xml&quot;] ? joinSource(data[&quot;image/svg+xml&quot;]) : undefined,
    imageMime: data[&quot;image/png&quot;]
      ? &quot;image/png&quot;
      : data[&quot;image/jpeg&quot;]
        ? &quot;image/jpeg&quot;
        : undefined,
    imageData:
      (joinSource(data[&quot;image/png&quot;] || data[&quot;image/jpeg&quot;]) || &quot;&quot;).trim() ||
      undefined,
    html: data[&quot;text/html&quot;] ? joinSource(data[&quot;text/html&quot;]) : undefined,
    json: data[&quot;application/json&quot;]
      ? JSON.stringify(data[&quot;application/json&quot;], null, 2)
      : undefined,
    text: data[&quot;text/plain&quot;]
      ? stripAnsi(joinSource(data[&quot;text/plain&quot;]))
      : undefined,
  };
}
</code></pre>
<h2>3. Build the Interactive &quot;&lt;NotebookRenderer /&gt;&quot; Component</h2>
<p>On the client side, <code>src/components/NotebookRenderer.tsx</code> receives the pre-highlighted cells and provides interactive controls:</p>
<ul>
<li>A global <strong>Hide code / Show code</strong> button in the notebook header bar</li>
<li>Per-cell collapse toggles (<code>In [1]:</code>) and one-click <strong>Copy code</strong> buttons</li>
<li>Styled containers for <code>stdout</code>/<code>stderr</code>, Pandas HTML tables, Base64 plots (<code>data:image/png;base64,...</code>), and Python tracebacks</li>
</ul>
<pre><code class="language-tsx">&quot;use client&quot;;

import React, { useState } from &quot;react&quot;;
import {
  Check,
  Copy,
  ChevronDown,
  ChevronRight,
  Eye,
  EyeOff,
  Terminal,
} from &quot;lucide-react&quot;;
import { cn } from &quot;@/lib/utils&quot;;
import type { RenderedNotebookCell, RenderedNotebookOutput } from &quot;@/lib/ipynb&quot;;

export default function NotebookRenderer({
  cells,
  kernelName = &quot;Python 3&quot;,
}: {
  cells: RenderedNotebookCell[];
  kernelName?: string;
}) {
  const [showAllCode, setShowAllCode] = useState(true);
  const codeCellsCount = cells.filter((c) =&gt; c.cellType === &quot;code&quot;).length;
  const markdownCellsCount = cells.filter(
    (c) =&gt; c.cellType === &quot;markdown&quot;,
  ).length;

  return (
    &lt;div className=&quot;space-y-4&quot;&gt;
      {/* Notebook Header Bar */}
      &lt;div className=&quot;flex flex-wrap items-center justify-between gap-2 pb-4 mb-6 border-b border-border/60 text-xs text-muted-foreground/70&quot;&gt;
        &lt;div className=&quot;flex items-center gap-3 font-mono&quot;&gt;
          &lt;span className=&quot;inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md border border-border bg-muted/30 text-foreground/80&quot;&gt;
            &lt;Terminal className=&quot;h-3 w-3&quot; /&gt;
            {kernelName}
          &lt;/span&gt;
          &lt;span&gt;
            {markdownCellsCount} markdown &amp;middot; {codeCellsCount} code cells
          &lt;/span&gt;
        &lt;/div&gt;

        {codeCellsCount &gt; 0 &amp;&amp; (
          &lt;button
            onClick={() =&gt; setShowAllCode((prev) =&gt; !prev)}
            className=&quot;inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md border border-border/70 bg-muted/20 hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors font-mono text-xs&quot;
          &gt;
            {showAllCode ? (
              &lt;EyeOff className=&quot;h-3.5 w-3.5&quot; /&gt;
            ) : (
              &lt;Eye className=&quot;h-3.5 w-3.5&quot; /&gt;
            )}
            &lt;span&gt;{showAllCode ? &quot;Hide code&quot; : &quot;Show code&quot;}&lt;/span&gt;
          &lt;/button&gt;
        )}
      &lt;/div&gt;

      {/* Render Markdown &amp; Code Cells */}
      {cells.map((cell) =&gt;
        cell.cellType === &quot;markdown&quot; ? (
          &lt;div
            key={cell.id}
            className=&quot;notebook-markdown&quot;
            dangerouslySetInnerHTML={{ __html: cell.renderedHtml }}
          /&gt;
        ) : (
          &lt;CodeCellView
            key={cell.id}
            cell={cell}
            globalShowCode={showAllCode}
          /&gt;
        ),
      )}
    &lt;/div&gt;
  );
}
</code></pre>
<h3>Rendering Base64 Plots &amp; Pandas DataFrames</h3>
<p>Inside <code>NotebookOutputView</code>, Base64 images and Pandas HTML tables are rendered cleanly without duplicating the fallback <code>text/plain</code> representation:</p>
<pre><code class="language-tsx">{
  output.imageData &amp;&amp; output.imageMime &amp;&amp; (
    &lt;div className=&quot;rounded-lg border border-border/60 bg-white dark:bg-[#121212] p-4 flex justify-center overflow-x-auto&quot;&gt;
      &lt;img
        src={`data:${output.imageMime};base64,${output.imageData}`}
        alt=&quot;Notebook output plot&quot;
        className=&quot;max-w-full h-auto rounded&quot;
      /&gt;
    &lt;/div&gt;
  );
}

{
  output.html &amp;&amp; (
    &lt;div
      className=&quot;my-2 w-full overflow-x-auto rounded-lg border border-border/60 bg-[#FAFBFB] dark:bg-[#121212] p-3 [&amp;_table]:w-full [&amp;_table]:border-collapse [&amp;_th]:px-3 [&amp;_th]:py-2 [&amp;_td]:px-3 [&amp;_td]:py-1.5 [&amp;_style]:hidden&quot;
      dangerouslySetInnerHTML={{ __html: output.html }}
    /&gt;
  );
}
</code></pre>
<blockquote>
<p>Notice <code>[&amp;_style]:hidden</code> on the HTML output container—Pandas injects a <code>&lt;style scoped&gt;</code> tag inside DataFrame HTML exports with hardcoded borders. Hiding that inline style tag lets your Tailwind table classes style the DataFrame cleanly in both dark and light mode.</p>
</blockquote>
<h2>4. Wire Up the Next.js Dynamic Route</h2>
<p>Finally, in <code>src/app/diary/research/[slug]/page.tsx</code>, we pre-generate static routes via <code>generateStaticParams()</code>, compute the Table of Contents from the aggregated Markdown cells (<code>post.rawMarkdownForToc</code>), and render <code>&lt;NotebookRenderer /&gt;</code>:</p>
<pre><code class="language-tsx">import { notFound } from &quot;next/navigation&quot;;
import NotebookRenderer from &quot;@/components/NotebookRenderer&quot;;
import { TableOfContents } from &quot;@/components/MagicToc&quot;;
import { getTableOfContents } from &quot;@/lib/toc&quot;;
import { getAllResearchItems, getResearchBySlug } from &quot;@/lib/ipynb&quot;;
import { formatDate } from &quot;@/lib/utils&quot;;

export async function generateStaticParams() {
  const posts = await getAllResearchItems();
  return posts.map((post) =&gt; ({ slug: post.slugAsParams }));
}

export default async function PostPage({
  params,
}: {
  params: { slug: string };
}) {
  const post = await getResearchBySlug(params.slug);
  if (!post) notFound();

  const toc = await getTableOfContents(post.rawMarkdownForToc);

  return (
    &lt;article className=&quot;relative&quot;&gt;
      &lt;TableOfContents toc={toc} /&gt;
      &lt;div className=&quot;space-y-2 mb-12&quot;&gt;
        &lt;h1 className=&quot;text-4xl font-extrabold tracking-tight&quot;&gt;{post.title}&lt;/h1&gt;
        &lt;time
          dateTime={post.publishedAt}
          className=&quot;block text-muted-foreground/60&quot;
        &gt;
          {formatDate(post.publishedAt)} &amp;middot; {post.duration}
        &lt;/time&gt;
      &lt;/div&gt;

      {post.cells &amp;&amp; (
        &lt;NotebookRenderer
          cells={post.cells}
          language={post.language}
          kernelName={post.kernelName}
        /&gt;
      )}
    &lt;/article&gt;
  );
}
</code></pre>
<h1>Adding Metadata to Your .ipynb Files</h1>
<p>With this setup, you have two ways to control how a notebook appears in the list view:</p>
<ol>
<li><strong>Zero-Config (Automatic):</strong> Drop any <code>.ipynb</code> file into <code>content/research/</code>. The parser automatically uses the first <code># Heading</code> as the title, the first paragraph as the summary, the file's modification date as <code>publishedAt</code>, and calculates reading time (<code>duration</code>) from the word count.</li>
<li><strong>Explicit YAML Frontmatter (Optional):</strong> Add a YAML frontmatter block at the top of the first Markdown cell in your notebook:</li>
</ol>
<pre><code class="language-yaml">---
title: Principal Component Analysis from Scratch
publishedAt: 2026-11-09
summary: Deriving eigendecomposition and SVD for dimensionality reduction.
duration: 12min
---
</code></pre>
<p>The parser extracts the frontmatter metadata and strips it from the rendered cell automatically.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Gaussian Mixture Models]]></title>
            <link>https://gopalverma.com/diary/research/Gaussian-Mixtures</link>
            <guid>https://gopalverma.com/diary/research/Gaussian-Mixtures</guid>
            <pubDate>Mon, 09 Nov 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Short intro to Gaussian Mixture Models]]></description>
            <content:encoded><![CDATA[<p>This note is inspired by the <a href="https://github.com/jakevdp/PythonDataScienceHandbook/tree/master">Python Data Science Handbook by Jake VanderPlas</a>.<br>
Thanks <a href="https://x.com/jakevdp">@jakevdp</a>!</p>
<h1>Gaussian Mixture Models</h1>
<p>The <em>k</em>-means clustering model explored in the previous chapter is simple and relatively easy to understand, but its simplicity leads to practical challenges in its application.<br>
In particular, the nonprobabilistic nature of <em>k</em>-means and its use of simple distance from cluster center to assign cluster membership leads to poor performance for many real-world situations.<br>
In this chapter we will take a look at Gaussian mixture models, which can be viewed as an extension of the ideas behind <em>k</em>-means, but can also be a powerful tool for estimation beyond simple clustering.</p>
<p>We begin with the standard imports:</p>
<h2>Motivating Gaussian Mixtures: Weaknesses of k-Means</h2>
<p>Let's take a look at some of the weaknesses of <em>k</em>-means and think about how we might improve the cluster model.<br>
As we saw in the previous chapter, given simple, well-separated data, <em>k</em>-means finds suitable clustering results.</p>
<p>For example, if we have simple blobs of data, the <em>k</em>-means algorithm can quickly label those clusters in a way that closely matches what we might do by eye (see the following figure):</p>
<p>From an intuitive standpoint, we might expect that the clustering assignment for some points is more certain than others: for example, there appears to be a very slight overlap between the two middle clusters, such that we might not have complete confidence in the cluster assignment of points between them.<br>
Unfortunately, the <em>k</em>-means model has no intrinsic measure of probability or uncertainty of cluster assignments (although it may be possible to use a bootstrap approach to estimate this uncertainty).<br>
For this, we must think about generalizing the model.</p>
<p>One way to think about the <em>k</em>-means model is that it places a circle (or, in higher dimensions, a hypersphere) at the center of each cluster, with a radius defined by the most distant point in the cluster.<br>
This radius acts as a hard cutoff for cluster assignment within the training set: any point outside this circle is not considered a member of the cluster.<br>
We can visualize this cluster model with the following function (see the following figure):</p>
<p>An important observation for <em>k</em>-means is that these cluster models <em>must be circular</em>: <em>k</em>-means has no built-in way of accounting for oblong or elliptical clusters.<br>
So, for example, if we take the same data and transform it, the cluster assignments end up becoming muddled, as you can see in the following figure:</p>
<p>By eye, we recognize that these transformed clusters are noncircular, and thus circular clusters would be a poor fit.<br>
Nevertheless, <em>k</em>-means is not flexible enough to account for this, and tries to force-fit the data into four circular clusters.<br>
This results in a mixing of cluster assignments where the resulting circles overlap: see especially the bottom-right of this plot.<br>
One might imagine addressing this particular situation by preprocessing the data with PCA (see <a href="05.09-Principal-Component-Analysis.ipynb">In Depth: Principal Component Analysis</a>), but in practice there is no guarantee that such a global operation will circularize the individual groups.</p>
<p>These two disadvantages of <em>k</em>-means—its lack of flexibility in cluster shape and lack of probabilistic cluster assignment—mean that for many datasets (especially low-dimensional datasets) it may not perform as well as you might hope.</p>
<p>You might imagine addressing these weaknesses by generalizing the <em>k</em>-means model: for example, you could measure uncertainty in cluster assignment by comparing the distances of each point to <em>all</em> cluster centers, rather than focusing on just the closest.<br>
You might also imagine allowing the cluster boundaries to be ellipses rather than circles, so as to account for noncircular clusters.<br>
It turns out these are two essential components of a different type of clustering model, Gaussian mixture models.</p>
<h2>Generalizing E–M: Gaussian Mixture Models</h2>
<p>A Gaussian mixture model (GMM) attempts to find a mixture of multidimensional Gaussian probability distributions that best model any input dataset.<br>
In the simplest case, GMMs can be used for finding clusters in the same manner as <em>k</em>-means (see the following figure):</p>
<p>But because a GMM contains a probabilistic model under the hood, it is also possible to find probabilistic cluster assignments—in Scikit-Learn this is done using the <code>predict_proba</code> method.<br>
This returns a matrix of size <code>[n_samples, n_clusters]</code> which measures the probability that any point belongs to the given cluster:</p>
<p>We can visualize this uncertainty by, for example, making the size of each point proportional to the certainty of its prediction; looking at the following figure, we can see that it is precisely the points at the boundaries between clusters that reflect this uncertainty of cluster assignment:</p>
<p>Under the hood, a Gaussian mixture model is very similar to <em>k</em>-means: it uses an expectation–maximization approach, which qualitatively does the following:</p>
<ol>
<li>
<p>Choose starting guesses for the location and shape.</p>
</li>
<li>
<p>Repeat until converged:</p>
<ol>
<li><em>E-step</em>: For each point, find weights encoding the probability of membership in each cluster.</li>
<li><em>M-step</em>: For each cluster, update its location, normalization, and shape based on <em>all</em> data points, making use of the weights.</li>
</ol>
</li>
</ol>
<p>The result of this is that each cluster is associated not with a hard-edged sphere, but with a smooth Gaussian model.<br>
Just as in the <em>k</em>-means expectation–maximization approach, this algorithm can sometimes miss the globally optimal solution, and thus in practice multiple random initializations are used.</p>
<p>Let's create a function that will help us visualize the locations and shapes of the GMM clusters by drawing ellipses based on the GMM output:</p>
<p>With this in place, we can take a look at what the four-component GMM gives us for our initial data (see the following figure):</p>
<p>Similarly, we can use the GMM approach to fit our stretched dataset; allowing for a full covariance the model will fit even very oblong, stretched-out clusters, as we can see in the following figure:</p>
<p>This makes clear that GMMs address the two main practical issues with <em>k</em>-means encountered before.</p>
<h2>Choosing the Covariance Type</h2>
<p>If you look at the details of the preceding fits, you will see that the <code>covariance_type</code> option was set differently within each.<br>
This hyperparameter controls the degrees of freedom in the shape of each cluster; it is essential to set this carefully for any given problem.<br>
The default is <code>covariance_type=&quot;diag&quot;</code>, which means that the size of the cluster along each dimension can be set independently, with the resulting ellipse constrained to align with the axes.<br>
A slightly simpler and faster model is <code>covariance_type=&quot;spherical&quot;</code>, which constrains the shape of the cluster such that all dimensions are equal. The resulting clustering will have similar characteristics to that of <em>k</em>-means, though it is not entirely equivalent.<br>
A more complicated and computationally expensive model (especially as the number of dimensions grows) is to use <code>covariance_type=&quot;full&quot;</code>, which allows each cluster to be modeled as an ellipse with arbitrary orientation.</p>
<h2>Gaussian Mixture Models as Density Estimation</h2>
<p>Though the GMM is often categorized as a clustering algorithm, fundamentally it is an algorithm for <em>density estimation</em>.<br>
That is to say, the result of a GMM fit to some data is technically not a clustering model, but a generative probabilistic model describing the distribution of the data.</p>
<p>As an example, consider some data generated from Scikit-Learn's <code>make_moons</code> function, introduced in <a href="05.11-K-Means.ipynb">In Depth: K-Means Clustering</a> (see the following figure):</p>
<p>If we try to fit this with a two-component GMM viewed as a clustering model, the results are not particularly useful (see the following figure):</p>
<p>But if we instead use many more components and ignore the cluster labels, we find a fit that is much closer to the input data (see the following figure):</p>
<p>Here the mixture of 16 Gaussian components serves not to find separated clusters of data, but rather to model the overall <em>distribution</em> of the input data.<br>
This is a generative model of the distribution, meaning that the GMM gives us the recipe to generate new random data distributed similarly to our input.<br>
For example, here are 400 new points drawn from this 16-component GMM fit to our original data (see the following figure):</p>
<p>A GMM is convenient as a flexible means of modeling an arbitrary multidimensional distribution of data.</p>
<h3>How Many Components?</h3>
<p>The fact that a GMM is a generative model gives us a natural means of determining the optimal number of components for a given dataset.<br>
A generative model is inherently a probability distribution for the dataset, and so we can simply evaluate the <em>likelihood</em> of the data under the model, using cross-validation to avoid overfitting.<br>
Another means of correcting for overfitting is to adjust the model likelihoods using some analytic criterion such as the <a href="https://en.wikipedia.org/wiki/Akaike_information_criterion">Akaike information criterion (AIC)</a> or the <a href="https://en.wikipedia.org/wiki/Bayesian_information_criterion">Bayesian information criterion (BIC)</a>.<br>
Scikit-Learn's <code>GaussianMixture</code> estimator actually includes built-in methods that compute both of these, so it is very easy to operate using this approach.</p>
<p>Let's look at the AIC and BIC versus the number of GMM components for our moons dataset (see the following figure):</p>
<p>The optimal number of clusters is the value that minimizes the AIC or BIC, depending on which approximation we wish to use. The AIC tells us that our choice of 16 components earlier was probably too many: around 8–12 components would have been a better choice.<br>
As is typical with this sort of problem, the BIC recommends a simpler model.</p>
<p>Notice the important point: this choice of number of components measures how well a GMM works <em>as a density estimator</em>, not how well it works <em>as a clustering algorithm</em>.<br>
I'd encourage you to think of the GMM primarily as a density estimator, and use it for clustering only when warranted within simple datasets.</p>
<h2>Example: GMMs for Generating New Data</h2>
<p>We just saw a simple example of using a GMM as a generative model in order to create new samples from the distribution defined by the input data.<br>
Here we will run with this idea and generate <em>new handwritten digits</em> from the standard digits corpus that we have used before.</p>
<p>To start with, let's load the digits data using Scikit-Learn's data tools:</p>
<p>Next, let's plot the first 50 of these to recall exactly what we're looking at (see the following figure):</p>
<p>We have nearly 1,800 digits in 64 dimensions, and we can build a GMM on top of these to generate more.<br>
GMMs can have difficulty converging in such a high-dimensional space, so we will start with an invertible dimensionality reduction algorithm on the data.<br>
Here we will use a straightforward PCA, asking it to preserve 99% of the variance in the projected data:</p>
<p>The result is 41 dimensions, a reduction of nearly 1/3 with almost no information loss.<br>
Given this projected data, let's use the AIC to get a gauge for the number of GMM components we should use (see the following figure):</p>
<p>It appears that around 140 components minimizes the AIC; we will use this model.<br>
Let's quickly fit this to the data and confirm that it has converged:</p>
<p>Now we can draw samples of 100 new points within this 41-dimensional projected space, using the GMM as a generative model:</p>
<p>Finally, we can use the inverse transform of the PCA object to construct the new digits (see the following figure):</p>
<p>The results for the most part look like plausible digits from the dataset!</p>
<p>Consider what we've done here: given a sampling of handwritten digits, we have modeled the distribution of that data in such a way that we can generate brand new samples of digits from the data: these are &quot;handwritten digits,&quot; which do not individually appear in the original dataset, but rather capture the general features of the input data as modeled by the mixture model.<br>
Such a generative model of digits can prove very useful as a component of a Bayesian generative classifier, as we shall see in the next chapter.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Visualization with Matplotlib]]></title>
            <link>https://gopalverma.com/diary/research/Introduction-To-Matplotlib</link>
            <guid>https://gopalverma.com/diary/research/Introduction-To-Matplotlib</guid>
            <pubDate>Mon, 09 Nov 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[An in-depth look at the Matplotlib package for visualization in Python.]]></description>
            <content:encoded><![CDATA[<p>This note is inspired by the <a href="https://github.com/jakevdp/PythonDataScienceHandbook/tree/master">Python Data Science Handbook by Jake VanderPlas</a>.<br>
Thanks <a href="https://x.com/jakevdp">@jakevdp</a>!</p>
<h1>Visualization with Matplotlib</h1>
<p>We'll now take an in-depth look at the Matplotlib package for visualization in Python.<br>
Matplotlib is a multiplatform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.<br>
It was conceived by John Hunter in 2002, originally as a patch to IPython for enabling interactive MATLAB-style plotting via <code>gnuplot</code> from the IPython command line.<br>
IPython's creator, Fernando Perez, was at the time scrambling to finish his PhD, and let John know he wouldn’t have time to review the patch for several months.<br>
John took this as a cue to set out on his own, and the Matplotlib package was born, with version 0.1 released in 2003.<br>
It received an early boost when it was adopted as the plotting package of choice of the Space Telescope Science Institute (the folks behind the Hubble Telescope), which financially supported Matplotlib’s development and greatly expanded its capabilities.</p>
<p>One of Matplotlib’s most important features is its ability to play well with many operating systems and graphics backends.<br>
Matplotlib supports dozens of backends and output types, which means you can count on it to work regardless of which operating system you are using or which output format you desire.<br>
This cross-platform, everything-to-everyone approach has been one of the great strengths of Matplotlib.<br>
It has led to a large user base, which in turn has led to an active developer base and Matplotlib’s powerful tools and ubiquity within the scientific Python world.</p>
<p>In recent years, however, the interface and style of Matplotlib have begun to show their age.<br>
Newer tools like <code>ggplot</code> and <code>ggvis</code> in the R language, along with web visualization toolkits based on D3js and HTML5 canvas, often make Matplotlib feel clunky and old-fashioned.<br>
Still, I'm of the opinion that we cannot ignore Matplotlib's strength as a well-tested, cross-platform graphics engine.<br>
Recent Matplotlib versions make it relatively easy to set new global plotting styles (see <a href="04.11-Settings-and-Stylesheets.ipynb">Customizing Matplotlib: Configurations and Style Sheets</a>), and people have been developing new packages that build on its powerful internals to drive Matplotlib via cleaner, more modern APIs—for example, Seaborn (discussed in <a href="04.14-Visualization-With-Seaborn.ipynb">Visualization With Seaborn</a>), <a href="http://yhat.github.io/ggpy/"><code>ggpy</code></a>, <a href="http://holoviews.org/">HoloViews</a>, and even Pandas itself can be used as wrappers around Matplotlib's API.<br>
Even with wrappers like these, it is still often useful to dive into Matplotlib's syntax to adjust the final plot output.<br>
For this reason, I believe that Matplotlib itself will remain a vital piece of the data visualization stack, even if new tools mean the community gradually moves away from using the Matplotlib API directly.</p>
<h1>General Matplotlib Tips</h1>
<p>Before we dive into the details of creating visualizations with Matplotlib, there are a few useful things you should know about using the package.</p>
<h2>Importing Matplotlib</h2>
<p>Just as we use the <code>np</code> shorthand for NumPy and the <code>pd</code> shorthand for Pandas, we will use some standard shorthands for Matplotlib imports:</p>
<p>The <code>plt</code> interface is what we will use most often, as you shall see throughout this part of the book.</p>
<h2>Setting Styles</h2>
<p>We will use the <code>plt.style</code> directive to choose appropriate aesthetic styles for our figures.<br>
Here we will set the <code>classic</code> style, which ensures that the plots we create use the classic Matplotlib style:</p>
<p>Throughout this chapter, we will adjust this style as needed.<br>
For more information on stylesheets, see <a href="04.11-Settings-and-Stylesheets.ipynb">Customizing Matplotlib: Configurations and Style Sheets</a>.</p>
<h2>Show or No show? How to Display Your Plots</h2>
<p>A visualization you can't see won't be of much use, but just how you view your Matplotlib plots depends on the context.<br>
The best use of Matplotlib differs depending on how you are using it; roughly, the three applicable contexts are using Matplotlib in a script, in an IPython terminal, or in a Jupyter notebook.</p>
<h3>Plotting from a Script</h3>
<p>If you are using Matplotlib from within a script, the function <code>plt.show</code> is your friend.<br>
<code>plt.show</code> starts an event loop, looks for all currently active <code>Figure</code> objects, and opens one or more interactive windows that display your figure or figures.</p>
<p>So, for example, you may have a file called <em><a href="http://myplot.py">myplot.py</a></em> containing the following:</p>
<pre><code class="language-python"># file: myplot.py 
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))

plt.show()
</code></pre>
<p>You can then run this script from the command-line prompt, which will result in a window opening with your figure displayed:</p>
<pre><code>$ python myplot.py
</code></pre>
<p>The <code>plt.show</code> command does a lot under the hood, as it must interact with your system's interactive graphical backend.<br>
The details of this operation can vary greatly from system to system and even installation to installation, but Matplotlib does its best to hide all these details from you.</p>
<p>One thing to be aware of: the <code>plt.show</code> command should be used <em>only once</em> per Python session, and is most often seen at the very end of the script.<br>
Multiple <code>show</code> commands can lead to unpredictable backend-dependent behavior, and should mostly be avoided.</p>
<h3>Plotting from an IPython Shell</h3>
<p>Matplotlib also works seamlessly within an IPython shell (see <a href="01.00-IPython-Beyond-Normal-Python.ipynb">IPython: Beyond Normal Python</a>).<br>
IPython is built to work well with Matplotlib if you specify Matplotlib mode.<br>
To enable this mode, you can use the <code>%matplotlib</code> magic command after starting <code>ipython</code>:</p>
<pre><code class="language-ipython">In [1]: %matplotlib
Using matplotlib backend: TkAgg

In [2]: import matplotlib.pyplot as plt
</code></pre>
<p>At this point, any <code>plt</code> plot command will cause a figure window to open, and further commands can be run to update the plot.<br>
Some changes (such as modifying properties of lines that are already drawn) will not draw automatically: to force an update, use <code>plt.draw</code>.<br>
Using <code>plt.show</code> in IPython's Matplotlib mode is not required.</p>
<h3>Plotting from a Jupyter Notebook</h3>
<p>The Jupyter notebook is a browser-based interactive data analysis tool that can combine narrative, code, graphics, HTML elements, and much more into a single executable document (see <a href="01.00-IPython-Beyond-Normal-Python.ipynb">IPython: Beyond Normal Python</a>).</p>
<p>Plotting interactively within a Jupyter notebook can be done with the <code>%matplotlib</code> command, and works in a similar way to the IPython shell.<br>
You also have the option of embedding graphics directly in the notebook, with two possible options:</p>
<ul>
<li><code>%matplotlib inline</code> will lead to <em>static</em> images of your plot embedded in the notebook.</li>
<li><code>%matplotlib notebook</code> will lead to <em>interactive</em> plots embedded within the notebook.</li>
</ul>
<p>For this book, we will generally stick with the default, with figures rendered as static images (see the following figure for the result of this basic plotting example):</p>
<h3>Saving Figures to File</h3>
<p>One nice feature of Matplotlib is the ability to save figures in a wide variety of formats.<br>
Saving a figure can be done using the <code>savefig</code> command.<br>
For example, to save the previous figure as a PNG file, we can run this:</p>
<p>We now have a file called <em>my_figure.png</em> in the current working directory:</p>
<p>To confirm that it contains what we think it contains, let's use the IPython <code>Image</code> object to display the contents of this file (see the following figure):</p>
<p>In <code>savefig</code>, the file format is inferred from the extension of the given filename.<br>
Depending on what backends you have installed, many different file formats are available.<br>
The list of supported file types can be found for your system by using the following method of the figure canvas object:</p>
<p>Note that when saving your figure, it is not necessary to use <code>plt.show</code> or related commands discussed earlier.</p>
<h3>Two Interfaces for the Price of One</h3>
<p>A potentially confusing feature of Matplotlib is its dual interfaces: a convenient MATLAB-style state-based interface, and a more powerful object-oriented interface. I'll quickly highlight the differences between the two here.</p>
<h4>MATLAB-style Interface</h4>
<p>Matplotlib was originally conceived as a Python alternative for MATLAB users, and much of its syntax reflects that fact.<br>
The MATLAB-style tools are contained in the <code>pyplot</code> (<code>plt</code>) interface.<br>
For example, the following code will probably look quite familiar to MATLAB users (the following figure shows the result):</p>
<p>It is important to recognize that this interface is <em>stateful</em>: it keeps track of the &quot;current&quot; figure and axes, which are where all <code>plt</code> commands are applied.<br>
You can get a reference to these using the <code>plt.gcf</code> (get current figure) and <code>plt.gca</code> (get current axes) routines.</p>
<p>While this stateful interface is fast and convenient for simple plots, it is easy to run into problems.<br>
For example, once the second panel is created, how can we go back and add something to the first?<br>
This is possible within the MATLAB-style interface, but a bit clunky.<br>
Fortunately, there is a better way.</p>
<h4>Object-oriented interface</h4>
<p>The object-oriented interface is available for these more complicated situations, and for when you want more control over your figure.<br>
Rather than depending on some notion of an &quot;active&quot; figure or axes, in the object-oriented interface the plotting functions are <em>methods</em> of explicit <code>Figure</code> and <code>Axes</code> objects.<br>
To re-create the previous plot using this style of plotting, as shown in the following figure, you might do the following:</p>
<p>For simpler plots, the choice of which style to use is largely a matter of preference, but the object-oriented approach can become a necessity as plots become more complicated.<br>
Throughout the following chapters, we will switch between the MATLAB-style and object-oriented interfaces, depending on what is most convenient.<br>
In most cases, the difference is as small as switching <code>plt.plot</code> to <code>ax.plot</code>, but there are a few gotchas that I will highlight as they come up in the following chapters.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Edge Computing & TinyML]]></title>
            <link>https://gopalverma.com/diary/blogs/edge-computing-and-tinyml</link>
            <guid>https://gopalverma.com/diary/blogs/edge-computing-and-tinyml</guid>
            <pubDate>Thu, 25 Sep 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Edge Computing & TinyML And Bringing Intelligence to the Edge]]></description>
            <content:encoded><![CDATA[<p>The past decade has witnessed an explosion in the number of IoT endpoints—sensors, wearables, actuators, smart appliances. While cloud-based analytics have served us well, emerging use cases demand <strong>real-time</strong>, <strong>low-latency</strong>, <strong>private</strong>, and <strong>ultra-efficient</strong> processing. That’s where <strong>edge computing</strong> and <strong>TinyML</strong> come together, enabling machine learning models to run <em>directly on devices</em> or on edge nodes close to devices.</p>
<p>In this blog, I’ll walk you through:</p>
<ul>
<li>What edge computing and TinyML are, and why they matter</li>
<li>Architectural patterns and tradeoffs</li>
<li>How to build and deploy lightweight models</li>
<li>Real-world case studies (manufacturing, healthcare, conservation)</li>
<li>Performance comparisons and practical challenges</li>
<li>Future directions</li>
</ul>
<p>My goal is to keep this human and conversational, not overly formal—let’s explore this together.</p>
<h1>What is Edge Computing, and Why Now?</h1>
<p>Edge computing refers to moving computation, storage, or analytics closer to where the data is generated (the “edge” of the network) instead of sending everything to a centralized cloud.</p>
<h2>Why is edge computing suddenly so relevant?</h2>
<ul>
<li><strong>Latency Sensitivity</strong>: Some applications (e.g. defect detection, autonomous control, medical alerts) can’t wait for a round-trip to the cloud.</li>
<li><strong>Bandwidth / Cost Constraints</strong>: Transmitting raw sensor data (e.g. video, high-sample signals) is expensive or impractical.</li>
<li><strong>Connectivity Gaps</strong>: Many devices operate in remote or intermittently connected environments.</li>
<li><strong>Privacy &amp; Compliance</strong>: Keeping sensitive data locally (on device) avoids sending raw personal or health data over networks.</li>
<li><strong>Resiliency</strong>: Edge nodes can continue working even when connectivity to the cloud is degraded.</li>
</ul>
<p>IBM lists a host of use cases—from autonomous vehicles to industrial control and healthcare—where edge computing delivers tangible value. (<a href="https://www.ibm.com/think/topics/edge-computing-use-cases" title="Edge computing: Top use cases">IBM</a>)</p>
<h2>Edge tiers and hybrid architectures</h2>
<p>You don’t always need <em>all</em> the intelligence on the microcontroller. A typical architecture is hierarchical:</p>
<ol>
<li><strong>Device / Sensor level</strong> (microcontroller, sensor node)</li>
<li><strong>Edge gateway / local aggregator</strong> (Raspberry Pi, industrial PC, edge server)</li>
<li><strong>Cloud backend / central AI / model updates</strong></li>
</ol>
<p>At each layer, some processing, filtering, or inference may happen. The trick is knowing <strong>which tasks</strong> belong where.</p>
<h1>Enter TinyML: Machine Learning for Microcontrollers</h1>
<p><strong>TinyML</strong> is the discipline of building and deploying ML models on heavily resource-constrained devices (microcontrollers, low-power SoCs). The idea: run inference (not full training) on ultra-low-power hardware.</p>
<h2>Key characteristics of TinyML</h2>
<ul>
<li>Works on devices with <strong>tens to hundreds of kilobytes</strong> of RAM and limited compute</li>
<li>Emphasis on <strong>very low-power consumption</strong></li>
<li>Uses optimized models (quantized, pruned, compact architectures)</li>
<li>Usually supports a <strong>fixed inference pipeline</strong>, not full retraining</li>
</ul>
<p>See the Embedded article “Deploying Neural Networks on Microcontrollers with TinyML” for a good introduction to the workflow. (<a href="https://www.embedded.com/deploying-neural-networks-on-microcontrollers-with-tinyml/" title="Deploying Neural Networks on Microcontrollers with TinyML">Embedded</a>)</p>
<p>Recent survey work highlights how edge computing + TinyML synergize: embedding intelligence at the endpoints to reduce communication, latency, and energy consumption. (<a href="https://www.mdpi.com/2079-9292/13/17/3562" title="Advancements in TinyML: Applications, Limitations, and ...">MDPI</a>)</p>
<h1>Building and Deploying TinyML Models — A Walkthrough</h1>
<p>Let me outline a practical pipeline for developing a TinyML solution. I’ll also show some code snippets to make this concrete.</p>
<h2>1. Data collection and preprocessing</h2>
<p>You gather data from sensors (accelerometer, vibration, audio, etc.). Preprocessing might include filtering, normalization, windowing, feature extraction (e.g. FFT, spectrograms).</p>
<p>Example (Python) for a sliding window:</p>
<pre><code class="language-python">import numpy as np

def sliding_windows(signal, window_size, step_size):
    windows = []
    for start in range(0, len(signal) - window_size + 1, step_size):
        windows.append(signal[start : start + window_size])
    return np.stack(windows)

# Example: 1D accelerometer series
sig = np.load(&quot;accel_data.npy&quot;)
windows = sliding_windows(sig, window_size=128, step_size=32)
</code></pre>
<p>You might compute features like mean, variance, FFT bins, etc. Or directly feed the raw window into a small neural network.</p>
<h2>2. Model selection, training &amp; optimization</h2>
<p>Pick a compact neural architecture (e.g. small CNN, 1D conv, MLP). Train it on a desktop or server. Then:</p>
<ul>
<li><strong>Quantize</strong> (e.g. 8-bit integer operations)</li>
<li><strong>Prune</strong> (remove redundant weights)</li>
<li><strong>Knowledge distillation</strong> (train small model to mimic a larger one)</li>
</ul>
<p>Frameworks like <strong>TensorFlow Lite for Microcontrollers (TFLite Micro)</strong> help convert models to C arrays. There’s also <strong>Edge Impulse</strong> (a no-code/low-code platform) that targets TinyML workflows.</p>
<p>Example: converting a Keras model to a TFLite quantized model:</p>
<pre><code class="language-python">import tensorflow as tf

model = ...  # your trained Keras model
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
# Optionally specify representative dataset for quantization
def representative_dataset():
    for x in tf.data.Dataset.from_tensor_slices(training_data).batch(1).take(100):
        yield [x]
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8

tflite_model = converter.convert()
with open(&quot;model_quant.tflite&quot;, &quot;wb&quot;) as f:
    f.write(tflite_model)
</code></pre>
<h2>3. Porting and deploying to microcontroller</h2>
<p>Once you have a <code>.tflite</code> file, you embed it in the firmware. If using TFLite Micro, you include the model as a C array.</p>
<p>Example skeleton (C++):</p>
<pre><code class="language-cpp">#include &quot;tensorflow/lite/micro/all_ops_resolver.h&quot;
#include &quot;tensorflow/lite/micro/micro_interpreter.h&quot;
#include &quot;model_data.h&quot;  // generated header containing model bytes

constexpr int tensor_arena_size = 10 * 1024;  // adjust as needed
uint8_t tensor_arena[tensor_arena_size];

void setup() {
  // set up interpreter
  static tflite::MicroMutableOpResolver&lt;10&gt; resolver;
  resolver.AddDense();
  resolver.AddConv2D();
  // add other ops you need

  tflite::MicroInterpreter interpreter(
    model, resolver, tensor_arena, tensor_arena_size, error_reporter);

  interpreter.AllocateTensors();

  // get input &amp; output pointers
  TfLiteTensor* input = interpreter.input(0);
  TfLiteTensor* output = interpreter.output(0);
}

void loop() {
  // fill input data
  // e.g. copy sensor data window into input-&gt;data.int8 (if quantized)
  ...
  interpreter.Invoke();
  int8_t* result = output-&gt;data.int8;
  // interpret the output
  ...
}
</code></pre>
<p>You should also handle sensor reading, buffering, interrupts, power management, etc.</p>
<h2>4. Edge &amp; cloud coordination</h2>
<p>Your devices may periodically transmit <em>only the inference results</em>, or if anomaly detected, the raw data. The edge gateway or cloud can perform heavier aggregation, model updates, retraining, and fleet management.</p>
<p>You can also adopt <strong>hierarchical TinyML</strong>, where each device runs a simple model, and an edge node does ensemble decisions across multiple endpoints. For example, Sanchez-Iborra et al. propose a two-layer TinyML scheme in agriculture that reduces communication and energy costs. (<a href="https://informatica.vu.lt/journal/INFORMATICA/article/1281/text" title="Intelligent and Efficient IoT Through the Cooperation of ...">Informatica</a>)</p>
<h1>Real-World Case Studies &amp; Applications</h1>
<p>To ground this discussion, here are interesting real-world uses:</p>
<h2>Manufacturing &amp; Predictive Maintenance</h2>
<ul>
<li>TinyML sensors continuously listen to motor or bearing vibration; when patterns deviate, the device raises an alert locally instead of streaming raw time-series.</li>
<li>An ultra-low-power visual TinyML system processed object detection at 30 FPS with only ~160 mW using a co-processor + MCU setup. (<a href="https://arxiv.org/abs/2207.04663" title="An Ultra-low Power TinyML System for Real-time Visual Processing at Edge">arXiv</a>)</li>
</ul>
<h2>Healthcare &amp; Remote Monitoring</h2>
<ul>
<li>Wearable sensors performing ECG or breathing analysis locally to detect arrhythmias or apnea events in real time.</li>
<li>In environmental monitoring / conservation, one project deployed TinyML on an Arduino Nano 33 BLE to classify hornbill bird calls (for wildlife monitoring) directly at the edge. (<a href="https://arxiv.org/abs/2504.12272" title="Edge Intelligence for Wildlife Conservation: Real-Time Hornbill Call Classification Using TinyML">arXiv</a>)</li>
</ul>
<h2>Smart Agriculture / Environmental IoT</h2>
<ul>
<li>A TinyML + LoRa setup where devices predict optimal LoRa channel hopping locally to reduce packet collisions and improve link performance. Their approach increased RSSI by up to 63% and SNR by 44% compared to random hopping. (<a href="https://arxiv.org/abs/2412.01609" title="Optimizing LoRa for Edge Computing with TinyML Pipeline for Channel Hopping">arXiv</a>)</li>
<li>In a hierarchical scheme, as earlier mentioned, IoT nodes use TinyML to make local decisions, and these are aggregated by an edge node to form a global decision (e.g. soil moisture control). (<a href="https://informatica.vu.lt/journal/INFORMATICA/article/1281/text" title="Intelligent and Efficient IoT Through the Cooperation of ...">Informatica</a>)</li>
</ul>
<h2>Urban Mobility &amp; Smart Cities</h2>
<ul>
<li>A FIWARE-based architecture extended to support TinyML and ML Ops for urban systems (e.g. traffic), managing full model lifecycles across edge devices. (<a href="https://arxiv.org/abs/2411.13583" title="Enhanced FIWARE-Based Architecture for Cyberphysical Systems With Tiny Machine Learning and Machine Learning Operations: A Case Study on Urban Mobility Systems">arXiv</a>)</li>
</ul>
<h2>Consumer &amp; Ambient Devices</h2>
<ul>
<li>“No More Coffee Spills” (NMCS): a microcontroller detects brewing sound via microphone and uses a vision module (TinyML) to check whether a cup is present; alerts the user if the cup is missing. (<a href="https://files.seeedstudio.com/wiki/K1100-quick-start/TinyML-Case-Studies.pdf" title="TinyML Case Studies">Seeed Studio Files</a>)</li>
<li>Liquid classification and “electronic nose” devices built using tiny sensors + TinyML to distinguish substances like water quality or beverage types. (<a href="https://files.seeedstudio.com/wiki/K1100-quick-start/TinyML-Case-Studies.pdf" title="TinyML Case Studies">Seeed Studio Files</a>)</li>
</ul>
<h1>Performance Comparison: Edge / TinyML vs Cloud ML</h1>
<p>Here’s a rough sketch of tradeoffs (actual numbers depend heavily on use case, hardware, model):</p>
<table>
<thead>
<tr>
<th>Metric</th>
<th>TinyML / Edge</th>
<th>Cloud ML</th>
</tr>
</thead>
<tbody>
<tr>
<td>Latency</td>
<td>Very low (ms)</td>
<td>Higher (network + processing delay)</td>
</tr>
<tr>
<td>Bandwidth usage</td>
<td>Minimal (only inference results or anomalies)</td>
<td>High (raw data upload)</td>
</tr>
<tr>
<td>Energy / Power</td>
<td>Ultra constrained, optimized</td>
<td>Less constrained but cost of networking matters</td>
</tr>
<tr>
<td>Model complexity</td>
<td>Smaller, simpler models; limited capacity</td>
<td>Large, deep models</td>
</tr>
<tr>
<td>Model updates / retraining</td>
<td>Challenging to update many endpoints</td>
<td>Easier in centralized cloud</td>
</tr>
<tr>
<td>Scalability in devices</td>
<td>Better for many distributed endpoints</td>
<td>Network and cost can limit scale</td>
</tr>
<tr>
<td>Security / privacy</td>
<td>Sensitive data stays local</td>
<td>Higher exposure risk transmitting data</td>
</tr>
<tr>
<td>Reliability in connectivity loss</td>
<td>Can run offline</td>
<td>Dependent on network availability</td>
</tr>
</tbody>
</table>
<p>Benchmarks in literature show that for many tasks, quantized TinyML models give acceptable accuracy (within a few percentage points) while drastically reducing memory and compute footprint. For example, the Embedded article mentions that converting models to TFLite and pruning can make them feasible on microcontrollers. (<a href="https://www.embedded.com/deploying-neural-networks-on-microcontrollers-with-tinyml/" title="Deploying Neural Networks on Microcontrollers with TinyML">Embedded</a>)</p>
<p>Also, in some TinyML systems, all weights/features are stored on-chip, avoiding power-hungry off-chip memory accesses—this results in both latency and energy reduction. (<a href="https://arxiv.org/abs/2207.04663" title="An Ultra-low Power TinyML System for Real-time Visual Processing at Edge">arXiv</a>)</p>
<p>But it's not a silver bullet: when the model needs to adapt, learn continuously, or handle large context, cloud or hybrid architectures still play a key role.</p>
<h1>Challenges, Best Practices &amp; Tips</h1>
<h2>Challenges</h2>
<ol>
<li><strong>Memory constraints &amp; fragmentation</strong>: tiny RAM, limited flash.</li>
<li><strong>Model accuracy vs size tradeoff</strong></li>
<li><strong>Energy / battery management</strong></li>
<li><strong>Sensor noise, environment drift</strong></li>
<li><strong>OTA (Over-the-Air) updates / versioning</strong></li>
<li><strong>Security of model and data on endpoint</strong></li>
<li><strong>Toolchain fragmentation</strong></li>
</ol>
<h2>Tips &amp; Best Practices</h2>
<ul>
<li>Start with a small baseline model; profile memory and latency early.</li>
<li>Use <strong>representative datasets</strong> (on-device-like inputs) for quantization calibration.</li>
<li>Apply <strong>pruning</strong>, <strong>quantization-aware training</strong>, and <strong>knowledge distillation</strong>.</li>
<li>Consider <strong>sparse architectures</strong> or efficient building blocks (like separable convolutions).</li>
<li>Use hardware accelerators (e.g., NPU, DSP) when available.</li>
<li>Design your system for <strong>fail-safe fallback</strong> (if edge fails, send minimal data to cloud).</li>
<li>Build robust update and rollback mechanisms.</li>
<li>Monitor drift, plan for periodic re-calibration or remote retraining.</li>
<li>Secure the device (encrypt model, prevent adversarial inputs, secure boot).</li>
</ul>
<h1>Future Directions &amp; Trends</h1>
<ul>
<li><strong>Federated learning / split learning</strong> across tiny devices may distribute training more securely.</li>
<li><strong>Adaptive / self-updating models</strong> that evolve based on sensed context.</li>
<li><strong>Multimodal TinyML</strong>: combining audio, vibration, vision at the edge.</li>
<li><strong>Energy harvesting + perpetual devices</strong>, where the device lives indefinitely powered by solar / ambient.</li>
<li><strong>Better tools and abstractions</strong> (AutoML for TinyML, unified toolchains)</li>
<li><strong>Edge-to-cloud continuum</strong>, where intelligence flows across device, edge, and cloud layers.</li>
</ul>
<p>The trend is that TinyML will increasingly blur the line: instead of pushing all intelligence to cloud or all to device, systems will dynamically allocate workloads across tiers.</p>
<h1>Conclusion</h1>
<p>Edge computing and TinyML together unlock a compelling paradigm: intelligence at the source. We can build systems that respond instantly, conserve bandwidth, protect privacy, and scale across massive fleets of devices. But to get there, you need careful architecture, disciplined optimization, and robust update strategies.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Generative AI and Synthetic Data]]></title>
            <link>https://gopalverma.com/diary/blogs/generative-ai-and-synthetic-data</link>
            <guid>https://gopalverma.com/diary/blogs/generative-ai-and-synthetic-data</guid>
            <pubDate>Wed, 24 Sep 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Generative AI and Synthetic Data And Enabling Next-Gen Data Pipelines]]></description>
            <content:encoded><![CDATA[<p>In 2025, generative AI is rapidly reshaping how data scientists think about data augmentation, anonymization, and model training—especially in domains with strict privacy constraints. In this blog, we’ll cover:</p>
<ul>
<li>What synthetic data is, and why it matters</li>
<li>How generative models (GANs, diffusion models, LLMs) are applied to create synthetic data</li>
<li>Practical use-cases in finance, healthcare, analytics</li>
<li>Challenges, pitfalls, and best practices</li>
<li>Outlook: where synthetic data is heading</li>
</ul>
<h1>What Is Synthetic Data, and Why It Matters</h1>
<p><strong>Synthetic data</strong> refers to data that is artificially generated (by algorithms) to mimic the statistical properties, structure, and relationships of real-world datasets, without directly revealing identifiable information.</p>
<p>Key motivations:</p>
<ul>
<li><strong>Privacy &amp; compliance</strong>: In sectors like healthcare, finance, and insurance, strict regulations (e.g. HIPAA, GDPR) restrict use or sharing of real sensitive records. Synthetic data offers a privacy-respecting alternative. (<a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC11958975/" title="Synthetic data generation: a privacy-preserving approach ...">PMC</a>)</li>
<li><strong>Data scarcity &amp; class imbalance</strong>: Some events (fraud, rare disease cases) are infrequent. Synthetic data can artificially upsample rare classes or simulate edge-case scenarios. (<a href="https://humansintheloop.org/why-synthetic-data-is-taking-over-in-2025-solving-ais-data-crisis/" title="Why Synthetic Data Is Taking Over in 2025: Solving AI's Data ...">humansintheloop.org</a>)</li>
<li><strong>Safe sharing &amp; collaboration</strong>: Organizations can share synthetic datasets with partners or external researchers without risking exposure of sensitive data. (<a href="https://research.aimultiple.com/synthetic-data-use-cases/" title="Top 20+ Synthetic Data Use Cases">AIMultiple</a>)</li>
<li><strong>Faster prototyping / validation</strong>: You can generate custom scenarios on demand, test model robustness, validate under stress conditions. (<a href="https://www.tredence.com/blog/synthetic-data-generation" title="Synthetic Data Generation with Generative AI for Tabular ...">tredence.com</a>)</li>
</ul>
<p>However, synthetic data is not a silver bullet. The generated data must maintain <strong>utility</strong> (i.e., support model performance) and <strong>fidelity</strong> (i.e., follow real distributional patterns) without leaking sensitive information.</p>
<h1>How Synthetic Data is Created Using Generative Models</h1>
<p>Broadly, synthetic data generation can leverage different classes of generative models. Below are some of the commonly used approaches as of 2025.</p>
<h2>GANs (Generative Adversarial Networks)</h2>
<ul>
<li>A <strong>generator</strong> network produces synthetic samples; a <strong>discriminator</strong> network tries to distinguish real vs synthetic. Over adversarial training, the generator learns to produce realistic samples.</li>
<li>Variants exist for tabular, image, time-series, and mixed-modal data.</li>
<li>In healthcare, recent work proposes <strong>bias-transforming GANs (Bt-GAN)</strong> to generate fair synthetic EHR data by constraining spurious correlations and preserving subgroup densities. (<a href="https://arxiv.org/abs/2404.13634" title="Bt-GAN: Generating Fair Synthetic Healthdata via Bias-transforming Generative Adversarial Networks">arXiv</a>)</li>
<li>In finance, GANs have long been considered for simulating transaction data, though more recently diffusion-based models are gaining attention. (<a href="https://arxiv.org/html/2508.19570v1" title="Generative Models for Synthetic Data">arXiv</a>)</li>
</ul>
<h2>Diffusion Models &amp; Score-Based Generative Models</h2>
<ul>
<li>Diffusion models gradually corrupt data by adding noise, and then learn to reverse the process to sample from the clean distribution.</li>
<li>They are gaining prominence for tabular data generation because they often avoid some of the mode-collapse issues of GANs.</li>
<li>For instance, <strong>FinDiff</strong> is a diffusion-based model tailored for financial tabular data that generates mixed-type attributes (numeric, categorical) with high utility. (<a href="https://arxiv.org/abs/2309.01472" title="FinDiff: Diffusion Models for Financial Tabular Data Generation">arXiv</a>)</li>
</ul>
<h2>Variational Autoencoders (VAEs) and Their Hybrids</h2>
<ul>
<li>VAEs encode data to a latent space distribution, then decode from latent samples back to synthetic instances.</li>
<li>They can be easier to train and more stable than GANs, but may produce more “blurry” or average-like samples, especially for edge cases.</li>
<li>Some hybrid approaches (e.g., VAE + GAN, VAE with conditional priors) attempt to combine stability with realism.</li>
</ul>
<h2>LLMs / Transformer-Based Models for Tabular or Textual Synthetic Data</h2>
<ul>
<li>Large models (e.g., transformer-style architectures) originally built for text are being adapted to generate structured or semi-structured synthetic data.</li>
<li>One common pattern: convert rows into a serialized token sequence and prompt the model to generate new “rows” consistent with learned patterns.</li>
<li>In domains like healthcare or finance, LLMs can also generate synthetic narratives (clinical notes, transaction descriptions) or synthetic attribute augmentation. (<a href="https://www.dataversity.net/how-generative-ai-is-revolutionizing-training-data-with-synthetic-datasets/" title="How Generative AI Is Revolutionizing Training Data with ...">DATAVERSITY</a>)</li>
</ul>
<h2>Auxiliary Models &amp; Nested Synthetic Pipelines</h2>
<ul>
<li>In advanced pipelines, one generative model (auxiliary model) produces synthetic data which is then used to train or test another model. This nested architecture is becoming more common in large-scale AI workflows. (<a href="https://arxiv.org/abs/2501.18493" title="Examining the Expanding Role of Synthetic Data Throughout the AI Development Pipeline">arXiv</a>)</li>
<li>But this layering increases risk: poor synthetic data can cascade errors downstream.</li>
</ul>
<h2>Domain-Specific Enhancements</h2>
<ul>
<li><strong>Knowledge distillation &amp; domain constraints</strong>: For example, CK4Gen integrates Cox proportional hazards model knowledge into synthetic survival datasets to preserve hazard ratios and realistic survival curves. (<a href="https://arxiv.org/abs/2410.16872" title="CK4Gen: A Knowledge Distillation Framework for Generating High-Utility Synthetic Survival Datasets in Healthcare">arXiv</a>)</li>
<li><strong>Fairness-aware generation</strong>: Enforcing constraints so that protected subgroups are fairly represented and bias amplification is avoided (like Bt-GAN above). (<a href="https://arxiv.org/abs/2404.13634" title="Bt-GAN: Generating Fair Synthetic Healthdata via Bias-transforming Generative Adversarial Networks">arXiv</a>)</li>
</ul>
<h1>Practical Use-Cases &amp; Real-World Impact</h1>
<p>Here are concrete domains and use-cases where synthetic data + generative AI have made notable progress by 2025.</p>
<h2>Healthcare &amp; Clinical Research</h2>
<ul>
<li>Synthetic EHR / patient records: Training diagnostic models, decision-support systems, and analytics models without exposing real patient records. (<a href="https://www.dataversity.net/how-generative-ai-is-revolutionizing-training-data-with-synthetic-datasets/" title="How Generative AI Is Revolutionizing Training Data with ...">DATAVERSITY</a>)</li>
<li>Clinical trial simulation: Synthetic trial arms, patient recruitment, and outcome simulation when sample sizes are low. (<a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC11958975/" title="Synthetic data generation: a privacy-preserving approach ...">PMC</a>)</li>
<li>Rare disease modeling: For very low-incidence conditions, synthetic augmentation helps build predictive models. (<a href="https://www.dataversity.net/how-generative-ai-is-revolutionizing-training-data-with-synthetic-datasets/" title="How Generative AI Is Revolutionizing Training Data with ...">DATAVERSITY</a>)</li>
<li>Survival analysis: CK4Gen (cited above) specifically targets survival datasets while preserving survival curve and hazard distributions. (<a href="https://arxiv.org/abs/2410.16872" title="CK4Gen: A Knowledge Distillation Framework for Generating High-Utility Synthetic Survival Datasets in Healthcare">arXiv</a>)</li>
</ul>
<p>However, challenges in healthcare are acute. For example:</p>
<ul>
<li>Synthetic models may miss <strong>temporal dynamics</strong> or subtle signals, reducing fidelity in critical scenarios (e.g. detecting deterioration). (<a href="https://www.rgnmed.com/post/beyond-the-hype-why-synthetic-data-falls-short-in-healthcare-and-how-regenmed-circles-closes-the-gap" title="Beyond the Hype: Why Synthetic Data Falls Short ...">rgnmed.com</a>)</li>
<li>Over-reliance on synthetic data can lead models to underperform in real-world settings if distribution shift is unaccounted.</li>
</ul>
<h2>Finance, Risk &amp; Fraud Detection</h2>
<ul>
<li><strong>Fraud simulation</strong>: Synthetic transaction histories mimic fraudulent behavior to help models detect anomalies, especially when real fraud examples are rare. (<a href="https://www.netguru.com/blog/synthetic-data" title="Synthetic Data: Revolutionizing Modern AI Development in ...">Netguru</a>)</li>
<li><strong>Stress testing / scenario generation</strong>: Generating hypothetical market or economic scenarios to evaluate models (e.g., shocks, crises) without waiting for real events. (<a href="https://arxiv.org/abs/2309.01472" title="FinDiff: Diffusion Models for Financial Tabular Data Generation">arXiv</a>)</li>
<li><strong>Investment analytics &amp; synthetic factor modeling</strong>: Some asset managers use synthetic data to train models where real data is sparse or proprietary. (<a href="https://blogs.cfainstitute.org/investor/2025/07/31/how-genai-powered-synthetic-data-is-reshaping-investment-workflows/" title="How GenAI-Powered Synthetic Data Is Reshaping ...">CFA Institute Daily Browse</a>)</li>
<li><strong>Data sharing among institutions</strong>: Banks or financial bodies generate synthetic datasets to share (e.g. in consortiums) to evaluate common risk models while preserving confidentiality. (<a href="https://arxiv.org/html/2508.19570v1" title="Generative Models for Synthetic Data">arXiv</a>)</li>
</ul>
<h2>Other Domains</h2>
<ul>
<li><strong>Market research &amp; consumer analytics</strong>: Synthetic consumer responses, simulated survey data to explore “what-if” scenarios while maintaining respondent privacy. (<a href="https://www.greenbook.org/insights/data-science/the-secret-life-of-synthetic-data-why-its-taking-over-research" title="The Secret Life of Synthetic Data: Why It's Taking Over ...">greenbook.org</a>)</li>
<li><strong>Autonomous driving / robotics / simulation</strong>: Synthetic sensor and scenario data (e.g., generating rare edge-case scenes) augment real-world collected data. (<a href="https://www.nvidia.com/en-us/use-cases/synthetic-data/" title="Synthetic Data for AI &amp; 3D Simulation Workflows | Use Case">NVIDIA</a>)</li>
<li><strong>3D, vision, and multimodal pipelines</strong>: Synthetic image, video, 3D model generation for training computer vision systems. (<a href="https://www.nvidia.com/en-us/use-cases/synthetic-data/" title="Synthetic Data for AI &amp; 3D Simulation Workflows | Use Case">NVIDIA</a>)</li>
</ul>
<h2>Business Impact Metrics &amp; Estimates</h2>
<ul>
<li>Gartner estimates that by 2028, <strong>80% of data used for AI</strong> will be synthetic in nature. (<a href="https://www.ibm.com/think/insights/streamline-accelerate-ai-initiatives-synthetic-data" title="5 best practices for synthetic data use">IBM</a>)</li>
<li>Many organizations report cost savings, faster iteration cycles, and better model robustness by using synthetic data in augmentation pipelines. (<a href="https://www.netguru.com/blog/synthetic-data" title="Synthetic Data: Revolutionizing Modern AI Development in ...">Netguru</a>)</li>
<li>However, adoption is still emerging: many organizations are in pilot phases or proof-of-concept stages. (<a href="https://www.ibm.com/think/insights/streamline-accelerate-ai-initiatives-synthetic-data" title="5 best practices for synthetic data use">IBM</a>)</li>
</ul>
<h1>Challenges, Risks &amp; Best Practices</h1>
<h2>Key Risks &amp; Limitations</h2>
<ol>
<li>
<p><strong>Fidelity vs. realism trade-off</strong><br>
Synthetic datasets often approximate the “central manifold” of distributions and may underrepresent tails or extreme events, limiting generalizability. (<a href="https://www.rgnmed.com/post/beyond-the-hype-why-synthetic-data-falls-short-in-healthcare-and-how-regenmed-circles-closes-the-gap" title="Beyond the Hype: Why Synthetic Data Falls Short ...">rgnmed.com</a>)</p>
</li>
<li>
<p><strong>Model collapse / recursive degradation</strong><br>
If models are trained repeatedly on synthetic data generated by prior models (a form of recursion), performance can degrade over successive generations. This phenomenon is known as <strong>model collapse</strong>. (<a href="https://en.wikipedia.org/wiki/Model_collapse" title="Model collapse">Wikipedia</a>)</p>
</li>
<li>
<p><strong>Privacy leakage / inference attacks</strong><br>
Poor synthesis may allow adversaries to reconstruct or memorize real individuals, especially if overfitting occurs. Strong differential privacy or noise constraints are often required.</p>
</li>
<li>
<p><strong>Bias amplification &amp; fairness issues</strong><br>
Synthetic generators may propagate or amplify existing biases (e.g. underrepresented groups), leading to downstream discrimination. Techniques like fairness-aware generation are needed (e.g. Bt-GAN). (<a href="https://arxiv.org/abs/2404.13634" title="Bt-GAN: Generating Fair Synthetic Healthdata via Bias-transforming Generative Adversarial Networks">arXiv</a>)</p>
</li>
<li>
<p><strong>Validation and trustworthiness</strong><br>
Verifying that synthetic data is “safe” and “useful” is nontrivial. Standard metrics may not reveal subtle errors that hurt downstream performance.</p>
</li>
<li>
<p><strong>Distribution shift &amp; domain mismatch</strong><br>
Synthetic data might not reflect changes in real-world distributions (temporal drift, feature interactions), making models brittle in production.</p>
</li>
</ol>
<h2>Best Practices &amp; Guidelines</h2>
<p>Here are recommended practices to increase the success rate of synthetic data in production:</p>
<ul>
<li><strong>Hybrid training</strong>: Mix synthetic and real data rather than relying purely on synthetic. This balances realism and flexibility.</li>
<li><strong>Differential privacy / noise injection</strong>: Add controlled noise to ensure that synthetic outputs do not leak sensitive records.</li>
<li><strong>Diversity &amp; oversampling rare regions</strong>: Force generative models to pay attention to underrepresented regions (e.g. enforce sampling weights).</li>
<li><strong>Domain constraints / rules-based anchoring</strong>: Use domain knowledge to enforce invariants (e.g. monotonic relationships, constraints) in generation.</li>
<li><strong>Robust validation suite</strong>: Evaluate synthetic data with multiple metrics: distributional similarity (e.g. KL divergence, feature-wise distances), downstream model performance, outlier detection, and sanity checks for edge-case fidelity.</li>
<li><strong>Progressive scaling &amp; sanity checks</strong>: Start with small, controlled synthetic sets, validate, then expand.</li>
<li><strong>Governance, audit &amp; transparency</strong>: Maintain audit logs, metadata, and clear documentation (when synthetic data was used).</li>
<li><strong>Avoid deep recursion loops</strong>: Do not train new generators only on synthetic data without injecting fresh real data to avoid model collapse.</li>
<li><strong>Stress testing on boundary cases</strong>: Purposefully generate adversarial or corner-case synthetic samples to test model robustness.</li>
<li><strong>Continuous monitoring after deployment</strong>: Monitor for drift, anomalies, or degradation in model performance in real production data.</li>
</ul>
<p>IBM’s recommendations for synthetic data adoption emphasize many of these, noting that synthetic data is still under-adopted and organizations must build internal capability to validate and monitor utility. (<a href="https://www.ibm.com/think/insights/streamline-accelerate-ai-initiatives-synthetic-data" title="5 best practices for synthetic data use">IBM</a>)</p>
<h1>Sample Architecture: Synthetic Data Pipeline</h1>
<p>Below is a simplified pipeline architecture you might adopt.</p>
<pre><code class="language-txt">Raw / sensitive data  →  Preprocessing &amp; Feature Engineering  
    → Train generative model (GAN / diffusion / transformer)  
    → Synthetic dataset (with metadata, labels)  
    → Validation &amp; filtering  
         • Compare distribution against real  
         • Outlier / anomaly checks  
         • Privacy risk tests  
    → Hybrid dataset (real + synthetic)  
    → Model training / testing / validation  
    → Monitoring &amp; feedback loop  
</code></pre>
<p>Some pipelines integrate domain-checking modules or rules-based correction steps after generation to maintain consistency (e.g., enforce monotonicity, business rules). For temporal or time-series data, generative models may incorporate autoregressive or recurrent components to capture dynamics.</p>
<h1>Outlook &amp; Trends for 2025 and Beyond</h1>
<p>Here are some emerging trends and predictions:</p>
<ul>
<li><strong>Widespread integration of synthetic data in AI pipelines</strong>: As generative AI matures, synthetic data becomes a mainstream tool—not just for augmentation, but as a core component of model training. (<a href="https://arxiv.org/abs/2501.18493" title="Examining the Expanding Role of Synthetic Data Throughout the AI Development Pipeline">arXiv</a>)</li>
<li><strong>Transformer-based structured-data models</strong>: More LLM-like architectures fine-tuned to generate tabular, time-series, and mixed-type data natively.</li>
<li><strong>On-the-fly synthetic data generation</strong>: Real-time synthetic augmentation during model inference or retraining (e.g. live data drift compensation).</li>
<li><strong>Better privacy guarantees</strong>: Integration of rigorous differential privacy, federated synthetic generation, and cryptographic techniques to bound leakage.</li>
<li><strong>Self-supervised or self-refining synthetic pipelines</strong>: Generative models that improve via closed-loop feedback from downstream tasks.</li>
<li><strong>Domain-specific synthetic platforms</strong>: Vertical solutions (finance, life sciences, IoT) offering synthetic generation tuned for domain constraints.</li>
<li><strong>Hybrid generative / refinement approaches</strong>: For example, Generative Data Refinement (GDR) methods that &quot;clean&quot; mixed or untrusted data rather than fully synthetic approaches. (A new direction emerging in 2025) (<a href="https://www.businessinsider.com/google-deepmind-ai-training-data-shortage-researchers-harmful-2025-9" title="A key type of AI training data is running out. Googlers have a bold new idea to fix that.">Business Insider</a>)</li>
<li><strong>Guardrails and regulation</strong>: As synthetic data use proliferates, regulatory and auditing frameworks will evolve to ensure accountability, fairness, and privacy compliance.</li>
</ul>
<h1>Sample Starter Code Sketch (Python / PyTorch pseudocode)</h1>
<p>Below is a rough sketch showing how one might build a simple GAN-based synthetic tabular generator. (This is illustrative—not production-ready.)</p>
<pre><code class="language-python">import torch
import torch.nn as nn
import torch.optim as optim

class Generator(nn.Module):
    def __init__(self, latent_dim, output_dim):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(latent_dim, 128),
            nn.ReLU(),
            nn.Linear(128, 256),
            nn.ReLU(),
            nn.Linear(256, output_dim),
        )
    def forward(self, z):
        return self.net(z)

class Discriminator(nn.Module):
    def __init__(self, input_dim):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(input_dim, 256),
            nn.LeakyReLU(0.2),
            nn.Linear(256, 128),
            nn.LeakyReLU(0.2),
            nn.Linear(128, 1),
            nn.Sigmoid(),
        )
    def forward(self, x):
        return self.net(x)

def train_gan(real_data, latent_dim=32, epochs=1000, batch_size=128):
    gen = Generator(latent_dim, real_data.shape[1])
    dis = Discriminator(real_data.shape[1])
    opt_g = optim.Adam(gen.parameters(), lr=1e-4)
    opt_d = optim.Adam(dis.parameters(), lr=1e-4)
    criterion = nn.BCELoss()
    for epoch in range(epochs):
        # sample real batch
        idx = torch.randperm(real_data.size(0))[:batch_size]
        real_batch = real_data[idx]
        # train discriminator
        z = torch.randn(batch_size, latent_dim)
        fake = gen(z).detach()
        d_real = dis(real_batch)
        d_fake = dis(fake)
        loss_d = criterion(d_real, torch.ones_like(d_real)) + criterion(d_fake, torch.zeros_like(d_fake))
        opt_d.zero_grad()
        loss_d.backward()
        opt_d.step()
        # train generator
        z2 = torch.randn(batch_size, latent_dim)
        fake2 = gen(z2)
        d_fake2 = dis(fake2)
        loss_g = criterion(d_fake2, torch.ones_like(d_fake2))
        opt_g.zero_grad()
        loss_g.backward()
        opt_g.step()
        if epoch % 100 == 0:
            print(f&quot;Epoch {epoch}, loss_d {loss_d.item():.4f}, loss_g {loss_g.item():.4f}&quot;)
    return gen
</code></pre>
<p>You would extend this with:</p>
<ul>
<li><strong>Conditional generation</strong> (so you can generate based on labels or categories)</li>
<li><strong>Post-processing &amp; clipping / rounding</strong> (to match feature domain)</li>
<li><strong>Privacy noise injection</strong></li>
<li><strong>Validation and rejection sampling</strong></li>
</ul>
<h1>Conclusion</h1>
<p>Generative AI–driven synthetic data is rapidly maturing into a core tool in the data scientist’s toolbox. With the right architecture, safeguards, and validation practices, synthetic data enables:</p>
<ul>
<li>Privacy-preserving model development</li>
<li>Rich augmentation for rare events</li>
<li>Safer data sharing</li>
<li>Faster experimentation</li>
</ul>
<p>But the hurdles remain: fidelity, bias, model collapse, and validation must be actively managed. As the field evolves in 2025, expect to see:</p>
<ul>
<li>more robust domain-specific synthetic data platforms</li>
<li>generative models that seamlessly produce structured, multimodal, temporal data</li>
<li>better regulatory frameworks and audit tools</li>
</ul>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Vibe Coding - Great for Founders, Risky for Future Pros]]></title>
            <link>https://gopalverma.com/diary/blogs/vibe-coding</link>
            <guid>https://gopalverma.com/diary/blogs/vibe-coding</guid>
            <pubDate>Wed, 14 May 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Vibe coding empowers indie developers and founders with rapid prototyping and efficiency, but relying on it can hinder the deep technical understanding crucial for becoming an expert-level coder focused on robust and scalable applications.]]></description>
            <content:encoded><![CDATA[<p>The software development landscape is continually evolving, with new methodologies and tools emerging to streamline the creation of digital products. Among the latest trends is the rise of AI-assisted coding, a paradigm shift that has given birth to concepts like &quot;vibe coding&quot;. This approach promises to democratize software development, allowing individuals with limited technical expertise to bring their ideas to life more rapidly than ever before.</p>
<h1>Decoding the &quot;Vibe&quot;: What Exactly is Vibe Coding?</h1>
<p>The term &quot;vibe coding&quot; gained prominence in February 2025 when renowned computer scientist <a href="https://karpathy.ai/">Andrej Karpathy</a> described it as a new kind of coding where one &quot;fully give[s] in to the vibes, embrace[s] exponentials, and forget[s] that the code even exists&quot;. This concept, aligned with advancements in artificial intelligence, particularly large language models (LLMs), refers to the practice of using natural language prompts to instruct AI agents to write code.</p>
<p>Here's a simple example to illustrate the difference:</p>
<p><strong>Traditional Coding:</strong></p>
<pre><code class="language-javascript">function calculateFibonacci(n) {
  if (n &lt;= 1) return n;
  let a = 0, b = 1;
  for (let i = 2; i &lt;= n; i++) {
    const temp = a + b;
    a = b;
    b = temp;
  }
  return b;
}
</code></pre>
<p><strong>Vibe Coding Prompt:</strong></p>
<pre><code class="language-txt">&quot;Write a function that calculates the nth Fibonacci number efficiently&quot;
</code></pre>
<blockquote>
<p>&quot;I just see stuff, say stuff, run stuff, and copy paste stuff, and it mostly works&quot; - <em>Andrej Karpathy</em></p>
</blockquote>
<p>Instead of developers manually writing every line of code, they describe the desired functionality or problem they aim to solve in plain language, allowing the AI to handle the technical implementation. This signifies a fundamental shift in the programmer's role, moving from the detailed work of manual coding to the higher-level tasks of guiding, testing, and refining the code generated by AI.</p>
<h1>The Indie Advantage: Why Vibe Coding Resonates with Founders and Small Teams</h1>
<p>For indie developers and startup founders, who often operate with limited resources and tight deadlines, vibe coding presents a compelling set of advantages. The ability to rapidly translate ideas into functional prototypes can be a game-changer in the fast-paced world of technology.</p>
<h2>1. Speed and Efficiency</h2>
<p>The most significant benefit of vibe coding is the speed and efficiency it offers. This approach allows for near-instant prototyping and accelerates the overall development and launch process. Indie developers can go from a concept to a working demo or a minimum viable product (MVP) in a significantly shorter timeframe compared to traditional coding methods.</p>
<p>Here's an example of creating a simple API endpoint:</p>
<p><strong>Traditional Coding:</strong></p>
<pre><code class="language-javascript">const express = require('express');
const app = express();

app.use(express.json());

app.post('/api/users', async (req, res) =&gt; {
  try {
    const { name, email } = req.body;
    const user = await User.create({ name, email });
    res.status(201).json(user);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () =&gt; {
  console.log('Server running on port 3000');
});
</code></pre>
<p><strong>Vibe Coding Prompt:</strong></p>
<pre><code class="language-txt">&quot;Create an Express.js API endpoint that handles user creation with name and email&quot;
</code></pre>
<h2>2. Lower Barrier to Entry</h2>
<p>Vibe coding democratizes software development by making it considerably easier for individuals who may not possess a traditional technical background. This empowers entrepreneurs, designers, and experts from various fields to bring their software ideas to fruition without requiring extensive coding knowledge or the immediate need to hire a team of developers. This democratization can lead to a surge of innovation as individuals with unique domain expertise can now directly participate in creating software solutions tailored to their specific needs and problems.</p>
<h2>3. Focus on Creativity</h2>
<p>By handling much of the underlying technical implementation, AI tools free up valuable time and energy, enabling creators to concentrate on the creative aspects of app development, such as user experience, functionality, and overall vision. This shift in focus allows founders to act more like product managers or directors, guiding the AI to build the application according to their desired outcomes, rather than getting bogged down in the intricacies of syntax and debugging. This can lead to a better alignment between the final product and the initial vision, ultimately resulting in a more user-centric application.</p>
<h2>4. Automation of Mundane Tasks</h2>
<p>Vibe coding tools can automate many of the mundane and repetitive aspects of programming, such as setting up basic files, handling simple data tasks, and writing standard code patterns. This automation allows developers to dedicate more of their time and mental energy to the more complex, challenging, and ultimately more rewarding aspects of software development, such as designing intricate features, solving unique problems, and enhancing the user experience.</p>
<h2>5. Rapid Prototyping</h2>
<p>Vibe coding is inherently suited for rapid prototyping and validation. It enables the swift creation of early versions of apps, also known as prototypes or MVPs, which can be used to test ideas and gather feedback from potential users. This iterative approach allows for faster validation of concepts and reduces the risk of investing significant time and resources into ideas that may not resonate with the target audience. Early feedback loops enable founders to make necessary adjustments and ensure that the final product is more likely to meet market demands.</p>
<p>The following table summarizes the key advantages of vibe coding for indie developers and founders:</p>
<table>
<thead>
<tr>
<th>Advantage</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Speed and Efficiency</td>
<td>Faster development cycles, quicker time to market for MVPs.</td>
</tr>
<tr>
<td>Lower Barrier to Entry</td>
<td>Enables individuals without deep technical skills to create software.</td>
</tr>
<tr>
<td>Focus on Creativity</td>
<td>Allows founders to concentrate on product vision and user experience.</td>
</tr>
<tr>
<td>Automation of Mundane Tasks</td>
<td>Frees up developers from repetitive coding tasks.</td>
</tr>
<tr>
<td>Rapid Prototyping</td>
<td>Facilitates quick validation of ideas and iterative development.</td>
</tr>
</tbody>
</table>
<h1>The Pitfalls for the Pro: When Vibe Coding Hinders the Journey to Mastery</h1>
<p>While vibe coding offers significant benefits for certain developer profiles, it also presents potential drawbacks, especially for those who aspire to become highly skilled and expert-level coders or developers.</p>
<h2>1. Code Quality and Performance Issues</h2>
<p>AI-generated code may not always adhere to best practices or generate the most efficient solutions. The generated code might require significant optimization and refinement to ensure acceptable performance and scalability, particularly for complex applications.</p>
<p>Here's an example of a database query optimization:</p>
<p><strong>AI-Generated Code (Potentially Inefficient):</strong></p>
<pre><code class="language-javascript">async function getUsersWithPosts() {
  const users = await User.findAll();
  const usersWithPosts = [];
  
  for (const user of users) {
    const posts = await Post.findAll({ where: { userId: user.id } });
    usersWithPosts.push({ ...user, posts });
  }
  
  return usersWithPosts;
}
</code></pre>
<p><strong>Optimized Version:</strong></p>
<pre><code class="language-javascript">async function getUsersWithPosts() {
  return await User.findAll({
    include: [{
      model: Post,
      required: false
    }],
    attributes: ['id', 'name', 'email']
  });
}
</code></pre>
<h2>2. Debugging Challenges</h2>
<p>Code generated by AI can be dynamic and may lack a clear architectural structure, making it difficult to trace errors and understand the underlying logic. If a developer does not fully comprehend how the AI-generated code functions, the process of identifying and fixing bugs can become significantly more complex and time-consuming. Even Karpathy himself acknowledged that AI tools are not always capable of understanding or fixing bugs effectively, sometimes necessitating trial-and-error approaches. Aspiring expert developers need to cultivate strong debugging skills, which are honed through understanding the intricacies of code and systematically identifying and resolving issues.</p>
<h2>3. Security Risks</h2>
<p>AI-generated code might inadvertently contain security vulnerabilities if the developer lacks the expertise to identify and address them. Blindly trusting AI suggestions without a thorough understanding of security principles and best practices can lead to the introduction of security gaps that could be exploited. A deep understanding of security is paramount for any professional developer.</p>
<h1>Vibe Coding vs. Traditional Development: A Tale of Two Priorities</h1>
<p>Vibe coding and traditional software development methodologies represent distinct approaches with different priorities and trade-offs. Vibe coding places a strong emphasis on speed and rapid prototyping, allowing for quick iteration and validation of ideas. In contrast, traditional development often prioritizes a deeper understanding of the codebase and underlying principles, aiming for greater control and maintainability. Vibe coding operates at a higher level of abstraction, utilizing natural language prompts to instruct AI, whereas traditional development involves granular control over every aspect of the code. This makes vibe coding more accessible to individuals without extensive technical training, while traditional development demands significant technical expertise.</p>
<p>When using vibe coding for initial prototypes, developers might accept a higher level of risk regarding code quality and long-term maintainability. However, professional development for critical applications typically prioritizes robustness and reliability. The development lifecycle in vibe coding often aligns with rapid prototyping and iterative development, while traditional methods may follow more structured approaches like <strong>Waterfall</strong> or <strong>Agile</strong> with a strong emphasis on planning and documentation. Ultimately, the choice between these approaches depends on the specific goals of the project, the developer's skill level, and the long-term vision for the software.</p>
<h1>The Shadow of Technical Debt: Navigating the Risks of Rapid AI-Generated Code</h1>
<p>The rapid generation of code facilitated by vibe coding, while offering immediate benefits, carries the inherent risk of accumulating technical debt. Technical debt, in software development, refers to the future consequences of prioritizing speed of delivery over achieving an optimal solution. Essentially, shortcuts taken during the development process to meet deadlines or simplify implementation can lead to additional work and higher costs in the future.</p>
<p>In the context of vibe coding, technical debt can accrue through several avenues. Developers might hastily accept AI-generated code without conducting thorough reviews or fully understanding its implications. This lack of comprehension can make future modifications and debugging significantly more challenging. Furthermore, AI-generated code might exhibit inconsistent coding styles or fail to adhere to established best practices, contributing to a less maintainable codebase. Insufficient testing of AI-generated code can also lead to the accumulation of technical debt, as undetected bugs and vulnerabilities may persist within the application.</p>
<p>The consequences of unchecked technical debt can be substantial. It often leads to increased maintenance costs and longer development times as developers spend more time addressing issues arising from the initial shortcuts. The quality of service can suffer, with a higher likelihood of software malfunctions and system failures. Technical debt can also hinder the ability to scale the application to accommodate growing user bases or new features. As developers become increasingly occupied with fixing existing problems, the capacity for innovation diminishes. Poorly managed technical debt can also introduce security vulnerabilities, making the application more susceptible to attacks. At a higher level, it can lead to unreliable project plans and erode customer trust, ultimately decreasing code quality and increasing the frequency of bugs. The burden of working with a debt-ridden codebase can even impact a team's ability to attract and retain talented developers. While vibe coding can offer an initial burst of speed, neglecting the resulting technical debt can create significant obstacles in the long run, potentially undermining the initial advantages and even leading to project failure.</p>
<h1>Building a Solid Foundation: Why Core Coding Skills Remain Essential for Aspiring Experts</h1>
<p>For developers with aspirations of achieving mastery in their field and building robust, scalable applications, a strong foundation in core coding skills remains indispensable, even in the age of AI-assisted development. This foundational knowledge encompasses areas such as software architecture, design patterns, coding standards, and thorough testing methodologies.</p>
<p>A deep understanding of software architecture is essential for designing systems that are not only functional but also scalable, maintainable, and reliable. Software architecture provides the high-level blueprint for the software, defining its components and their interactions. It involves comprehending various architectural patterns and their associated trade-offs. This knowledge allows developers to make informed decisions about the structure of their applications, ensuring they can adapt to future growth and complexity, a critical aspect that a purely vibe-driven approach might overlook. Without a solid grasp of architectural principles, developers risk creating systems that are difficult to evolve or manage effectively.</p>
<p>The importance of design patterns cannot be overstated. Design patterns are reusable solutions to commonly occurring problems in software design. They improve code reusability, enhance maintainability and scalability, promote consistency and best practices, and facilitate communication among developers. Design patterns represent the collective experience of the software engineering community, offering proven approaches to common challenges. Understanding and applying these patterns leads to more robust and well-structured code, a hallmark of professional development. Relying solely on AI for code generation might result in solutions that do not leverage these established patterns, potentially leading to less efficient or harder-to-understand code.</p>
<p>Adherence to coding standards is another crucial element of professional software development. Coding standards ensure that code is consistent and of high quality, improving readability and maintainability. They facilitate team collaboration and reduce the likelihood of errors. While AI might generate syntactically correct code, it may not always conform to the specific coding standards of a project or team. A deep understanding of coding standards allows developers to ensure consistency and clarity in their codebase.</p>
<p>Finally, the necessity of thorough testing is paramount for aspiring expert developers. This includes various types of testing, such as unit tests, integration tests, and end-to-end tests, which are essential for ensuring that the code functions as expected and for preventing regressions. Relying solely on AI-generated code without rigorous testing can lead to unstable and unreliable applications. A strong understanding of testing methodologies and the ability to write effective tests are fundamental skills for any developer aiming for expertise.</p>
<h1>Finding the Right Rhythm: A Balanced Approach to Vibe Coding</h1>
<p>For indie developers and founders, vibe coding can be a valuable tool when used strategically and with an awareness of its limitations. Here's how to make the most of it:</p>
<h2>1. Best Practices</h2>
<ul>
<li>Use vibe coding for rapid prototyping and initial idea validation</li>
<li>Always focus on understanding the generated code</li>
<li>Implement proper testing for all AI-generated code</li>
<li>Refactor AI-generated code to maintain coding standards</li>
<li>Invest in foundational learning of core programming concepts</li>
</ul>
<p>Here's an example of proper testing implementation:</p>
<p><strong>AI-Generated Component:</strong></p>
<pre><code class="language-javascript">function UserProfile({ user }) {
  return (
    &lt;div&gt;
      &lt;h1&gt;{user.name}&lt;/h1&gt;
      &lt;p&gt;{user.email}&lt;/p&gt;
      &lt;button onClick={() =&gt; user.logout()}&gt;Logout&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p><strong>Proper Testing Implementation:</strong></p>
<pre><code class="language-javascript">import { render, screen, fireEvent } from '@testing-library/react';

describe('UserProfile', () =&gt; {
  const mockUser = {
    name: 'John Doe',
    email: 'john@example.com',
    logout: jest.fn()
  };

  test('renders user information correctly', () =&gt; {
    render(&lt;UserProfile user={mockUser} /&gt;);
    expect(screen.getByText('John Doe')).toBeInTheDocument();
    expect(screen.getByText('john@example.com')).toBeInTheDocument();
  });

  test('calls logout function when button is clicked', () =&gt; {
    render(&lt;UserProfile user={mockUser} /&gt;);
    fireEvent.click(screen.getByText('Logout'));
    expect(mockUser.logout).toHaveBeenCalled();
  });
});
</code></pre>
<h2>2. For Expert Developers</h2>
<ul>
<li>Maintain a strong foundation in software architecture and design patterns</li>
<li>Use version control diligently to track all changes</li>
<li>Seek peer review for critical components</li>
<li>Be mindful of technical debt and continuously refactor</li>
</ul>
<h1>Conclusion</h1>
<p>Vibe coding represents an exciting evolution in software development, offering a powerful set of tools for indie developers and founders seeking to rapidly prototype and bring their ideas to life. Its ability to lower the barrier to entry and accelerate development cycles makes it a compelling option for individuals and small teams operating with limited resources.</p>
<p>However, for those who aspire to become expert-level coders or developers, relying solely on vibe coding carries significant risks. A deep understanding of core programming principles, software architecture, design patterns, coding standards, and rigorous testing methodologies remains essential for achieving mastery and building robust, scalable applications.</p>
<p>The most successful developers in the future will likely be those who can strategically integrate AI-assisted tools like vibe coding into their workflow while maintaining a strong foundation in traditional software development practices. As AI continues to reshape the software development landscape, a balanced approach that embraces innovation while upholding fundamental principles will be key to achieving excellence in the craft.</p>
<h1>References</h1>
<ol>
<li><a href="https://azumo.com/project-outsourcing-handbook/version-control-and-code-quality-in-development">Version Control and Code Quality in Development</a></li>
<li><a href="https://www.smashingmagazine.com/2023/05/impact-agile-methodologies-code-quality/">Impact of Agile Methodologies on Code Quality</a></li>
<li><a href="https://blog.replit.com/what-is-vibe-coding">What is Vibe Coding?</a></li>
<li><a href="https://devops.com/does-using-ai-assistants-lead-to-lower-code-quality/">Does Using AI Assistants Lead to Lower Code Quality?</a></li>
<li><a href="https://leaddev.com/software-quality/how-ai-generated-code-accelerates-technical-debt">How AI-Generated Code Accelerates Technical Debt</a></li>
<li><a href="https://www.reddit.com/r/SoftwareEngineering/comments/1kjwiso/maintaining_code_quality_with_widespread_ai/">Maintaining Code Quality with Widespread AI</a></li>
<li><a href="https://en.wikipedia.org/wiki/Vibe_coding">Vibe Coding - Wikipedia</a></li>
<li><a href="https://cloudsecurityalliance.org/blog/2025/04/09/secure-vibe-coding-guide">Secure Vibe Coding Guide</a></li>
<li><a href="https://www.reddit.com/r/AskProgramming/comments/1jfia88/does_ai_actually_improve_code_quality_or_just/">Does AI Actually Improve Code Quality?</a></li>
<li><a href="https://www.thoughtworks.com/radar/techniques/complacency-with-ai-generated-code">Complacency with AI-Generated Code</a></li>
<li><a href="https://blog.bonfy.ai/code-review-in-the-age-of-ai-best-practices-for-reviewing-ai-generated-code">Code Review in the Age of AI</a></li>
<li><a href="https://www.leanware.co/insights/best-practices-ai-software-development">Best Practices for AI in Software Development</a></li>
<li><a href="https://zencoder.ai/blog/how-to-use-ai-in-coding">How to Use AI in Coding</a></li>
<li><a href="https://www.reddit.com/r/ChatGPTCoding/comments/1fyti60/8_best_practices_to_generate_code_with_generative/">8 Best Practices to Generate Code with Generative AI</a></li>
<li><a href="https://www.reddit.com/r/AskProgramming/comments/1jtoyso/how_do_you_validate_aigenerated_code_in/">How to Validate AI-Generated Code</a></li>
<li><a href="https://blog.codacy.com/best-practices-for-coding-with-ai">Best Practices for Coding with AI</a></li>
<li><a href="https://stackoverflow.blog/2024/09/10/gen-ai-llm-create-test-developers-coding-software-code-quality/">Gen AI and Code Quality</a></li>
<li><a href="https://securetrust.io/blog/secure-ai-generated-code/">Secure AI-Generated Code</a></li>
<li><a href="https://www.readysetcloud.io/blog/allen.helton/tdd-with-ai/">TDD with AI</a></li>
<li><a href="https://www.sonarsource.com/blog/ai-code-assurance-sonar/">AI Code Assurance</a></li>
<li><a href="https://dev.to/volkmarr/is-generated-code-harder-to-maintain-1n1n">Is Generated Code Harder to Maintain?</a></li>
<li><a href="https://invozone.com/blog/ai-generated-code-maintenance-challenges/">AI-Generated Code Maintenance Challenges</a></li>
<li><a href="https://www.stauffer.com/news/blog/the-impact-of-ai-in-the-software-development-lifecycle">Impact of AI in Software Development Lifecycle</a></li>
<li><a href="https://www.mckinsey.com/industries/technology-media-and-telecommunications/our-insights/how-an-ai-enabled-software-product-development-life-cycle-will-fuel-innovation">AI-Enabled Software Product Development</a></li>
<li><a href="https://www.developer-tech.com/news/ai-impact-on-software-development-jobs/">AI Impact on Software Development Jobs</a></li>
<li><a href="https://www.ibm.com/think/topics/ai-in-software-development">AI in Software Development</a></li>
<li><a href="https://ieeechicago.org/the-impact-of-ai-and-automation-on-software-development-a-deep-dive/">Impact of AI and Automation on Software Development</a></li>
<li><a href="https://brainhub.eu/library/software-developer-age-of-ai">Software Developer in the Age of AI</a></li>
<li><a href="https://www.reddit.com/r/Futurology/comments/1jc6r40/will_ai_really_eliminate_software_developers/">Will AI Really Eliminate Software Developers?</a></li>
<li><a href="https://www.brookings.edu/articles/how-ai-powered-software-development-may-affect-labor-markets/">AI-Powered Software Development and Labor Markets</a></li>
<li><a href="https://www.reddit.com/r/ExperiencedDevs/comments/1hm8gxj/ai_wont_replace_software_engineers_but_an/">AI Won't Replace Software Engineers</a></li>
<li><a href="https://www.forbes.com/councils/forbestechcouncil/2025/04/04/the-future-of-code-how-ai-is-transforming-software-development/">The Future of Code: How AI is Transforming Software Development</a></li>
<li><a href="https://www.pluralsight.com/resources/blog/business-and-leadership/AI-in-software-development">AI in Software Development</a></li>
<li><a href="https://www.deloitte.com/uk/en/Industries/technology/blogs/2024/the-future-of-coding-is-here-how-ai-is-reshaping-software-development.html">The Future of Coding: How AI is Reshaping Software Development</a></li>
<li><a href="https://onlinecs.baylor.edu/news/will-ai-replace-SWEs">Will AI Replace Software Engineers?</a></li>
<li><a href="https://www.whitesmith.co/blog/evolution-of-programming-skills/">The Evolution of Programming Skills</a></li>
<li><a href="https://dev.to/bikashdaga/ai-and-the-evolution-of-coding-will-ai-tools-replace-programmers-13af">AI and the Evolution of Coding</a></li>
<li><a href="https://www.mixmax.com/engineering/the-evolution-of-coding">The Evolution of Coding</a></li>
<li><a href="https://www.oreilly.com/radar/ai-and-programming-the-beginning-of-a-new-era/">AI and Programming: The Beginning of a New Era</a></li>
<li><a href="https://kvytechnology.com/blog/software/ai-in-software-development/">AI in Software Development</a></li>
<li><a href="https://dzone.com/articles/from-algorithms-to-ai-the-evolution-of-programming">From Algorithms to AI: The Evolution of Programming</a></li>
<li><a href="https://www.signalfire.com/blog/ai-evolution-of-coding">AI: Evolution of Coding</a></li>
<li><a href="https://thebootstrappedfounder.com/the-evolution-of-coding-in-the-ai-era/">The Evolution of Coding in the AI Era</a></li>
<li><a href="https://www.atlassian.com/agile/software-development/code-reviews">Code Reviews in Agile Software Development</a></li>
</ol>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Clean my Mac]]></title>
            <link>https://gopalverma.com/diary/notes/clean-my-mac</link>
            <guid>https://gopalverma.com/diary/notes/clean-my-mac</guid>
            <pubDate>Mon, 28 Oct 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Notes for how to clean system junks on Mac]]></description>
            <content:encoded><![CDATA[<p>These notes provide a quick guide on how to clean system junk files on your Mac.</p>
<h1>Why clean your Mac?</h1>
<p>Regular system cleaning helps:</p>
<ul>
<li>Improve your Mac's performance</li>
<li>Free up valuable storage space</li>
<li>Remove unnecessary files and applications</li>
<li>Maintain system stability</li>
</ul>
<h1>Common areas to clean</h1>
<ol>
<li>User Cache Files</li>
<li>System Log Files</li>
<li>Language Files</li>
<li>User Log Files</li>
<li>Broken Login Items</li>
<li>System Cache Files</li>
</ol>
<h2>1. User Cache Files</h2>
<ul>
<li>
<p><strong>Why</strong>: Created to speed up apps and processes by storing frequently accessed data.</p>
</li>
<li>
<p><strong>Made of</strong>: Temporary app data, browser caches, preview thumbnails, and downloaded app components.</p>
</li>
<li>
<p><strong>Stored in</strong>: <code>/Library/Caches</code> and <code>/Library/Caches</code></p>
</li>
<li>
<p><strong>Clear Command</strong>:</p>
<pre><code class="language-bash">rm -rf ~/Library/Caches/* &amp;&amp; sudo rm -rf /Library/Caches/*
</code></pre>
</li>
</ul>
<h2>2. System Log Files</h2>
<ul>
<li>
<p><strong>Why</strong>: Created to track system events, errors, and activities for troubleshooting.</p>
</li>
<li>
<p><strong>Made of</strong>: System reports, crash logs, diagnostic reports, and installation logs.</p>
</li>
<li>
<p><strong>Stored in</strong>: <code>/var/log</code> and <code>~/Library/Logs</code></p>
</li>
<li>
<p><strong>Clear Command</strong>:</p>
<pre><code class="language-bash">sudo rm -rf /var/log/* &amp;&amp; rm -rf ~/Library/Logs/*
</code></pre>
</li>
</ul>
<h2>3. Language Files</h2>
<ul>
<li>
<p><strong>Why</strong>: Stored to support multiple language interfaces in applications.</p>
</li>
<li>
<p><strong>Made of</strong>: Localization files (.lproj folders) for unused languages.</p>
</li>
<li>
<p><strong>Stored in</strong>: <code>/Applications/[AppName]/Contents/Resources</code></p>
</li>
<li>
<p><strong>Clear command</strong>:</p>
<pre><code class="language-bash">find /Applications -name &quot;*.lproj&quot; -type d ! -name &quot;en.lproj&quot; ! -name &quot;Base.lproj&quot; -exec rm -rf {} \;
</code></pre>
</li>
</ul>
<h2>4. User Log Files</h2>
<ul>
<li>
<p><strong>Why</strong>: Created to track user-specific application activities and errors.</p>
</li>
<li>
<p><strong>Made of</strong>: App-specific logs, crash reports, and usage data.</p>
</li>
<li>
<p><strong>Stored in</strong>: <code>~/Library/Logs</code> and <code>~/Library/Application Support</code></p>
</li>
<li>
<p><strong>Clear command</strong>:</p>
<pre><code class="language-bash">rm -rf ~/Library/Logs/* &amp;&amp; rm -rf ~/Library/Application\ Support/*/logs/*
</code></pre>
</li>
</ul>
<h2>5. Broken Login Items</h2>
<ul>
<li>
<p><strong>Why</strong>: Remnants of uninstalled applications that were set to launch at startup.</p>
</li>
<li>
<p><strong>Made of</strong>: Launch agents, daemons, and login item references.</p>
</li>
<li>
<p><strong>Stored in</strong>: <code>~/Library/LaunchAgents</code> and <code>/Library/LaunchAgents</code></p>
</li>
<li>
<p><strong>Clear command</strong>:</p>
<pre><code class="language-bash">rm -rf ~/Library/LaunchAgents/* &amp;&amp; sudo rm -rf /Library/LaunchAgents/*
</code></pre>
</li>
</ul>
<h2>6. System Cache Files</h2>
<ul>
<li>
<p><strong>Why</strong>: Created by macOS to improve system performance and app loading times.</p>
</li>
<li>
<p><strong>Made of</strong>: System-level caches, kernel caches, and framework caches.</p>
</li>
<li>
<p><strong>Stored in</strong>: <code>/System/Library/Caches</code> and <code>/Library/Caches</code></p>
</li>
<li>
<p><strong>Clear command</strong>:</p>
<pre><code class="language-bash">sudo rm -rf /System/Library/Caches/* &amp;&amp; sudo rm -rf /Library/Caches/*
</code></pre>
</li>
</ul>
<h1>Important Notes</h1>
<ul>
<li>Always backup your data before running these commands</li>
<li>Some of these commands require administrator privileges (sudo)</li>
<li>Some system caches will be regenerated automatically after deletion</li>
<li>Be careful with these commands as they can affect system performance if not used properly</li>
<li>You can manually delete files by navigating to their respective storage locations using Finder (⌘ + Shift + G to enter the path)</li>
</ul>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[N accounts on 1 machine]]></title>
            <link>https://gopalverma.com/diary/notes/n-accounts-on-1-machine</link>
            <guid>https://gopalverma.com/diary/notes/n-accounts-on-1-machine</guid>
            <pubDate>Thu, 10 Oct 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[How to work with multiple GitHub accounts on a single machine.]]></description>
            <content:encoded><![CDATA[<p>If you have two GitHub accounts, such as <strong><a href="http://github.com/gopx-office">github.com/gopx-office</a></strong> and <strong><a href="http://github.com/gopx-personal">github.com/gopx-personal</a></strong>, you can easily manage both on the same machine.</p>
<blockquote>
<p>Tip: This method works for more than two accounts as well!</p>
</blockquote>
<h1>Steps to follow</h1>
<ol>
<li>Generate SSH keys for each account</li>
<li>Add SSH keys to the SSH agent</li>
<li>Add SSH keys to GitHub</li>
<li>Create an SSH config file with host entries</li>
<li>Clone repositories using the correct account</li>
</ol>
<h1>1. Generate SSH Keys</h1>
<p>Navigate to your <code>.ssh</code> directory:</p>
<pre><code class="language-bash">cd ~/.ssh
</code></pre>
<p>Generate SSH keys for each account:</p>
<pre><code class="language-bash">ssh-keygen -t rsa -C &quot;office-email@gmail.com&quot; -f &quot;github-gopx-office&quot;
ssh-keygen -t rsa -C &quot;personal-email@gmail.com&quot; -f &quot;github-gopx-personal&quot;
</code></pre>
<p>After entering the command the terminal will ask for passphrase, leave it empty and proceed.</p>
<pre><code class="language-bash">Generating public/private rsa key pair.
Enter file in which to save the key (/Users/username/.ssh/github-gopx-office): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/username/.ssh/github-gopx-office.
Your public key has been saved in /Users/username/.ssh/github-gopx-office.pub.
The key fingerprint is:
SHA256:XXXXXXXXXXXXXX your-office-email@gmail.com
The key's randomart image is:
+---[RSA 2048]----+
|       ...       |
|      .o .       |
|      o. .       |
|     ... ..      |
|      ... .      |
|     ...  .      |
|    .o..   .     |
|   ..o    ..     |
+----[SHA256]-----+
</code></pre>
<p>After generating the keys, your <code>.ssh</code> folder will contain both the public key <code>github-gopx-office.pub</code> and the private key <code>github-gopx-office</code>. The public key has a <code>.pub</code> extension, while the private key does not.</p>
<h1>2. Add SSH Keys to the Agent</h1>
<p>Add your SSH keys to the SSH agent:</p>
<pre><code class="language-bash">ssh-add -K ~/.ssh/github-gopx-office
ssh-add -K ~/.ssh/github-gopx-personal
</code></pre>
<p>Learn more about adding keys to the SSH agent, check out - <a href="https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent">Generating a new SSH key and adding it to the ssh-agent</a>.</p>
<h1>3. Add SSH Keys to GitHub</h1>
<p>Copy and add your public keys to GitHub. For doing this we need to:</p>
<h2>1. Copy the public key</h2>
<p>We can copy the public key either by opening the github-gopx-office.pub file in vim and then copying the content of it.</p>
<pre><code class="language-bash">vim ~/.ssh/github-gopx-office.pub
vim ~/.ssh/github-gopx-personal.pub
</code></pre>
<p><strong>OR</strong></p>
<p>We can directly copy the content of the public key file in the clipboard.</p>
<pre><code class="language-bash">pbcopy &lt; ~/.ssh/github-gopx-office.pub
pbcopy &lt; ~/.ssh/github-gopx-personal.pub
</code></pre>
<h2>2. Paste the public key on GitHub</h2>
<ol>
<li>Sign in to GitHub Account</li>
<li>Goto <strong>Settings</strong> &gt; <strong>SSH and GPG keys</strong> &gt; <strong>New SSH Key</strong></li>
<li>Paste your copied public key and give it a Title of your choice</li>
</ol>
<p><strong>OR</strong></p>
<ol>
<li>Sign in to GitHub</li>
<li>Paste this link in your browser <a href="https://github.com/settings/keys">https://github.com/settings/keys</a></li>
<li>Click on New SSH Key and paste your copied key</li>
</ol>
<h1>4. Configure SSH for Multiple Accounts</h1>
<p>Create or open the SSH config file:</p>
<pre><code class="language-bash">touch ~/.ssh/config
open ~/.ssh/config
</code></pre>
<p>Add the following configurations:</p>
<pre><code class="language-bash"># Office account
Host github.com-gopx-office
    HostName github.com
    User git
    IdentityFile ~/.ssh/github-gopx-office

# Personal account
Host github.com-gopx-personal
    HostName github.com
    User git
    IdentityFile ~/.ssh/github-gopx-personal
</code></pre>
<h1>5. Clone Repositories</h1>
<p>To clone repositories, use the correct SSH host for the respective account:</p>
<pre><code class="language-bash">git clone git@github.com-gopx-personal:{owner}/{repo}.git
git clone git@github.com-gopx-office:{owner}/{repo}.git
</code></pre>
<h1>Final Configuration</h1>
<p>For each repository, set the appropriate user information:</p>
<pre><code class="language-bash">git config user.email &quot;office-email@gmail.com&quot;
git config user.name &quot;Gopx Office&quot;
</code></pre>
<p>Repeat for the personal account:</p>
<pre><code class="language-bash">git config user.email &quot;personal-email@gmail.com&quot;
git config user.name &quot;Gopx Personal&quot;
</code></pre>
<p>To ensure proper push/pull commands, set the remote origin:</p>
<pre><code class="language-bash">git remote add origin git@github.com-gopx-personal:gopx-personal/repo.git
git remote add origin git@github.com-gopx-office:gopx-office/repo.git
</code></pre>
<blockquote>
<p>You can now use git push and git pull as usual.</p>
</blockquote>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[MDX Hello World Showcase]]></title>
            <link>https://gopalverma.com/diary/notes/notes-world</link>
            <guid>https://gopalverma.com/diary/notes/notes-world</guid>
            <pubDate>Sat, 21 Sep 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[This page demonstrates various MDX components and syntax, including text formatting, links, lists, blockquotes, code blocks, tables, task lists, horizontal rules, math equations, and footnotes. It serves as a comprehensive guide to help you understand MDX parsing and its capabilities.]]></description>
            <content:encoded><![CDATA[<p>This page demonstrates various MDX components and syntax to help you understand MDX parsing.</p>
<h1>Text Formatting</h1>
<p>You can use <em>italic</em>, <strong>bold</strong>, and <em><strong>bold italic</strong></em> text.</p>
<p>You can also use <s>strikethrough</s> and <code>inline code</code>.</p>
<h1>Links</h1>
<p>Here's a <a href="https://mdxjs.com/">link to MDX documentation</a>.</p>
<h1>Lists</h1>
<p>Unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Subitem 2.1</li>
<li>Subitem 2.2</li>
</ul>
</li>
<li>Item 3</li>
</ul>
<p>Ordered list:</p>
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
<h1>Blockquotes</h1>
<blockquote>
<p>This is a blockquote.<br>
It can span multiple lines.</p>
</blockquote>
<h1>Code Blocks</h1>
<p>Inline code: <code>console.log(&quot;Hello, MDX!&quot;);</code></p>
<p>JavaScript code block:</p>
<pre><code class="language-jsx">const greeting = &quot;Hello, MDX!&quot;;
console.log(greeting);
</code></pre>
<p>Python code block:</p>
<pre><code class="language-python">print(&quot;Hello, MDX!&quot;)
</code></pre>
<h1>Tables</h1>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Supported</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tables</td>
<td>Yes</td>
<td>This table</td>
</tr>
<tr>
<td>Code</td>
<td>Yes</td>
<td><code>code</code></td>
</tr>
<tr>
<td>Math</td>
<td>Yes</td>
<td>$E = mc^2$</td>
</tr>
</tbody>
</table>
<h1>Task Lists</h1>
<ul>
<li>[x] Learn MDX basics</li>
<li>[ ] Master advanced MDX concepts</li>
<li>[ ] Build an MDX-powered website</li>
</ul>
<h1>Horizontal Rule</h1>
<hr>
<h1>Math Equations</h1>
<p>$y = mx + b$</p>
<h1>Footnotes</h1>
<p>Here's a sentence with a footnote.[^1]</p>
<p>[^1]: This is the footnote content.</p>
<h1>Conclusion</h1>
<p>This page showcases various MDX components and syntax. Happy MDX parsing!</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Windows Crash of July 19, 2024]]></title>
            <link>https://gopalverma.com/diary/blogs/window-crash-190724</link>
            <guid>https://gopalverma.com/diary/blogs/window-crash-190724</guid>
            <pubDate>Sat, 20 Jul 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[How did a cybersecurity update triggered a global disaster, exposing the hidden dangers of software vulnerabilities.]]></description>
            <content:encoded><![CDATA[<p>On July 19, 2024, a significant global outage occurred affecting Microsoft Windows users, primarily triggered by a problematic update from <a href="%22https://www.crowdstrike.com%22">CrowdStrike</a>, a cybersecurity company. This incident led to widespread instances of the &quot;Blue Screen of Death&quot; (BSOD), a critical error screen displayed by Windows when it encounters a system failure. The repercussions of this outage were felt across various sectors, including airlines, banks, telecommunications, and emergency services, causing operational disruptions and significant public concern.</p>
<h1>Overview of the Incident</h1>
<p>The BSOD incidents began surfacing early on July 19, with users reporting their systems crashing and displaying error messages indicating that the device had encountered a problem and needed to restart. This situation escalated quickly as more users across multiple countries, including the United States, Australia, India, and Japan, experienced similar issues. As the day progressed, reports indicated that the outage had grounded flights, disrupted banking services, and caused chaos in supermarkets and other essential services.</p>
<h1>Causes of the outage</h1>
<p>The root cause of the BSOD was identified as a recent update to the <a href="https://www.crowdstrike.com/blog/statement-on-falcon-content-update-for-windows-hosts">CrowdStrike Falcon Sensor</a>, which is designed to provide endpoint protection and cybersecurity solutions. According to CrowdStrike, the update inadvertently led to stability issues in Windows systems, resulting in the BSOD errors. The company acknowledged the problem and stated that their engineering team was actively working to resolve the issue by reverting the changes made by the update</p>
<p>The National Cyber Security Coordinator of Australia confirmed that the outage was due to a technical issue with a third-party software platform, ruling out the possibility of a cyber-attack. Microsoft also confirmed that they were in contact with CrowdStrike to address the situation and mitigate the impact on users globally.</p>
<h1>Impact of the Outage</h1>
<p>The outage's impact was extensive, with reports indicating that critical services were severely disrupted:</p>
<ul>
<li><strong>Airlines</strong>: Numerous flights were grounded or canceled, particularly in the United States and Australia, as airport systems became inoperable, preventing check-ins and other essential operations.</li>
<li><strong>Banking and Financial Services</strong>: Banking institutions faced significant challenges, with many users unable to access online banking services, leading to concerns about financial transactions and operations.</li>
<li><strong>Telecommunications</strong>: Major telecom companies reported outages, affecting communication services for millions of users.</li>
<li><strong>Emergency Services</strong>: Critical services, including hospitals and emergency response teams, experienced difficulties due to the reliance on Windows systems for operational management.</li>
</ul>
<h1>Technical Analysis of the Windows Crash</h1>
<h2>1. Understanding the Blue Screen of Death (BSOD)</h2>
<p>The BSOD is a critical failure screen that Windows displays when it encounters a fatal system error. This error can occur due to various reasons, including hardware failures, driver issues, or corrupted system files. The BSOD typically includes a stop code that helps identify the source of the problem.</p>
<p>Example of a BSOD Error Code:</p>
<pre><code class="language-shell">STOP: 0x0000007E (0xFFFFFFFFC0000005, 0xFFFFF8024A123456, 0xFFFFF8024A123456, 0xFFFFF8024A123456)
</code></pre>
<p>In this case, the stop code <code>0x0000007E</code> indicates a <code>SYSTEM_THREAD_EXCEPTION_NOT_HANDLED</code> error, often associated with driver problems. The parameters that follow provide additional context for debugging.</p>
<h2>2. Memory Management and Pointer Issues</h2>
<p>One of the prevalent causes of BSODs is improper memory management, particularly when dealing with pointers. As discussed in a recent Twitter thread by Zach Vorhies, a Google whistleblower, the misuse of pointers can lead to catastrophic failures. For example, consider the following C++ structure:</p>
<pre><code class="language-cpp">struct Obj {
    int a;
    int b;
};
</code></pre>
<p>When a pointer is created to this structure:</p>
<pre><code class="language-cpp">Obj* obj = new Obj();
</code></pre>
<p>The address of <code>obj</code> might be something like <code>0x9030</code>. Accessing its members would involve offsets from this base address:</p>
<ul>
<li><code>obj</code> is at <code>0x9030</code></li>
<li><code>obj-&gt;a</code> is at <code>0x9030 + 0x4</code></li>
<li><code>obj-&gt;b</code> is at <code>0x9030 + 0x8</code></li>
</ul>
<p>However, if the pointer is null:</p>
<pre><code class="language-cpp">Obj* obj = NULL;
</code></pre>
<p>Then attempting to access obj-&gt;a would lead to an invalid memory access:</p>
<pre><code class="language-cpp">print(obj-&gt;a); // This will cause a crash
</code></pre>
<p>The program attempts to read from an invalid memory address, leading to a BSOD. This scenario highlights the critical importance of null pointer checks before dereferencing pointers, especially in system-level programming.</p>
<h2>3. The Role of Drivers</h2>
<p>In the case of the CrowdStrike Falcon Sensor update, the driver responsible for system security likely interacted with the Windows kernel in a way that introduced instability. Drivers operate at a high privilege level, meaning that any bugs can lead to system-wide failures. As Vorhies pointed out, if a programmer forgets to check for null pointers, it can lead to accessing invalid memory regions, causing the operating system to crash out of caution.</p>
<p>When a system driver encounters an error, it cannot simply terminate like a user-mode application; instead, the operating system must crash to prevent further damage. This is why 95% of BSODs are attributed to issues within system drivers, as noted by Vorhies.</p>
<h2>4. Error Handling and Exception Management</h2>
<p>Proper error handling is crucial in preventing crashes. In languages like C/C++, developers often use structured exception handling (SEH) to catch exceptions and handle them gracefully. Here's an example:</p>
<pre><code class="language-cpp">__try {
    int *ptr = NULL;
    *ptr = 42; // This will cause an access violation
} __except(EXCEPTION_EXECUTE_HANDLER) {
    printf(&quot;An exception occurred.\n&quot;);
}
</code></pre>
<p>In the case of the CrowdStrike update, if the driver did not handle exceptions correctly, it could lead to a system crash.</p>
<h2>5. Computational Analysis of the Update Process</h2>
<p>When an update is deployed, it often involves downloading and installing new drivers. This process can be mathematically modeled to understand its impact on system stability. Let’s define some variables:</p>
<ul>
<li><strong>U</strong>: The update size (in MB)</li>
<li><strong>D</strong>: The download time (in seconds)</li>
<li><strong>I</strong>: The installation time (in seconds)</li>
<li><strong>R</strong>: The risk of failure (a function of <strong>U</strong>, <strong>D</strong>, and <strong>I</strong>)</li>
</ul>
<p>A simple model can be expressed as:</p>
<p>$ R = f(U, D, I) = k \cdot \left(\frac{U}{D + I}\right) $</p>
<p>Here, <strong>k</strong> is a constant representing the system's resilience to updates. A higher <strong>R</strong> indicates a greater risk of failure, highlighting the need for careful management of update processes.</p>
<h2>6. Recovery Steps and Best Practices</h2>
<p>In response to the crisis, CrowdStrike outlined recovery steps for affected users. These include booting into Safe Mode, navigating to the CrowdStrike driver directory, and removing the problematic driver file. This process is critical for restoring functionality but poses challenges, especially for cloud environments and remote users.</p>
<p>Example Recovery Steps:</p>
<ol>
<li>Boot Windows into Safe Mode or the Windows Recovery Environment.</li>
<li>Navigate to <code>C:\Windows\System32\drivers\CrowdStrike</code></li>
<li>Locate and delete the file matching <code>C-00000291*.sys</code></li>
<li>Boot the host normally.</li>
</ol>
<p>For cloud environments like AWS and Azure, specific commands and procedures are required to revert to stable states.</p>
<h1>Conclusion</h1>
<p>The Windows crash on July 19, 2024, serves as a stark reminder of the vulnerabilities inherent in software updates, particularly in critical systems. The incident can be attributed to a combination of factors, including improper memory management, inadequate error handling, and the complexities of driver interactions.</p>
<p>By understanding these computational principles and examining the underlying code, developers can appreciate the importance of rigorous testing and validation in software updates. As organizations increasingly rely on interconnected systems, the need for robust cybersecurity measures and contingency plans becomes paramount to mitigate the impact of such outages in the future.</p>
<p>This incident not only highlights the challenges faced by software developers but also emphasizes the critical role of thorough testing and validation in ensuring system stability and security.</p>
<h1>References</h1>
<ol>
<li>
<p><strong>Blue Screen of Death (BSOD)</strong>:</p>
<ul>
<li>Microsoft Documentation on BSOD: <a href="https://support.microsoft.com/en-us/help/14238/windows-10-troubleshoot-blue-screen-errors">Microsoft Support - Troubleshoot blue screen errors</a></li>
</ul>
</li>
<li>
<p><strong>Memory Management and Pointers</strong>:</p>
<ul>
<li>C++ Pointers and Memory Management: <a href="https://www.geeksforgeeks.org/pointers-in-c/">GeeksforGeeks - Pointers in C/C++</a></li>
<li>Understanding Null Pointers: <a href="http://www.cplusplus.com/doc/tutorial/pointers/">Cplusplus.com - Pointers</a></li>
</ul>
</li>
<li>
<p><strong>Driver Development</strong>:</p>
<ul>
<li>Windows Driver Development: <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/">Microsoft Docs - Windows Drivers</a></li>
<li>Understanding System Drivers: <a href="https://wiki.osdev.org/Driver">OSDev Wiki - Drivers</a></li>
</ul>
</li>
<li>
<p><strong>Error Handling in C/C++</strong>:</p>
<ul>
<li>Structured Exception Handling: <a href="https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/structured-exception-handling?view=msvc-160">Microsoft Docs - Structured Exception Handling</a></li>
</ul>
</li>
<li>
<p><strong>Buffer Overflow</strong>:</p>
<ul>
<li>Buffer Overflow Vulnerabilities: <a href="https://owasp.org/www-community/attacks/Buffer_Overflow_Attack">OWASP - Buffer Overflow</a></li>
</ul>
</li>
<li>
<p><strong>Mathematical Modeling in Software Engineering</strong>:</p>
<ul>
<li>Software Reliability Engineering: <a href="https://ieeexplore.ieee.org/document/6880151">IEEE - Software Reliability Engineering</a></li>
</ul>
</li>
<li>
<p><strong>CrowdStrike Falcon</strong>:</p>
<ul>
<li>CrowdStrike Official Website: <a href="https://www.crowdstrike.com/">CrowdStrike</a></li>
</ul>
</li>
</ol>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[The End of Junior Engineers]]></title>
            <link>https://gopalverma.com/diary/blogs/end-of-je</link>
            <guid>https://gopalverma.com/diary/blogs/end-of-je</guid>
            <pubDate>Tue, 09 Jul 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[The Threat of AI Taking Over Entry-Level Jobs]]></description>
            <content:encoded><![CDATA[<p>In a dimly lit office, a fresh-faced junior engineer named Alex stared at the computer screen, watching in disbelief as lines of code wrote themselves. The once bustling room, filled with the hum of eager conversations and the clatter of keyboards, had fallen eerily silent. In the corner, an AI-driven robot arm effortlessly assembled circuit boards, a task that Alex and his colleagues used to handle. The transformation was swift and ruthless, as artificial intelligence (AI) had not just joined the workforce but had begun to dominate it. The promise of innovation had turned into a dystopian reality where entry-level engineering jobs were vanishing at an alarming rate. This blog delves into the unsettling reality of why AI is poised to wipe out these jobs, supported by chilling statistics, real-life horror stories, and unsettling daily news.</p>
<h1>The AI Invasion in Engineering</h1>
<p>AI is infiltrating every aspect of engineering, from design and simulation to predictive maintenance and quality control. Machine learning algorithms can analyze massive datasets, spot patterns, and make decisions with a speed and accuracy that humans cannot match. While this might seem like progress, it poses a significant threat to those just starting their engineering careers.</p>
<h1>Alarming Statistics</h1>
<h2>1. <strong>Automation and Job Loss</strong></h2>
<p>According to the World Economic Forum's 2020 report, AI and automation could displace 85 million jobs by 2025. While 97 million new roles may be created, these often require advanced skills that most junior engineers currently lack . As Martin Ford mentions in his book &quot;Rise of the Robots: Technology and the Threat of a Jobless Future,&quot;</p>
<blockquote>
<p>&quot;As technology advances, it eliminates the need for many types of jobs, particularly those that involve routine tasks&quot;.</p>
</blockquote>
<h2>2. <strong>Decline in Entry-Level Positions</strong></h2>
<p>A 2022 McKinsey study revealed a 15% decrease in entry-level engineering positions over the past five years, primarily due to automation and AI technologies . Erik Brynjolfsson and Andrew McAfee, in &quot;The Second Machine Age,&quot; argue that</p>
<blockquote>
<p>&quot;technological progress is going to leave behind some people, perhaps even a lot of people, as it races ahead&quot; .</p>
</blockquote>
<h2>3. <strong>AI in Manufacturing</strong></h2>
<p>In the automotive industry, giants like Tesla and BMW have embraced AI in their manufacturing processes. PwC estimates AI could boost productivity by up to 40%, but at the cost of human jobs, particularly those of junior engineers who handle routine tasks . Jerry Kaplan states in &quot;Humans Need Not Apply,&quot;</p>
<blockquote>
<p>&quot;AI and robotics are accelerating the automation of routine tasks, which were once the domain of junior engineers and other entry-level professionals&quot; .</p>
</blockquote>
<h1>Real-Life Nightmares</h1>
<ol>
<li><strong>Automotive Industry</strong>: Tesla's Gigafactories are a dystopian glimpse into our future. AI runs the show, from quality control to predictive maintenance and even design. The result? Fewer jobs for junior engineers, as machines outpace human capabilities.</li>
<li><strong>Software Development</strong>: AI tools like GitHub Copilot are taking over coding. Junior software engineers, who used to spend their days writing and debugging code, now find these tasks increasingly automated. Efficiency is up, but the opportunities for hands-on learning and growth are vanishing.</li>
<li><strong>Construction</strong>: AI-driven project management tools are becoming the norm in construction. These tools can predict timelines, manage resources, and identify risks better than any human. The fallout? A reduced need for junior engineers who once handled these tasks.</li>
</ol>
<h1>Daily News and Trends</h1>
<ol>
<li><strong>AI in Recruitment</strong>: Companies are using AI-driven recruitment tools to screen candidates, quickly weeding out those without advanced skills. Entry-level candidates must now have a deep understanding of AI and machine learning to even stand a chance.</li>
<li><strong>Upskilling Initiatives</strong>: Companies like IBM and Google are pushing upskilling programs to help employees adapt. Junior engineers must scramble to develop new skills to stay relevant in an AI-dominated job market.</li>
<li><strong>Educational Shifts</strong>: Universities are frantically updating their curricula to include AI and machine learning. For example, MIT's comprehensive AI program prepares students for this new world, underscoring the necessity of AI literacy for future engineers.</li>
</ol>
<h1>The Grim Future for Junior Engineers</h1>
<p>While AI is casting a long, dark shadow over junior engineering jobs, there are still a few glimmers of hope. Here's how junior engineers can try to survive:</p>
<ol>
<li><strong>Embrace Continuous Learning</strong>: In an AI-driven world, staying still is falling behind. Junior engineers must constantly expand their skill sets by diving into AI, machine learning, and data science.</li>
<li><strong>Develop Soft Skills</strong>: Technical skills alone won't cut it. Creativity, problem-solving, and communication are more important than ever. These soft skills might be the last refuge in a world increasingly dominated by machines.</li>
<li><strong>Use AI to Your Advantage</strong>: Rather than fighting the inevitable, junior engineers should learn to work alongside AI tools to enhance their productivity. Understanding AI can provide a crucial edge.</li>
<li><strong>Seek Mentorship</strong>: Finding mentors experienced in AI and related fields is vital. Mentors can help junior engineers navigate this treacherous landscape and find opportunities for growth.</li>
</ol>
<h1>Conclusion</h1>
<p>AI is not just reshaping the engineering landscape; it's threatening the very existence of junior engineers. To survive this transition, junior engineers must embrace continuous learning, focus on soft skills, leverage AI tools, and seek mentorship. Viewing AI not as a replacement but as an enabler might be the only way to avoid being left behind in this relentless march of technology. The question remains: will junior engineers adapt quickly enough, or will they be swept away by the AI tide?</p>
<h1>References</h1>
<ol>
<li>World Economic Forum. (2020). <a href="https://www.weforum.org/reports/the-future-of-jobs-report-2020">The Future of Jobs Report 2020</a>.</li>
<li>McKinsey &amp; Company. (2022). <a href="https://www.mckinsey.com/featured-insights/future-of-work/the-future-of-work-after-covid-19">The Future of Work after COVID-19</a>.</li>
<li>PwC. (2018). <a href="https://www.pwc.com/gx/en/industries/technology/artificial-intelligence/ai-and-robotics.html">AI and Robotics</a>.</li>
<li>Tesla. (2023). <a href="https://www.tesla.com/gigafactory">Gigafactory</a>.</li>
<li>GitHub. (2023). <a href="https://github.com/features/copilot">GitHub Copilot</a>.</li>
<li>Kaplan, J. (2015). <em>Humans Need Not Apply: A Guide to Wealth and Work in the Age of Artificial Intelligence</em>. Yale University Press.</li>
<li>IBM. (2023). <a href="https://www.ibm.com/skills">IBM Skills</a>.</li>
<li>Google. (2023). <a href="https://ai.google/">Google AI</a>.</li>
<li>Massachusetts Institute of Technology. (2023). <a href="https://computing.mit.edu/">MIT Schwarzman College of Computing</a>.</li>
</ol>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Minimalistic vs Noob Programmers]]></title>
            <link>https://gopalverma.com/diary/blogs/fake-minimalism</link>
            <guid>https://gopalverma.com/diary/blogs/fake-minimalism</guid>
            <pubDate>Mon, 08 Jul 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Explore the crucial differences between true minimalistic programmers and those who merely imitate minimalism. This blog post delves into the characteristics of minimalistic artist programmers and novice programmers attempting to fake minimalism, using examples from React and Tailwind CSS. Learn about efficient state management, optimal use of frameworks, and best practices for writing clean, maintainable code. Discover how real pro programmers take minimalism to the next level, combining efficiency, readability, and performance optimization. Gain insights into identifying genuine minimalism in programming and avoiding common pitfalls of oversimplification.]]></description>
            <content:encoded><![CDATA[<p>Explore the crucial differences between true minimalistic programmers and those who merely imitate minimalism. This blog post delves into the characteristics of minimalistic artist programmers and novice programmers attempting to fake minimalism, using examples from React and Tailwind CSS. Learn about efficient state management, optimal use of frameworks, and best practices for writing clean, maintainable code. Discover how real pro programmers take minimalism to the next level, combining efficiency, readability, and performance optimization. Gain insights into identifying genuine minimalism in programming and avoiding common pitfalls of oversimplification.</p>
<h1>The Problem</h1>
<p>In the world of programming, minimalism is a highly valued principle. However, there's a fine line between a programmer who practices minimalism artfully and one who uses it as a facade to cover a lack of skill. This blog will help you identify the key differences between a minimalistic artist programmer and a noob programmer who fakes minimalism, using examples from React and Tailwind CSS.</p>
<h1>Understanding Minimalism in Programming</h1>
<p>Minimalism in programming means using only what is necessary to achieve the desired functionality, without overcomplicating the code. It involves clean, efficient, and readable code. Let's look at how this principle applies to React and Tailwind CSS.</p>
<h2>Minimalistic Artist Programmer</h2>
<p>A minimalistic artist programmer embraces minimalism without compromising functionality or readability. They focus on writing clean, efficient code that's easy to maintain. Here are some characteristics and examples:</p>
<ol>
<li>Efficient use of language features</li>
<li>Clear and descriptive naming conventions</li>
<li>Modular and reusable code structures</li>
<li>Thoughtful state management</li>
<li>Optimal use of libraries and frameworks</li>
</ol>
<p><strong>React Example:</strong></p>
<p>A minimalistic artist will use React hooks and concise state management techniques.</p>
<pre><code class="language-jsx">import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    &lt;div&gt;
      &lt;p&gt;You clicked {count} times&lt;/p&gt;
      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;
        Click me
      &lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>In this example, the useState hook is used effectively to manage the state of the counter. The code is clear, concise, and easy to understand. Notice how:</p>
<ol>
<li>The state is declared with a meaningful name (count)</li>
<li>The setCount function is used correctly within the onClick handler</li>
<li>The component's logic is straightforward and focused on a single responsibility</li>
</ol>
<p><strong>Tailwind CSS Example:</strong></p>
<p>A minimalistic artist uses Tailwind CSS classes to style components efficiently.</p>
<pre><code class="language-html">&lt;button className=&quot;bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded&quot;&gt;
  Button
&lt;/button&gt;
</code></pre>
<p>Here, the button is styled using Tailwind CSS utility classes, achieving a modern look with minimal code. This approach:</p>
<ol>
<li>Eliminates the need for separate CSS files</li>
<li>Provides a consistent design system</li>
<li>Allows for quick adjustments and responsive design</li>
<li>Reduces the overall file size by only including used styles</li>
</ol>
<h2>Noob Programmer Faking Minimalism</h2>
<p>A noob programmer might misunderstand minimalism, leading to oversimplified or non-functional code. Here are some examples:</p>
<p><strong>React Example:</strong></p>
<pre><code class="language-tsx">function Counter() {
  let count = 0;

  return (
    &lt;div&gt;
      &lt;p&gt;You clicked {count} times&lt;/p&gt;
      &lt;button onClick={() =&gt; count++}&gt;
        Click me
      &lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>In this example, the programmer avoided using useState for state management, resulting in a non-functional component because React does not re-render the component when <code>count</code> changes. This demonstrates:</p>
<ol>
<li>Lack of understanding of React's rendering mechanism</li>
<li>Misuse of component-level variables instead of state</li>
<li>Ineffective event handling that doesn't trigger re-renders</li>
</ol>
<p><strong>Tailwind CSS Example:</strong></p>
<p>A noob programmer might misuse Tailwind CSS classes, leading to redundant or ineffective styles.</p>
<p>A noob programmer might misuse Tailwind CSS classes, leading to redundant or ineffective styles.</p>
<pre><code class="language-html">&lt;button className=&quot;text-center p-2&quot;&gt;
  Button
&lt;/button&gt;
</code></pre>
<p>Here, the button lacks essential styling to differentiate it from plain text. The minimal classes used do not achieve the desired effect. This shows:</p>
<ol>
<li>Insufficient understanding of Tailwind's utility classes</li>
<li>Lack of consideration for user experience and visual hierarchy</li>
<li>Missed opportunities for responsive design and interactive states</li>
</ol>
<h2>The Real Pro Programmer Approach</h2>
<p>A real pro programmer takes minimalism to the next level, combining efficiency, readability, and maintainability. Here's how they might approach our examples:</p>
<p><strong>React Example:</strong></p>
<pre><code class="language-jsx">import { useCallback, useState } from 'react';

const Counter = () =&gt; {
  const [count, setCount] = useState(0);
  const increment = useCallback(() =&gt; setCount(prev =&gt; prev + 1), []);

  return (
    &lt;div&gt;
      &lt;p&gt;You clicked {count} times&lt;/p&gt;
      &lt;button onClick={increment}&gt;Click me&lt;/button&gt;
    &lt;/div&gt;
  );
};
</code></pre>
<p>In this pro version:</p>
<ol>
<li>The component is defined as an arrow function for consistency.</li>
<li><code>useCallback</code> is used to memoize the increment function, optimizing performance.</li>
<li>The state update uses a functional update to ensure accuracy with rapid clicks.</li>
</ol>
<p><strong>Tailwind CSS Example:</strong></p>
<pre><code class="language-jsx">const Button = ({ children, onClick }) =&gt; (
  &lt;button
    className=&quot;bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline transition duration-300 ease-in-out&quot;
    onClick={onClick}
  &gt;
    {children}
  &lt;/button&gt;
);
</code></pre>
<p>Here, the pro programmer:</p>
<ol>
<li>Creates a reusable Button component for consistency across the application.</li>
<li>Adds focus and transition styles for better accessibility and user experience.</li>
<li>Uses props to make the button flexible and reusable.</li>
</ol>
<h1>Best Practices for Minimalistic Programming</h1>
<p>To truly embrace minimalism in programming, consider these best practices:</p>
<ol>
<li><strong>Understand the tools</strong>: Gain a deep understanding of the frameworks and libraries you're using.</li>
<li><strong>Prioritize readability</strong>: Write code that's easy for others (and your future self) to understand.</li>
<li><strong>Use built-in features</strong>: Leverage language and framework features instead of reinventing the wheel.</li>
<li><strong>Optimize for performance</strong>: Consider the performance implications of your code choices.</li>
<li><strong>Refactor regularly</strong>: Continuously improve your code to maintain its minimalistic nature.</li>
</ol>
<h1>Conclusion</h1>
<p>Distinguishing between a minimalistic artist programmer and a noob programmer faking minimalism requires looking at the effectiveness and clarity of their code. A true minimalistic programmer will use minimal code to achieve maximum functionality and readability, while a noob programmer might use minimalism as a cover for lack of skill, resulting in incomplete or ineffective code.</p>
<p>By examining examples in React and Tailwind CSS, you can better understand how to identify true minimalism in programming. Remember, minimalism is about simplicity and efficiency, not cutting corners.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Pair programming lowers quality]]></title>
            <link>https://gopalverma.com/diary/blogs/pair-prog-sucks</link>
            <guid>https://gopalverma.com/diary/blogs/pair-prog-sucks</guid>
            <pubDate>Sat, 06 Jul 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Pair Programming: Debunking the Myth of Improved Code Quality - This article challenges the widely held belief that pair programming enhances code quality and accelerates development. It presents evidence from studies showing increased defects and longer development times with pair programming. The piece explores how this practice can lead to reduced individual accountability, increased cognitive load, and potential personality clashes. While acknowledging some benefits like knowledge sharing, it argues for a balanced approach that doesn't neglect individual skill development and code ownership.]]></description>
            <content:encoded><![CDATA[<p>Pair programming has long been touted as a panacea for improving code quality and reducing bugs. The idea of having two developers collaborating on a single task seems intuitive - more minds working together should lead to better results, right? However, the reality paints a different picture. Numerous studies and real-world experiences suggest that pair programming, in fact, lowers the overall quality of the codebase.</p>
<h1>The Negative Impact on Code Quality</h1>
<p>Contrary to popular belief, pair programming has been shown to have a detrimental effect on code quality. A study conducted by the University of Utah found that code produced through pair programming exhibited 15% more defects compared to code written by individual developers. This surprising result challenges the notion that pair programming leads to higher-quality code.</p>
<h1>Lack of Individual Accountability</h1>
<p>When working in pairs, developers may feel less accountable for the quality of their code. The presence of a partner can create a false sense of security, leading to a more casual approach to coding and a higher tolerance for technical debt. Developers may be more inclined to take shortcuts or implement suboptimal solutions, knowing that their partner will likely not catch or challenge these decisions.</p>
<h1>Increased Cognitive Load</h1>
<p>Pair programming places a significant cognitive load on developers. Constantly communicating, explaining their thought process, and navigating the codebase together can be mentally exhausting. This fatigue can lead to reduced focus, increased errors, and a lower overall quality of the code produced during pair programming sessions.</p>
<h1>Personality Clashes and Communication Issues</h1>
<p>Pair programming requires effective communication and collaboration between developers. However, personality clashes, differences in coding styles, and communication breakdowns can hinder this process. When developers struggle to work together harmoniously, the quality of the code suffers as a result.</p>
<h1>The Myth of Faster Development</h1>
<p>Another common misconception about pair programming is that it leads to faster development cycles. While pair programming may initially seem more efficient, with two developers working on a single task, studies have shown that this is not always the case.</p>
<p>A research experiment conducted by NASA found that pair programming took 15% more time to complete compared to individual programming. This is likely due to the increased overhead of communication, coordination, and the need to reach consensus on design decisions.</p>
<h1>The Importance of Individual Skill Development</h1>
<p>While pair programming can be a valuable tool for knowledge sharing and mentorship, it should not be the sole focus of a development team's efforts. Developers need to have opportunities to work independently, hone their skills, and take ownership of their code. Overreliance on pair programming can stifle individual growth and lead to a team of developers who are overly dependent on their partners.</p>
<h1>Conclusion</h1>
<p>The idea of pair programming improving code quality is a myth that has been perpetuated by the software development community for far too long. While pair programming can have its benefits, such as knowledge sharing and reduced bus factor, it should not be seen as a silver bullet for improving code quality. Developers need to focus on building their individual skills, taking responsibility for their code, and communicating effectively with their teammates. By striking a balance between collaborative and individual work, development teams can produce high-quality code that meets the needs of their</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[GitHub Templates]]></title>
            <link>https://gopalverma.com/diary/notes/gh-templates</link>
            <guid>https://gopalverma.com/diary/notes/gh-templates</guid>
            <pubDate>Fri, 05 Jul 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[GitHub templates streamline software development by providing structured formats for bug reports, commits, issues, pull requests, and feature requests. They ensure consistency, improve communication, and facilitate efficient problem-solving within teams. This document covers various template types, including detailed templates for bug reports, Git commit messages, issues, pull requests, and enhancement requests. Implementing these templates enhances workflow, reduces misunderstandings, and accelerates high-quality software delivery.]]></description>
            <content:encoded><![CDATA[<p>GitHub templates streamline software development by providing structured formats for bug reports, commits, issues, pull requests, and feature requests. They ensure consistency, improve communication, and facilitate efficient problem-solving within teams. This document covers various template types, including detailed templates for bug reports, Git commit messages, issues, pull requests, and enhancement requests. Implementing these templates enhances workflow, reduces misunderstandings, and accelerates high-quality software delivery.</p>
<h1>How it Works?</h1>
<p>Templates provide a structured format for consistently capturing key information needed for common software development tasks like bug reports, commits, issues, pull requests (PRs), and enhancement/feature requests. Using templates ensures all relevant details are provided, streamlining the process and making it easier to prioritize, reproduce, and resolve the reported issues or requested changes.</p>
<h1>Templates</h1>
<p>Following are the templates for bug reports, commits, issues, PRs, enhancement/feature requests.</p>
<h2>Bug-Report Template</h2>
<pre><code class="language-markdown">## Overview

[Provide a brief summary of the bug.]

## How to Reproduce

1. [Step 1]
2. [Step 2]
3. [Step 3]
4. [Include as many steps as necessary to reproduce the issue]

## Environment Information

- **Operating System**: Windows 10
- **Browser**: Chrome 98.0.4758.102
- **Application Version/Commit**: v2.1.0

## Actual and Expected Behavior

- **Actual**: [Describe what happened]
- **Expected**: [Describe what you expected to happen]

## Additional Context

[Include any additional information that might be relevant]
</code></pre>
<h2>Git Commit Message Convention</h2>
<blockquote>
<p>This is adapted from <a href="https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular">Angular's commit convention</a>.</p>
</blockquote>
<p>Messages must be matched by the following regex:</p>
<pre><code class="language-js">/^(revert: )?(feat|fix|docs|style|refactor|perf|test|workflow|build|ci|chore|types|wip)(\(.+\))?: .{1,72}/;
</code></pre>
<details>
<summary>Full Message Format</summary>
<br />
A commit message consists of a **header**, **body** and **footer**. The header has a **type**, **scope** and **subject**:
<pre><code class="language-html">&lt;type&gt;(&lt;scope&gt;): &lt;subject&gt;
&lt;BLANK LINE&gt;
&lt;body&gt;
&lt;BLANK LINE&gt;
&lt;footer&gt;
</code></pre>
<p>The <strong>header</strong> is mandatory and the <strong>scope</strong> of the header is optional.</p>
<h3>Revert</h3>
<p>If the commit reverts a previous commit, it should begin with <code>revert:</code>, followed by the header of the reverted commit. In the body, it should say: <code>This reverts commit &lt;hash&gt;.</code>, where the hash is the SHA of the commit being reverted.</p>
<h3>Type</h3>
<p>If the prefix is <code>feat</code>, <code>fix</code> or <code>perf</code>, it will appear in the changelog. However, if there is any <a href="#footer">BREAKING CHANGE</a>, the commit will always appear in the changelog.</p>
<p>Other prefixes are up to your discretion. Suggested prefixes are <code>docs</code>, <code>chore</code>, <code>style</code>, <code>refactor</code>, and <code>test</code> for non-changelog related tasks.</p>
<h3>Scope</h3>
<p>The scope could be anything specifying the place of the commit change.</p>
<h3>Subject</h3>
<p>The subject contains a succinct description of the change:</p>
<ul>
<li>use the imperative, present tense: &quot;change&quot; not &quot;changed&quot; nor &quot;changes&quot;</li>
<li>don't capitalize the first letter</li>
<li>no dot (.) at the end</li>
</ul>
<h3>Body</h3>
<p>Just as in the <strong>subject</strong>, use the imperative, present tense: &quot;change&quot; not &quot;changed&quot; nor &quot;changes&quot;.<br>
The body should include the motivation for the change and contrast this with previous behavior.</p>
<h3>Footer</h3>
<p>The footer should contain any information about <strong>Breaking Changes</strong> and is also the place to<br>
reference GitHub issues that this commit <strong>Closes</strong>.</p>
<p><strong>Breaking Changes</strong> should start with the word <code>BREAKING CHANGE:</code> with a space or two newlines. The rest of the commit message is then used for this.</p>
</details>
<h2>Issue Template</h2>
<pre><code class="language-markdown"># Prerequisites

Please answer the following questions for yourself before submitting an issue. **YOU MAY DELETE THE PREREQUISITES SECTION.**

- [ ] I am running the latest version
- [ ] I checked the documentation and found no answer
- [ ] I checked to make sure that this issue has not already been filed
- [ ] I'm reporting the issue to the correct repository (for multi-repository projects)

# Issue Type

[ ] Bug Report
[ ] Feature Request
[ ] Question

# Description

[Provide a clear and concise description of the issue or request. If it's a bug, describe the unexpected behavior. If it's a feature request, explain the new functionality you're proposing. For questions, clearly state your question.]

# Steps to Reproduce (if applicable)

1. [Step 1]
2. [Step 2]
3. [Step 3]
4. [Include as many steps as necessary to reproduce the issue, if applicable]

# Expected Behavior

[Describe what you expected to happen.]

# Actual Behavior

[Describe what actually happened.]

# Environment Information

- **Operating System**: [e.g., Windows 10, macOS 11.3, Ubuntu 20.04]
- **Browser (if applicable)**: [e.g., Chrome 98.0.4758.102, Firefox 98.0]
- **Application Version/Commit (if applicable)**: [e.g., v2.1.0 or Git commit hash]

# Screenshots (if applicable)

[Include screenshots or images that help illustrate the issue, if applicable.]

# Additional Information

[Include any additional information that might be relevant to understanding or resolving the issue.]

---

**By submitting this issue, I confirm that I have read and understood the project's guidelines, and I believe this is not a duplicate of an existing issue.**
</code></pre>
<h2>Pull-Request Template</h2>
<pre><code class="language-markdown"># Description

[Provide a brief description of the purpose of this pull request.]

# Related Issues

[Include links to any related issues or discussions that are addressed by this pull request.]

# Changes Made

[Highlight the key changes made in this pull request. This can include new features, bug fixes, improvements, etc.]

# Screenshots (if applicable)

[Include screenshots or gifs demonstrating the changes made, if applicable.]

# Checklist

- [ ] I have tested these changes locally.
- [ ] I have updated the documentation accordingly.
- [ ] The code follows the project's coding standards.
- [ ] All tests pass successfully.
- [ ] The branch is up-to-date with the base branch.
- [ ] There are no merge conflicts.
- [ ] I have added necessary comments to the code, especially in complex areas.

# Additional Notes

[Include any additional information that might be relevant for the reviewers or that explains the context of the changes.]

# Reviewer Guidelines

[Provide guidelines for reviewers, such as specific areas to focus on or any particular concerns.]

# Definition of Done

[Specify the criteria that need to be met for this pull request to be considered &quot;done&quot; and ready for merging.]

# Closing Notes

[Include any closing notes, acknowledgments, or shoutouts to contributors.]

---

**By submitting this pull request, I confirm that my contributions are made under the terms of the project's guidelines.**
</code></pre>
<h2>Enhancement/Feature Request Template</h2>
<pre><code class="language-markdown"># Description

[Provide a clear and concise description of the enhancement or feature you are proposing.]

# Use Case

[Describe the specific use case or scenario where this enhancement or feature would be beneficial.]

# Proposed Solution

[Outline your proposed solution for the enhancement or feature. If applicable, include code snippets, diagrams, or any other details that help convey your idea.]

# Alternatives Considered

[If you've considered alternative solutions, list them here with a brief explanation of why you chose the proposed solution over the alternatives.]

# Benefits

[Explain the benefits and value that the proposed enhancement or feature would bring to users or the project.]

# Implementation Details

[If you have any suggestions on how the enhancement or feature could be implemented, provide high-level implementation details. If you are unsure, you can leave this section blank.]

# Additional Context

[Include any additional information that might be relevant to understanding or discussing the proposed enhancement or feature.]

---

**By submitting this enhancement or feature request, I confirm that I have read and understood the project's guidelines, and I believe this is not a duplicate of an existing request.**
</code></pre>
<h1>Conclusion</h1>
<p>Using these templates for bug reports, commits, issues, pull requests, and enhancement/feature requests can significantly improve the efficiency and clarity of your development process. They provide a structured approach to communication within your team and with external contributors, ensuring that all necessary information is captured consistently. By adopting these templates, you can streamline your workflow, reduce misunderstandings, and ultimately deliver better software more quickly.</p>
<p>Remember to adapt these templates to fit your specific project needs and team preferences. Regular reviews and updates of these templates can help keep them relevant and effective as your project evolves.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Ollama on external drive]]></title>
            <link>https://gopalverma.com/diary/notes/ollama-external</link>
            <guid>https://gopalverma.com/diary/notes/ollama-external</guid>
            <pubDate>Fri, 21 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Explore the benefits of running Large Language Models (LLMs) locally using Ollama, with a focus on data security, reduced latency, and customization. Learn how to set up Ollama on an external drive for efficient model management and storage, giving users full control over their data and model deployment. This guide covers the advantages of local LLMs, Ollama's features, and step-by-step instructions for installation and configuration on external storage.]]></description>
            <content:encoded><![CDATA[<p>Explore the benefits of running Large Language Models (LLMs) locally using Ollama, with a focus on data security, reduced latency, and customization. Learn how to set up Ollama on an external drive for efficient model management and storage, giving users full control over their data and model deployment. This guide covers the advantages of local LLMs, Ollama's features, and step-by-step instructions for installation and configuration on external storage.</p>
<h1>Why run LLMs locally?</h1>
<ol>
<li>
<p><strong>Data security:</strong><br>
Local LLMs can process data on-site, reducing the risk of data breaches by eliminating the need to transmit data over the internet. This can also help meet regulatory requirements for data privacy and security.</p>
</li>
<li>
<p><strong>Reduced latency:</strong><br>
Running LLMs locally can reduce the response time between a request and the model's response. This can be especially beneficial for applications that require real-time data processing.</p>
</li>
<li>
<p><strong>Customization:</strong><br>
Local LLMs can be tailored to specific needs and requirements, allowing for better performance than general-purpose models.</p>
</li>
<li>
<p><strong>Control:</strong><br>
Local deployment gives users complete control over their hardware, data, and the LLMs themselves. This can be useful for optimization and customization according to specific needs and regulations.</p>
</li>
<li>
<p><strong>Flexibility:</strong><br>
Local deployment can also provide greater flexibility than working with third-party servers, which may limit businesses to pre-defined models and functionality.</p>
</li>
</ol>
<h1>But why Ollama?</h1>
<p>Ollama bridges the gap between large language models (LLMs) and local development, allowing you to run powerful LLMs directly on your machine. Here’s how Ollama empowers you:</p>
<ol>
<li>
<p><strong>Simplified LLM Interaction:</strong><br>
Ollama’s straightforward CLI and API make it easy to create, manage, and interact with LLMs, accessible to a wide range of users.</p>
</li>
<li>
<p><strong>Pre-built Model Library:</strong><br>
Access a curated collection of ready-to-use LLM models, saving you time and effort.</p>
</li>
<li>
<p><strong>Customization Options:</strong><br>
Fine-tune models to your specific needs, customize prompts, or import models from various sources for greater control.</p>
</li>
</ol>
<h1>How to setup?</h1>
<h2>1. Download Ollama for your OS from <a href="https://www.ollama.com/download">here</a>.</h2>
<blockquote>
<p>To checkout the code base and community integrations, check out the <a href="https://github.com/ollama/ollama">Ollama GitHub repository</a>.</p>
</blockquote>
<h2>2. After downloading, run your first model.</h2>
<p>This will install the model at <code>~/.ollama/models/</code> and allow you to interact with it.</p>
<pre><code class="language-bash">ollama run llama3 # or any other model you want
</code></pre>
<h2>3. How to install models in an external drive?</h2>
<p>For this, follow these steps after connecting your hard drive to your machine.</p>
<h3>1. Execute this command to create a models directory in your external drive:</h3>
<pre><code class="language-bash">mkdir -p ai_models/ollama/models
</code></pre>
<p>This will generate a directory structure like this in your external drive:</p>
<pre><code class="language-md">ai_models/
└── ollama/
    └── models/
</code></pre>
<h3>2. Creating a symlink in your ~/.ollama/models directory to your external drive:</h3>
<p>The Ollama is designed to search for its models in the <code>~/.ollama/models</code> directory by default. However, if you want to store your Ollama models on an external drive (in this case, <code>~/Volumes/drive/ai_models/ollama/models</code>), you can create a symlink to redirect the library's search to the external location.</p>
<ol>
<li>Remove the default models directory in your <code>~/.ollama</code> directory.</li>
</ol>
<pre><code class="language-bash">sudo rm -rf models
# enter the password 🔑
</code></pre>
<ol start="2">
<li>Create a symlink.</li>
</ol>
<pre><code class="language-bash">Replace lines: 88-88
sudo ln -s /Volumes/drive/ai_models/ollama/models ~/.ollama/models
</code></pre>
<p>Replace lines: 91-91<br>
3. Check the <code>~/.ollama</code> for symlink. Execute this command to list all items with info:</p>
<pre><code class="language-bash">ls -la
</code></pre>
<p>You will see a similar output:</p>
<pre><code class="language-bash">total 48
drwxr-xr-x@   8 gopalverma  staff   256 Jun 20 00:38 .
drwxr-x---+ 107 gopalverma  staff  3424 Jun 22 10:57 ..
-rw-r--r--@   1 gopalverma  staff  6148 Jun 19 17:34 .DS_Store
-rw-------    1 gopalverma  staff  4976 Jun 20 00:38 history
-rw-------@   1 gopalverma  staff   387 Jun 19 14:40 id_ed25519
-rw-r--r--@   1 gopalverma  staff    81 Jun 19 14:40 id_ed25519.pub

Replace lines: 108-108
drwxr-xr-x@   3 gopalverma  staff    96 Jun 19 14:40 logs
lrwxr-xr-x    1 root        staff    41 Jun 19 16:32 models -&gt; /Volumes/GopalSSD/ai_models/ollama/models
# above line means that the models directory is linked to the external drive
</code></pre>
<ol start="4">
<li>Install and Run the model.</li>
</ol>
<pre><code class="language-bash">Replace lines: 116-116
ollama run llama3
</code></pre>
<p>This will install the model at <code>/Volumes/drive/ai_models/ollama/models</code> and allow you to interact with it. Use it!</p>
<h1>Conclusion</h1>
<p>Running LLMs locally with Ollama on an external drive offers numerous benefits, including enhanced data security, reduced latency, and greater control over your AI models. By following the steps outlined in this guide, you can easily set up Ollama to use models stored on an external drive, giving you the flexibility to manage large model files without consuming your main system's storage.</p>
<p>This approach not only allows you to leverage the power of LLMs locally but also provides a scalable solution for storing and accessing multiple models. As AI continues to evolve, having a setup that allows for easy expansion and management of your model library will become increasingly valuable.</p>
<p>Remember, the key advantages of this setup include:</p>
<ul>
<li>Improved data privacy and security</li>
<li>Reduced dependency on cloud services</li>
<li>Flexibility in model selection and customization</li>
<li>Efficient use of storage resources</li>
</ul>
<p>By mastering the use of Ollama with external storage, you're well-positioned to explore and experiment with various LLMs while maintaining full control over your AI environment.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Divergent branches reconciliation]]></title>
            <link>https://gopalverma.com/diary/notes/divergent-branches-reconcile</link>
            <guid>https://gopalverma.com/diary/notes/divergent-branches-reconcile</guid>
            <pubDate>Wed, 19 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn how to reconcile divergent branches in Git, understand the causes, and choose the right strategy to update your branch.]]></description>
            <content:encoded><![CDATA[<p>When working with local and remote branches in Git, you might encounter this error when pushing or pulling from the remote (GitHub).</p>
<pre><code class="language-bash">hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
hint:
hint: You can replace &quot;git config&quot; with &quot;git config --global&quot; to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.
</code></pre>
<h1>What happened?</h1>
<ul>
<li>Your local branch and the branch on GitHub (remote branch) have different changes.</li>
<li>Git doesn't know how to combine (reconcile) these changes.</li>
</ul>
<h1>Why it matters?</h1>
<ul>
<li>You need to decide how to merge these changes so both branches are up to date.</li>
</ul>
<h1>How to fix?</h1>
<h2>1. Merge</h2>
<p>Combine changes and keep all commits (default strategy).</p>
<pre><code class="language-bash">git pull --no-rebase origin main

#or

git pull origin main
</code></pre>
<h2>2. Rebase</h2>
<p>Move your changes on top of the remote changes, creating a straight line of commits.</p>
<pre><code class="language-bash">git pull --rebase origin main
</code></pre>
<h2>3. Fast-forward</h2>
<p>Only update if there are no new local changes.</p>
<pre><code class="language-bash">git pull --ff-only origin main
</code></pre>
<h1>Summary</h1>
<p>Choose a strategy (merge, rebase, or fast-forward) to update your branch.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[MDX Hello World Showcase]]></title>
            <link>https://gopalverma.com/diary/blogs/hello-world</link>
            <guid>https://gopalverma.com/diary/blogs/hello-world</guid>
            <pubDate>Tue, 18 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[This page demonstrates various MDX components and syntax, including text formatting, links, lists, blockquotes, code blocks, tables, task lists, horizontal rules, math equations, and footnotes. It serves as a comprehensive guide to help you understand MDX parsing and its capabilities.]]></description>
            <content:encoded><![CDATA[<p>This page demonstrates various MDX components and syntax, including text formatting, links, lists, blockquotes, code blocks, tables, task lists, horizontal rules, math equations, and footnotes. It serves as a comprehensive guide to help you understand MDX parsing and its capabilities.</p>
<h1>Text Formatting</h1>
<p>You can use <em>italic</em>, <strong>bold</strong>, and <em><strong>bold italic</strong></em> text.</p>
<p>You can also use <s>strikethrough</s> and <code>inline code</code>.</p>
<h1>Links</h1>
<p>Here's a <a href="https://mdxjs.com/">link to MDX documentation</a>.</p>
<h1>Lists</h1>
<p>Unordered list:</p>
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Subitem 2.1</li>
<li>Subitem 2.2</li>
</ul>
</li>
<li>Item 3</li>
</ul>
<p>Ordered list:</p>
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
<h1>Blockquotes</h1>
<blockquote>
<p>This is a blockquote.<br>
It can span multiple lines.</p>
</blockquote>
<h1>Code Blocks</h1>
<p>Inline code: <code>console.log(&quot;Hello, MDX!&quot;);</code></p>
<p>JavaScript code block:</p>
<pre><code class="language-jsx">const greeting = &quot;Hello, MDX!&quot;;
console.log(greeting);
</code></pre>
<p>Python code block:</p>
<pre><code class="language-python">print(&quot;Hello, MDX!&quot;)
</code></pre>
<h1>Tables</h1>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Supported</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tables</td>
<td>Yes</td>
<td>This table</td>
</tr>
<tr>
<td>Code</td>
<td>Yes</td>
<td><code>code</code></td>
</tr>
<tr>
<td>Math</td>
<td>Yes</td>
<td>$E = mc^2$</td>
</tr>
</tbody>
</table>
<h1>Task Lists</h1>
<ul>
<li>[x] Learn MDX basics</li>
<li>[ ] Master advanced MDX concepts</li>
<li>[ ] Build an MDX-powered website</li>
</ul>
<h1>Horizontal Rule</h1>
<hr>
<h1>Math Equations</h1>
<p>$y = mx + b$</p>
<h1>Footnotes</h1>
<p>Here's a sentence with a footnote.[^1]</p>
<p>[^1]: This is the footnote content.</p>
<h1>Conclusion</h1>
<p>This page showcases various MDX components and syntax. Happy MDX parsing!</p>
<h1>Random Code Demo</h1>
<pre><code class="language-js">for (const el of enterElements) {
  el.classList.add('transition-enter')
  el.classList.add('transition-enter-from')
}

// Replace the children of the container with
// elements from the new code
container.replaceChildren(...newChildren)
// Force layout reflow
forceReflow()

for (const el of enterElements) {
  el.classList.remove('transition-enter-from')
  el.classList.add('transition-enter-to')
}

// Here the transition starts
// from `.transition-enter-from` to `.transition-enter-to`

for (const el of enterElements) {
  // Transition Finished
  el.addEventListener('transitionend', () =&gt; {
    el.classList.remove('transition-enter-to')
  })
}
</code></pre>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Renaming git remote]]></title>
            <link>https://gopalverma.com/diary/notes/renaming-git-remote</link>
            <guid>https://gopalverma.com/diary/notes/renaming-git-remote</guid>
            <pubDate>Sat, 01 Jun 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn how to rename an existing Git remote using simple command-line instructions. This guide covers checking your current remote name, renaming it, and verifying the change, all with clear step-by-step instructions and example outputs. ᛦ]]></description>
            <content:encoded><![CDATA[<p>Let’s say that your current remote name is “origin_1”. And now you want to change the remote name to  “origin_2”.</p>
<p><strong>1. Confirm the name of your current remote by running the following command:</strong></p>
<pre><code class="language-bash">git remote -v
</code></pre>
<p>You should see an output like the following</p>
<pre><code class="language-bash">origin_1  https://github.com/username/repository.git (fetch)
origin_1  https://github.com/username/repository.git (push)
</code></pre>
<p><strong>2. Now that the current remote name is confirmed — you can change it by running the following command:</strong></p>
<pre><code class="language-bash">git remote rename origin_1 origin_2
</code></pre>
<p>This command tells git to rename the current remote to something different. In this example, we’re changing the remote name to “origin_2”, but you can change your remote to be anything you want.</p>
<p><strong>3.  Verify that your remote has changed from “beanstalk” to “origin” by running the following command:</strong></p>
<pre><code class="language-bash">git remote -v
</code></pre>
<p>You should see an output like the following</p>
<pre><code class="language-bash">origin_2  https://github.com/username/repository.git (fetch)
origin_2  https://github.com/username/repository.git (push)
</code></pre>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[90% of devs are damn bad!]]></title>
            <link>https://gopalverma.com/diary/blogs/90pc-useless</link>
            <guid>https://gopalverma.com/diary/blogs/90pc-useless</guid>
            <pubDate>Sat, 16 Dec 2023 00:00:00 GMT</pubDate>
            <description><![CDATA[Exploring the controversial claim that 90% of programmers are subpar, this article delves into the reasons behind widespread underperformance in the field. It examines key factors such as lack of fundamental skills, overreliance on online resources, and insufficient practice. The piece also emphasizes the critical need to raise industry standards, promote continuous learning, and foster a culture of code quality to address these issues and prepare for future technological challenges.]]></description>
            <content:encoded><![CDATA[<p>Exploring the controversial claim that 90% of programmers are subpar, this article delves into the reasons behind widespread underperformance in the field. It examines key factors such as lack of fundamental skills, overreliance on online resources, and insufficient practice. The piece also emphasizes the critical need to raise industry standards, promote continuous learning, and foster a culture of code quality to address these issues and prepare for future technological challenges.</p>
<h1>Bitter Truth</h1>
<p>It's a bold statement, but one that many experienced developers would likely agree with: the majority of programmers out there are not particularly skilled or talented. While the field of software engineering has grown exponentially in recent years, the quality of code and programming ability has not kept pace.</p>
<h1>Why So Many Programmers Underperform</h1>
<p>There are a few key reasons why so many programmers fall short of expectations:</p>
<h2>1. Lack of Fundamental Skills</h2>
<p>Many programmers, especially those new to the field, lack a strong grasp of core computer science concepts like data structures, algorithms, and software design principles. They may be able to piece together working code, but their solutions are often inefficient, buggy, and difficult to maintain.</p>
<h2>2. Overreliance on Tutorials and Stack Overflow</h2>
<p>In the age of the internet, it's easy for programmers to find pre-written code snippets and solutions online. While this can be a helpful learning tool, too many developers simply copy-paste code without understanding how or why it works. This leads to a shallow knowledge base and an inability to solve novel problems.</p>
<h2>3. Insufficient Practice and Experience</h2>
<p>Programming is a skill that requires consistent, deliberate practice to master. Many programmers, however, are content to coast on the bare minimum, rarely challenging themselves with new technologies or complex projects. As a result, their skills stagnate, and they fail to develop the depth of experience needed to become truly proficient.</p>
<h1>The Importance of Raising the Bar</h1>
<p>The prevalence of mediocre programmers has serious consequences for the tech industry and the quality of software products. Poorly written code leads to bugs, security vulnerabilities, and technical debt that can haunt a project for years.</p>
<p>To address this issue, the programming community needs to raise the bar for what constitutes acceptable skill and expertise. This means:</p>
<ul>
<li>Emphasizing fundamental computer science education.</li>
<li>Encouraging continuous learning and skill development.</li>
<li>Fostering a culture of code quality, testing, and best practices.</li>
<li>Holding programmers accountable for the quality of their work.</li>
</ul>
<p>By elevating the standards of the profession, we can ensure that the next generation of developers is better equipped to tackle the complex challenges of the modern digital landscape.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
        <item>
            <title><![CDATA[Healthy life as a Developer]]></title>
            <link>https://gopalverma.com/diary/blogs/health-for-dev</link>
            <guid>https://gopalverma.com/diary/blogs/health-for-dev</guid>
            <pubDate>Wed, 13 Dec 2023 00:00:00 GMT</pubDate>
            <description><![CDATA[Prioritizing Your Health as a Software Developer. Learn about the importance of maintaining a healthy lifestyle, the risks associated with neglecting your well-being, and practical strategies to develop healthy habits that can enhance both your personal life and professional performance in the tech industry.]]></description>
            <content:encoded><![CDATA[<p>As a software developer, it's easy to get caught up in the demands of your work - long hours hunched over a computer, deadlines looming, and the constant pressure to deliver new features and updates. However, neglecting your physical and mental health can have serious consequences, both for your career and your overall well-being.</p>
<h1>The Risks of an Unhealthy Lifestyle</h1>
<p>Many software developers fall into unhealthy patterns, such as:</p>
<ul>
<li>Sitting for extended periods without breaks</li>
<li>Skipping meals or relying on unhealthy snacks</li>
<li>Irregular sleep schedules and lack of sleep</li>
<li>High stress levels and burnout</li>
<li>Minimal physical activity</li>
</ul>
<p>These behaviors can lead to a host of issues, including:</p>
<ul>
<li>Musculoskeletal problems like back pain, neck strain, and carpal tunnel syndrome</li>
<li>Weight gain and increased risk of chronic diseases like diabetes and heart disease</li>
<li>Decreased cognitive function, mood, and productivity</li>
<li>Burnout, depression, and anxiety</li>
</ul>
<p>Maintaining good health is not only important for your personal well-being, but it can also positively impact your professional performance and career trajectory.</p>
<h1>Developing Healthy Habits</h1>
<p>Fortunately, there are several steps software developers can take to prioritize their health:</p>
<ol>
<li><strong>Incorporate Regular Exercise</strong>: Even a brief daily walk or a few minutes of stretching can make a significant difference. Consider joining a gym or trying out activities like cycling, swimming, or rock climbing.</li>
<li><strong>Improve Your Posture and Ergonomics</strong>: Invest in a comfortable, adjustable chair and desk setup to minimize strain on your body. Take regular breaks to stretch and move around.</li>
<li><strong>Maintain a Balanced Diet</strong>: Avoid relying on fast food or unhealthy snacks. Incorporate more whole, nutrient-dense foods into your meals and stay hydrated throughout the day.</li>
<li><strong>Prioritize Sleep</strong>: Aim for 7-9 hours of quality sleep each night. Establish a consistent sleep routine and create a relaxing bedtime environment.</li>
<li><strong>Practice Stress Management</strong>: Experiment with techniques like meditation, yoga, or mindfulness to help manage stress and prevent burnout. Don't be afraid to take breaks or ask for help when needed.</li>
<li><strong>Schedule Regular Checkups</strong>: Make time for annual physicals, dental cleanings, and other preventive healthcare appointments to catch any issues early.</li>
</ol>
<p>By making your health a priority, you can not only improve your quality of life but also enhance your productivity, creativity, and overall job performance as a software developer.</p>
<p>Remember, taking care of yourself is not a luxury - it's a necessity for a long, fulfilling career in the tech industry.</p>
]]></content:encoded>
            <author>hi@gopalverma.com (Gopal Verma)</author>
        </item>
    </channel>
</rss>