Supervised Contrastive Learning in Python Keras

Supervised Contrastive Learning in Python Keras

When I first started training deep learning models for image classification, I often relied on the standard Cross-Entropy loss. It worked well enough, but I noticed the models struggled when the classes were visually similar. I discovered that Supervised Contrastive Learning (SupCon) is a game-changer for these scenarios. It helps the model learn to pull … Read more >>

How to Create a Stacked Bar Plot in Pandas

Create a Stacked Bar Plot in Pandas

I have found that a stacked bar plot is one of the most effective ways to visualize part-to-whole relationships. Whether I’m analyzing regional sales or tracking demographic shifts, Pandas makes it incredibly simple to generate these charts with just a few lines of code. In this tutorial, I’ll show you exactly how to build and … Read more >>

Check if a Number Is Between Two Values in Python

Checking whether a Python variable is between two numbers: the Command Prompt showing chained comparisons with inclusive and exclusive bounds

To check whether a Python variable sits between two numbers, chain the comparison the way you’d write it on paper: That’s the whole answer. Python allows low <= x <= high directly, which most languages don’t, so you rarely need and. Below I check the corners that actually bite: range(), floats, and arrays. Everything ran … Read more >>

scikit-learn accuracy_score: Usage and When It Misleads

scikit-learn accuracy_score: the Command Prompt showing a model scoring 98 percent accuracy while catching none of the fraud cases

The accuracy_score in sklearn returns the fraction of predictions that match the truth. Here’s the import and the whole call: It takes the true labels first and the predictions second. Swapping them gives the same number, so the mistake hides, but every other metric in sklearn.metrics cares about the order. Everything here ran on scikit-learn … Read more >>

PyTorch MSELoss: reduction, F.mse_loss and Shapes

PyTorch MSELoss: the Command Prompt showing the mean, sum and none reduction options side by side

nn.MSELoss is the mean squared error loss in PyTorch. It squares the gap between each prediction and its target, then averages. There’s a functional twin, F.mse_loss, that does exactly the same arithmetic without the object. Which you use is a style choice, and I’ll show why below. Runs and screenshots come from PyTorch 2.14.0, Python … Read more >>

np.add.at() in NumPy: Adding at Repeated Indices

np.add.at in NumPy: the Command Prompt showing plain fancy indexing losing duplicate indices while np.add.at counts all of them

np.add.at adds values into an array at the indices you give it, and it applies every index even when one repeats. That repetition is the entire point. Plain array[indices] += values quietly keeps only the last write for any index that appears more than once. Below I show that difference, the 2D form, and how … Read more >>

PyTorch nn.Conv2d: Parameters, Output Shape and Examples

PyTorch nn.Conv2d: the Command Prompt showing a convolution layer's input shape, output shape, weight shape and parameter count

nn.Conv2d is the 2D convolution layer in PyTorch. You give it how many channels come in, how many should go out, and how big the kernel is, and it builds the weights for you. It expects a 4D tensor shaped (batch, channels, height, width), and almost every problem people hit with it is a shape … Read more >>

Python List Comprehension If Else: Where Each One Goes

Python list comprehension if else: the Command Prompt showing labels from a conditional expression and a shorter filtered list

In a Python list comprehension, if else goes before the for, and a bare if goes after it. Get that backwards and Python raises a SyntaxError. The first one labels every item. The second one throws items away. That single difference is what most of the questions about this are really about. I ran each … Read more >>

Matplotlib Transparent Background: savefig, Patches and Legends

Matplotlib transparent background: the same chart composited onto a dark panel and a warm one, showing through both

To save a Matplotlib chart with a transparent background, pass transparent=True to savefig: That clears the figure background and the axes background in the saved file. It changes nothing on screen, which is why people think it didn’t work. Below I check every claim by reading the alpha channel back out of the saved PNG, … Read more >>

torch.cat in PyTorch: Joining Tensors Along a Dimension

torch.cat in PyTorch: the Command Prompt showing two tensors joined along dim 0 and dim 1 with the resulting shapes

torch.cat joins a sequence of tensors along a dimension that already exists. The shapes have to match everywhere except that one dimension, and the result never gains an axis. That last part is the entire difference between torch.cat and torch.stack, which does add an axis. The runs below are on PyTorch 2.14.0 on Python 3.12.5, … Read more >>