<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Aahan-Chauhan</title>
    <description>The latest articles on DEV Community by Aahan-Chauhan (@aahanchauhan).</description>
    <link>https://dev.to/aahanchauhan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4014080%2F4062f111-0b89-4de7-b384-3da4bc6a86f6.png</url>
      <title>DEV Community: Aahan-Chauhan</title>
      <link>https://dev.to/aahanchauhan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/aahanchauhan"/>
    <language>en</language>
    <item>
      <title>Attention Is Just A Weighted Average (And That's Why It's Genius)</title>
      <dc:creator>Aahan-Chauhan</dc:creator>
      <pubDate>Tue, 24 Nov 2026 09:23:17 +0000</pubDate>
      <link>https://dev.to/aahanchauhan/attention-is-just-a-weighted-average-and-thats-why-its-genius-g62</link>
      <guid>https://dev.to/aahanchauhan/attention-is-just-a-weighted-average-and-thats-why-its-genius-g62</guid>
      <description>&lt;p&gt;Every AI tool that you have used this year, from ChatGPT to speech-to-text model transcribing your voice memos, runs on the same idea: &lt;strong&gt;attention&lt;/strong&gt;. Most of these explanations jump straight into the queries, keys, values, and multi-head this-and-that without telling you &lt;em&gt;why&lt;/em&gt; anyone needed this in the first place. So lets do it another way around: start off with the problem, and let the solution show up on its own.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The Problem: Which Words Matter?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Read this sentence: The deer didn't cross the street because &lt;strong&gt;it&lt;/strong&gt; was too tired.&lt;/p&gt;

&lt;p&gt;What does "it" refer to? The animal, obviously. You figured that out instantly because your brain connected the "it" to the "animal" and completely disregarded the "street."&lt;/p&gt;

&lt;p&gt;Now change one word: The deer didn't cross the street because &lt;strong&gt;it&lt;/strong&gt; was too wide.&lt;/p&gt;

&lt;p&gt;Suddenly, "it" means the "street." It is the same sentence structure, just a completely different link. A plain neural network, like the ones from my previous post, has no good way to do this. It takes a fix set of inputs and runs the same weighted sums on them every time.  Older sequence models (RNNs) tried to fix this by reading one word at a time as they carried the "memory" forward, but that memory got blurry over long sentences, and reading slow by slow is time-taking.&lt;/p&gt;

&lt;p&gt;What we actually want is simple: &lt;strong&gt;let every word look at every other word and decide which ones matter for understanding it&lt;/strong&gt;. And this is attention.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Attention in One Sentence&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Attention is the weighted average, where the model &lt;em&gt;learns&lt;/em&gt; the weights based on what's relevant.&lt;/p&gt;

&lt;p&gt;That is basically the whole idea. You already know what a weighted average is. The only new part is that the weights are not fixed. They are computed on the fly, differently for every word from every sentence. When the model processes the "it," it assigns the weight to the animal (or "street," depending on the context) and tiny weight to the surrounding words in the sentence. Then's it blends the information from those words together, mostly from the important ones.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Queries, Keys, and Values: The Intuition&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To compute those weights, each word gets turned into three distinct vectors:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Query (Q): "What am I looking for?"&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Key (K): "What do I contain?"&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Value (V): "What information do I hand over if you pick me?"&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Think of it like searching a library. Your &lt;strong&gt;query&lt;/strong&gt; is what you type into the search bar. Every book has a &lt;strong&gt;key&lt;/strong&gt;, its title and its tags. The search compares your query against every key to see which books match the best. Then you actually read the &lt;strong&gt;value&lt;/strong&gt;, the content of the best-matching books.&lt;/p&gt;

&lt;p&gt;Now, for the word "it":&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Its query asks something like "Who is referring to me when I am a pronoun?"&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Every other word's key advertises what it is ("I'm a noun, an animal, a subject...").&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The query-key match scores are high for "animal" and low for "the."&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The model grabs a blend of the &lt;em&gt;values&lt;/em&gt;, mostly from animal."&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;All three vectors come from the same word embedding, multiplied by three different learned weigth matrices. Those matrices are what training actually adjusts.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The Math (It's Shorter Than you Think)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Step one is measuring how well each query matches each keky using a dot product. A big dot product means the vectors point in similar directions, which means "good match":&lt;/p&gt;

&lt;p&gt;score = QK^T&lt;/p&gt;

&lt;p&gt;Step two is scaling those scores down so they don't get huge (big numbers make softmax too extreme):&lt;/p&gt;

&lt;p&gt;(QK^T)/sqrt(dk) --&amp;gt; where d_k is the key vectors size.&lt;/p&gt;

&lt;p&gt;Step three is running the scores through softmax, the same function from my neural networks post, to turn them into weights between 0 and 1 that sum to 1:&lt;/p&gt;

&lt;p&gt;weights = softmax(step two)&lt;/p&gt;

&lt;p&gt;Step four is using those weights to take a weighted average of the values:&lt;/p&gt;

&lt;p&gt;Attention(Q, K, V) = (step three)V&lt;/p&gt;

&lt;p&gt;That one line is the heart of every transformer. Dot product, softmax, weighted average. There is nothing you haven't already seen!&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Attention in 10 Lines of Code&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Here's the entire mechanism in NumPy:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhz2w3geg74bjb373apaz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhz2w3geg74bjb373apaz.png" alt=" " width="800" height="452"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Each row of &lt;u&gt;weights&lt;/u&gt; shows how much one taken attends to every token in the sequence, and each row sums to 1. In a real transformer, Q, K, and V come from separate learned projections of X. Here, I'm skipping that to keep the core idea highlighted.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Multi-Head Attention, Many Perspectives at Once&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;One attention calculation captures one kind of relationship. But language has many at once: grammar, meaning, who-did-what, and what-refers-to-what.&lt;/p&gt;

&lt;p&gt;So transformers run &lt;strong&gt;multiple attention "heads"&lt;/strong&gt; in parallel, each with its own Q, K, and V matrices. One head might learn to track pronouns, another might focus on adjacent words, and another might pick up on verb-subject relationships. Their outputs get concatenated and mixed back together.&lt;/p&gt;

&lt;p&gt;It's like asking several pepole to read the same sentence, each paying attention to something different, and then combining their notes.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Building a Full Transformer&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Attention is the star, but a transformer block has a few supporting pieces:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;u&gt;Positional Encoding:&lt;/u&gt; attention itself has no sense of word order, so we add position information to each embedding. Otherwise "dog bites man" and "man bites dog" would look identical.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;u&gt;Multi-head Attention:&lt;/u&gt; the mechanism above.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;u&gt;Feed-forward Network:&lt;/u&gt; a small neural network applied to each token individually after attention.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;u&gt;Residual Connections and Layer Normalization:&lt;/u&gt; shortcuts and stabilizers that keep training smooth in deep stacks.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Stack that block as many times as you want, and you have finally got yourself a transformer. Train it with the same loop as always: forward pass, &lt;strong&gt;cross-entropy loss&lt;/strong&gt;, backpropagation, gradient descent.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Where This Shows up in Real AI&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;LLMs such as ChatGPT and Claude: transformers trained to predict the next token. The same attention mechanism lets them keep track of context across thousands of words.&lt;/p&gt;

&lt;p&gt;Image Models: vision transformers chop images into patches and dtreat them like words in a sentence.&lt;/p&gt;

&lt;p&gt;Different inputs, but the same engine.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The One-Sentence Summary&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Attention lets every piece of an input look at every other piece and learn how much to listen to each one, which is just a softmax-weighted average, and stacking that idea into transformers is what powers modern AI.&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>deeplearning</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Neural Networks: Weights, Activation, and Backpropagation</title>
      <dc:creator>Aahan-Chauhan</dc:creator>
      <pubDate>Sun, 06 Sep 2026 22:51:56 +0000</pubDate>
      <link>https://dev.to/aahanchauhan/neural-networks-weights-activation-and-backpropagation-jd6</link>
      <guid>https://dev.to/aahanchauhan/neural-networks-weights-activation-and-backpropagation-jd6</guid>
      <description>&lt;p&gt;If you've ever looked at a neural network diagram and every wondered what is actually happening in these networks, this post is just for you. I pulled this post together after researching the properties of neural networks, and writing out what is finally there to click. No analogies that lead to no explanations, just the math behind neural networks, one piece at a time.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The Simplest Possible Net——A Perceptron&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Before neural networks got keep, they started shallow. A &lt;strong&gt;perceptron&lt;/strong&gt; is a neural net with zero hidden layers, invented back in 1943. Perceptions work when data is &lt;em&gt;linearly separable&lt;/em&gt;, meaning you could draw a line and cleanly split the classes on either side of it.&lt;/p&gt;

&lt;p&gt;Let's take a simple example with an equation: D=y-2x-3. Everything where D&amp;gt;=0 is Class 1 and everything where D&amp;lt;0 is Class 2. This is basically how a model works: a single linear boundary that decides which side the example falls on.&lt;/p&gt;

&lt;p&gt;However, real data is rarely this cooperative. The moment your classes tangle in a way no straight line can separate, you will need more than one layer. This is really where the deep learning begins.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What A Neuron is Actually Computing&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Zoom into any single neuron in a network, and this is what entire computation occuring inside of it: &lt;/p&gt;

&lt;p&gt;S = b∑ w_i * x_i&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;x_i are the inputs coming in, such as the pixel values and whatever your data is.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;w_i are the weights (how much the network currently believes each input matters.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;b is the bias that acts like a nudge that shifts the output independent of the inputs.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;S is the logit, which is a unbounded value. The S value either shoots in the negative or positive direction indefinetely.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Stack raw logits like this across layers with nothing else added, and the whole network has a mathematical collapse into a linear function. Depth alone buys you nothing. You need a twist.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The Non-Linear Twist That Makes Depth Matter&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;That very twist is the activiation function. This is applied to every logit before it moves onto the next layer.  One of them is sigmoid: &lt;/p&gt;

&lt;p&gt;ø(S) = 1 / (1+e)^-s&lt;/p&gt;

&lt;p&gt;Just as the equation says, the ø(s) pushes the S value closest to 1 as the ø(s) value is positive. If ø(s) is negative, then the S value moves towards 0.&lt;/p&gt;

&lt;p&gt;This nonlinearity is the backbone of how depth works.  With nonlinearity, each added layer can fold the decision boundary into complex shapes, which is exactly what is required to separate tangled data.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Stacking Neurons into Layers&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;layer&lt;/strong&gt; is just a bank of neurons, each computing its own weighted sum form the same inputs, and each with its own weights. The formula goes like this: &lt;/p&gt;

&lt;p&gt;z_i​ = ϕ (j∑​ x_j * ​w_ij​)&lt;/p&gt;

&lt;p&gt;The middle layers are called the &lt;strong&gt;hidden&lt;/strong&gt; layers. They are called hidden layers because the values are not directly obseved; only the input and the output (final value) are observed. The early layers tend to pick up the simple patterns while the deeper layers form abstract connection with the simple patterns made by the early layers.&lt;/p&gt;

&lt;p&gt;The final output layer turns those hidden features into a prediction: &lt;/p&gt;

&lt;p&gt;y_i ​= ϕ(j∑​ z_j​ * w_ij​)&lt;/p&gt;

&lt;p&gt;For a K-way classification, the K output neurons are used. These neurons are used as one confidence score per class. &lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Softmax: Turning Raw Scores into Real Probabilities&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Say that the output layer displays three logits: (0.01, -3.8, 4.2). These numbers are all currently unbounded and do not hold any significant meaning at the moment. Softmax fixes this by taking any of those three logits and converting them into probabilities between 0 and 1 that sum up to exactly 1.0. The formula for softmax is: &lt;/p&gt;

&lt;p&gt;p_j = (e^z_j) / (∑_k * e^zk)​​&lt;/p&gt;

&lt;p&gt;In the example above, the 4.2 value would come out closer to a 90% or higher confidence score, while -3.8 will approach closer to 0, a lower confidence score.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Loss Functions: Scoring the Damage&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;One the network makes a prediction, there must be a way to measure how inaccurate it was. For the numerical predictions, it is normally considered the &lt;strong&gt;Mean Squared Error&lt;/strong&gt;. For classification, it is almost always &lt;strong&gt;Cross-Entropy&lt;/strong&gt;. This is how the formula goes:&lt;/p&gt;

&lt;p&gt;CE = -n∑i=1 [y_i * log(p(yi​)) + (1-yi) * log(1-p(yi))]&lt;/p&gt;

&lt;p&gt;The intuition is quite simple: if the true label is 1 and the model confidently predicts closer to the O, the log term blows up and there are severe penalties. However, if the model was &lt;em&gt;correct&lt;/em&gt;, the penalty shrinks towards zero. Cross-entropy rewards confident correctness and punishes the confident mistakes. This is exactly what you want out of a loss function.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What the Network Actually Learns: Backdrops and Gradient Descent&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Here's the loop that turns a "useless" network into a "useful" network:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Feed a batch of training samples through the network.&lt;/li&gt;
&lt;li&gt;Compute the predictions as the output layer.&lt;/li&gt;
&lt;li&gt;Measure losses and how inaccurate the predictions were.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Backpropagate&lt;/strong&gt; the error backwards through every layer so you can calculate the weight contributed to the error.&lt;/li&gt;
&lt;li&gt;Nudge every weight slightly in the direction that reduces the layer.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That fifth step is called the &lt;strong&gt;gradient descent&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;(w_ij)^new = w_ij - α * (∂E​) / (∂w_ij)&lt;/p&gt;

&lt;p&gt;α holds the &lt;strong&gt;learning rate&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Just picture the loss as a landscape. Training is descending that landscape, one gradient-calculated step at a time, trying to reach a low point. In a network with millions of billions of weights, that landscape has many dimensions with multiple valleys. This is part of why training is not guaranteed to find the &lt;em&gt;global&lt;/em&gt; best solution, just a good one.&lt;/p&gt;

&lt;p&gt;One pass through the &lt;em&gt;entire&lt;/em&gt; training is called an &lt;strong&gt;epoch&lt;/strong&gt;. Networks are trained across many epochs because each pass leaves weights in a sligtly different place. This is why seeing the same data again isn't wasted effort.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Watching It Happen Through a PyTorch Example&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Due to restrictions, the code commensts will be in []. Here's a real and complete neural network trained on MNIST in PyTorch.&lt;/p&gt;

&lt;p&gt;import torch&lt;br&gt;
import torch.nn as nn&lt;br&gt;
import torch.optim as optim&lt;br&gt;
from torchvision import datasets, transforms&lt;/p&gt;

&lt;p&gt;[Load Data]&lt;br&gt;
convertToTensor = transforms.ToTensor()&lt;br&gt;
train_data = datasets.MNIST(root='./data', train=True, download=True, transform=convertToTensor)&lt;br&gt;
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)&lt;/p&gt;

&lt;p&gt;[Define the network: 784 input pixels -&amp;gt; 128 hidden neurons -&amp;gt; 10 output classes]&lt;br&gt;
model = nn.Sequential(&lt;br&gt;
    nn.Flatten(),&lt;br&gt;
    nn.Linear(28*28, 128),&lt;br&gt;
    nn.ReLU(),&lt;br&gt;
    nn.Linear(128, 10)&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;criterion = nn.CrossEntropyLoss()&lt;br&gt;
optimizer = optim.SGD(model.parameters(), lr=0.01)&lt;/p&gt;

&lt;p&gt;[Train]&lt;br&gt;
for epoch in range(5):&lt;br&gt;
    for images, labels in train_loader:&lt;br&gt;
        optimizer.zero_grad()&lt;br&gt;
        predictedLabels = model(images)&lt;br&gt;
        loss = criterion(predictedLabels, labels)&lt;br&gt;
        loss.backward()&lt;br&gt;
        optimizer.step()&lt;br&gt;
    print(f"Epoch {epoch}, Loss: {loss.item():.4f}")&lt;/p&gt;

&lt;p&gt;Every concept from this post is sitting amongst these lines of code: nn.linear is the weighted sum, nn.reLU is the activation function, criterion computers cross-entropy loss, loss.backward() runs backpropagation, and optimizer.step() is the gradient descent update. This is basically just theory executed.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The One-Sentence Summary&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;A neural network is a stack of weighted sums broken up by non-linear activations, trained by repeatedly measuring how wrong its predictions are and nudging every weight a tiny bit in the direction that makes it less wrong — and that exact loop, scaled up, is what's running behind every AI tool you've ever used.&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>beginners</category>
      <category>deeplearning</category>
      <category>pytorch</category>
    </item>
    <item>
      <title>Entropy and Cross-Entropy, Explained</title>
      <dc:creator>Aahan-Chauhan</dc:creator>
      <pubDate>Tue, 25 Aug 2026 23:43:19 +0000</pubDate>
      <link>https://dev.to/aahanchauhan/entropy-and-cross-entropy-explained-f3m</link>
      <guid>https://dev.to/aahanchauhan/entropy-and-cross-entropy-explained-f3m</guid>
      <description>&lt;p&gt;If you've spent any time around machine learning the familiarizing yourself with the concept, you have seen the term "entropy" and "cross entropy" show up everywhere. These two distinct terms often show up in topics regarding: classification models, neural networks, and understanding language models. But if you are like me a few weeks ago, you would not be able to write down the formulas without &lt;em&gt;feeling&lt;/em&gt; the meaning of these terms.&lt;/p&gt;

&lt;p&gt;This post is my attempt to build this intuition of yours from the ground up. This blog will cover topics ranging from entropy to cross-entropy. As you read this post, these topics will finally connect to why they are the loss functions of choice in machine learning.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;PART 1: What Entropy Actually Measures&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Forget about the neural networks for a second. Entropy comes from the information theory and, at its core, it answers one main question: How surprised should you be by the outcome of a random event?&lt;/p&gt;

&lt;p&gt;Now let's image two coins:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Coin A is fair with 50% heads and 50% tails.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Coin B is rigged with 99% head and 1% tails.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If I flip Coin B and tell you the result, you will almost never be surprised if the outcome is heads. However, if I flip Coin A, you will have no idea what is coming. This is because every flip of Coin A is a genuine mystery that is only uncovered once the coin is flipped.&lt;/p&gt;

&lt;p&gt;Entropy is a formal way of measuring this same "amount of surprise." A fair coin like Coin A has high entropy (maximum uncertainity) while a rigged coin like Coin B has low entropy (easily predictable). &lt;/p&gt;

&lt;p&gt;Mathematically, the entropy for a probabilitiy distribution is: &lt;em&gt;H(P)=−x∑​p(x)log(p(x))&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Now, lets unpack this formula and understand &lt;em&gt;why&lt;/em&gt; it makes sense.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;log(p(x)) basically represents the "surprise." Rare events—small p(x)—have a more negative log value, meaning higher surprise rates. Common events—large p(x)—have log values that are closer to 0, meaning lower surprise rates.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The negative sign flips to a positive sign, knows as a surprise score, since the probabilities are between 0 and 1 with the log being a negative.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Multiplying by the p(x) value and summing it up gives you the expected value of the surprise. The expected value of surprise is the average surprise you'd experience sampling from this distribution over and over.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So basically: Entropy is the average amount of "surprise" backed into a distribution.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Part 2: From Entropy to Cross-Entropy&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Entropy already assumes that you &lt;em&gt;know&lt;/em&gt; the true distribution of the outcomes. However, in machine learning, we rarely know the true distribution. We are trying to &lt;em&gt;predict&lt;/em&gt; the distribution.&lt;/p&gt;

&lt;p&gt;Here is the mathematical definition of cross-entropy: &lt;em&gt;H(P,Q)=−x∑​p(x)log(q(x))&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;This is where cross-entropy plays a major role. It measures the surprise you experience when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;true&lt;/em&gt; outcomes come from distribution P (considered the actual label of an image).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;But you are using a &lt;em&gt;predicted&lt;/em&gt; distribution Q (your model's guess) to measure that particular surpise.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Notice the subtle but crucial difference from entropy: we still weight by the &lt;em&gt;true&lt;/em&gt; probabilitiy p(x), but we take the log of the &lt;em&gt;predicted&lt;/em&gt; probability q(x).&lt;/p&gt;

&lt;p&gt;Here is the intuition: if your model's predicted distribution Q is close to the true distribution P, then the cross-entropy will be low while the actual entropy is close to P. However, if the model is confidently wrong, the log term completely explodes and the cross-entropy shoots up.&lt;/p&gt;

&lt;p&gt;This is exactly something what we want in a loss function:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Confident and correct predictions are low loss.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Confident and high predictions are high loss.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Uncertain predictions are the moderate losses.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Part 3: Why Does This Matter For Neural Networks?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;When a classifier is trained, the model puts out a probability distribution over classes. Cross-entropy loss compares that predicted distribution against the true label, usually a one-hot vector.&lt;/p&gt;

&lt;p&gt;Since the true label is one-hot, the formula is properely simplified as almost every term in the sum becomes zero except for the one corresponding to the correct class. The equation goes like: Loss = -log(q(correct class)).&lt;/p&gt;

&lt;p&gt;During the training, the model is just trying to push the predicted probability of the &lt;em&gt;correct&lt;/em&gt; class as close to the value 1 as possible. This is because -log(1)=0 and -log(x) has x approaching 0.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;I am a high school senior that is interested in learning ML from the ground up and this is one of the first concepts that I have thoroughly researched in detail. I hope this blog was helpful to other students and adults like me that have a fond interest in ML.&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>beginners</category>
      <category>informationtheory</category>
      <category>deeplearning</category>
    </item>
  </channel>
</rss>
