Zero Labs
Industry News / AI

How Does a Neural Network Learn? Neurons, Activation Functions and Loss

Source · Towards AI By Sanika Tare

From the publisher’s feed, collected in the ZeroLabs newsroom.

A neural network starts from a surprisingly simple idea:Take some numbers, multiply them by weights, add a bias, and transform the result.That is it.But when you put thousands or millions of these operations together, and let the network adjust its weights based on its mistakes, something much more powerful appears.In Part 1 we built the big picture of Deep Learning. Now we go one level deeper and look at three ideas that everything else depends on:1. Neurons2. Activation functions3. Loss functionsOnce these three click, the rest of Deep Learning becomes much easier to follow.What you will take away from this article• How an artificial neuron combines inputs, weights, and a bias• Why a weighted sum alone is not enough, and what non-linearity fixes• How Sigmoid, Tanh, ReLU, and Leaky ReLU behave, and where each one struggles• How a layer of neurons produces a prediction, and how Softmax turns scores into probabilities• How Mean Squared Error and Cross-Entropy measure mistakes• How neuron, activation, prediction, and loss fit together in one pipelineWhere the Idea Comes FromThe artificial neuron is loosely inspired by the nerve cells in the brain, so it is worth a quick look at the original.A biological neuron is a natural nerve cell that passes along electrochemical signals. Dendrites receive signals from other neurons. The cell body (the soma) processes the signal. The axon sends the processed signal on to the next cells. Neurons also strengthen or weaken their connections based on learning, which makes the whole system adaptable and distributed.An artificial neuron borrows that structure as a mathematical model. It takes numeric inputs, multiplies each by a weight, sums everything up, applies an activation function, and passes the result on to the next layer of neurons.Figure 1: The biological neuron and the artificial neuron follow a similar pattern.Anatomy of an Artificial NeuronThe artificial neuron is the basic building block of a neural network. It receives several inputs, and each input has a weight attached to it. The neuron combines everything, adds a bias, and passes the result through an activation function.Let’s take it apart piece by piece.InputsInputs are the information we give the neuron. Suppose we want to predict how well a student will perform:x₁ = hours studiedx₂ = attendancex₃ = previous scoreIn an image problem, the inputs would be pixel values. In a language problem, they would be numerical representations of words or tokens. The common thread is that neural networks work with numerical data.WeightsEach input is multiplied by its own weight, because different inputs can influence the output by different amounts. If the input is 5 and the weight is 0.8, then:A larger weight means that input contributes more. During training these weights are adjusted, which is one of the main ways the network learns.BiasThe bias is one more adjustable number, added after the weighted inputs. It gives the neuron an extra parameter to tune, so it is not limited to using the weighted inputs alone. A neuron is not just “weighted inputs.” It is “weighted inputs plus bias.”The Weighted SumPut those pieces together and we get the neuron’s core calculation:In plain words: multiply each input xᵢ by its weight wᵢ, add all those products together, and then add the bias b. The result, z, is the weighted sum.Here it is with real numbers. Take three inputs, three weights, and a bias:• Inputs: x = [2, 3, 4]• Weights: w = [0.5, 0.2, 0.1]• Bias: b = 1Now the same thing in Python:def neuron(x, w, b):z = sum(xi * wi for xi, wi in zip(x, w)) + breturn zx = [2, 3, 4]w = [0.5, 0.2, 0.1]b = 1output = neuron(x, w, b)print(round(output, 2))Output:3.0The function pairs each input with its weight, multiplies each pair, adds up the results, and then adds the bias. The round call just tidies up tiny floating-point noise so the printed answer matches our hand calculation.A short detour: the perceptronHistorically, the simplest version of this idea is the perceptron. It computes the same weighted sum, but then makes a hard yes-or-no decision: if the sum reaches a threshold, the output is 1, otherwise it is 0.A perceptron works well on linearly separable data, meaning data where a straight line (or flat boundary) can split one class from another. Real problems are rarely that tidy, and that is exactly where the story turns. Networks built from many layers of neurons, known as multi-layer perceptrons (MLPs), can learn non-linear patterns. To see why that is possible, we need to understand what goes wrong with a plain weighted sum.Why Isn’t a Weighted Sum Enough?Imagine every neuron in a network only computed a weighted sum, and we stacked many layers on top of each other. What would we get?Surprisingly, the entire network would still behave like one single linear transformation. All those layers would collapse into something no more expressive than a single layer.That is a serious limitation. Real-world data, such as images, language, and speech, is full of complicated, non-linear patterns, and a purely linear model cannot capture them.So we need something that breaks the linearity. This is where activation functions enter the picture. After computing z, the neuron passes it through an activation function f:An activation function decides whether, and how strongly, a neuron should “fire”. More importantly, it introduces non-linearity, which is what allows a network to learn complex patterns and gives the model its flexibility. Here are four common ones.SigmoidSigmoid is one of the classic activation functions:It is differentiable, and it squashes any input into a value between 0 and 1. A large negative number gives something close to 0, zero gives exactly 0.5, and a large positive number gives something close to 1.Because the output sits between 0 and 1, sigmoid is handy when we want a result that behaves like a probability:0.05 → low probability0.50 → uncertain0.95 → high probabilityBut there is a catch. When the input is very large or very negative, the curve becomes almost flat, and the gradient (the signal used for learning) becomes tiny. This is the vanishing gradient problem. It matters a lot when training deep networks, and we will come back to it when we talk about backpropagation.TanhTanh has a similar S-shape but a different range:Its output lies between −1 and 1. Negative inputs give negative outputs, zero gives zero, and positive inputs give positive outputs.The big difference from sigmoid is that tanh is symmetric around the origin. Its gradients are stronger, which generally helps learning move faster. However, the gradients still become small at the extremes, so tanh can suffer from vanishing gradients too.ReLUNow for one of the most widely used activation functions: ReLU, short for Rectified Linear Unit.The rule is simple. If the input is negative, the output is 0. If the input is positive, the output is the input itself:ReLU(-5) = 0ReLU(-2) = 0ReLU(0) = 0ReLU(3) = 3ReLU(8) = 8In Python:def relu(x):return max(0, x)This returns whichever is larger: zero or the input. That is the entire activation.We can now upgrade our neuron so it applies ReLU to the weighted sum:def neuron(x, w, b):z = sum(xi * wi for xi, wi in zip(x, w)) + breturn relu(z)The neuron first computes z exactly as before, then passes it through ReLU. With our earlier numbers, z = 3, so the output stays 3. A negative z would have been turned into 0.ReLU is simple, fast, and has a gradient of 1 for positive inputs. But it has a weakness. Because it outputs exactly zero for every negative input, some neurons can get stuck producing zero and stop contributing to learning. These are often called dead neurons.Leaky ReLULeaky ReLU is a small fix for that problem. Instead of cutting negative inputs to zero, it lets a little through:Here α (alpha) is a small positive number, such as 0.01.def leaky_relu(x, alpha=0.01):return x if x > 0 else alpha * xFor positive values it returns the input unchanged. For negative values it returns a tiny fraction of the input instead of zero. That small non-zero signal keeps neurons from going completely inactive, helps gradients keep flowing in backpropagation, and makes training faster and more stable.Comparing the Activation FunctionsFunctionOutput rangeMain ideaWatch out forSigmoid0 to 1Probability-like outputVanishing gradientsTanh−1 to 1Symmetric around zero, stronger gradientsVanishing gradientsReLU0 to ∞Simple, fast, widely usedDead neuronsLeaky ReLUNegative values allowed, up to ∞Keeps a small signal for negative inputsSlightly more to configureNo single activation function is automatically right for every situation. ReLU and its variants are a very common choice inside hidden layers, while sigmoid and softmax tend to appear at the output when we need probabilities. The best choice ultimately depends on the architecture and the task.From Neurons to LayersOnce a neuron produces its output, that output can become an input to other neurons. This is how layers form:Input Layer → Hidden Layer 1 → Hidden Layer 2 → Output LayerA layer is just several neurons that all look at the same inputs, each with its own weights and bias. Here is a small layer of two neurons, both using ReLU:def layer(x, weights, biases):return [relu(sum(xi * wi for xi, wi in zip(x, w)) + b)for w, b in zip(weights, biases)]x = [2, 3, 4]weights = [[0.5, 0.2, 0.1],[-0.4, 0.3, 0.2]]biases = [1, -2]out = layer(x, weights, biases)print([round(o, 2) for o in out])Output:[3.0, 0]The first neuron reuses our earlier numbers and produces 3. The second neuron’s weighted sum works out to −1.1, so ReLU switches it off and outputs 0. The two neurons look at identical inputs yet respond differently, because their weights differ. That difference is exactly what lets a layer pick up different patterns.In compact mathematical form, a whole layer can be written as:Here W is the collection of all weights in the layer (one row per neuron), x is the input vector, b holds the biases, and f is applied to every neuron’s result. Each layer transforms the representation it receives from the previous one. With enough layers and the right training, a network can learn very complicated patterns.How a Network Produces a PredictionImagine a classifier looking at an image and choosing between cat, dog, and bird. The last layer produces one raw score per class. Those raw scores are not yet probabilities, and they can be any real numbers. Softmax converts them into probabilities that are never negative and add up to 1.Each score z is turned into an exponential, and then divided by the total of all the exponentials. The exponential guarantees the outputs are positive, and dividing by the total makes them a proper distribution.import mathdef softmax(scores):exps = [math.exp(s) for s in scores]total = sum(exps)return [e / total for e in exps]print([round(p, 2) for p in softmax([4.0, 1.45, 0.6])])Output:[0.9, 0.07, 0.03]The code exponentiates each score, sums them, and divides each one by the total. The network’s prediction would be “Cat”, with a probability of 0.90. But how do we know whether that prediction is any good?What Is a Loss Function?We need a way to compare the prediction with the correct answer, and that is the loss function’s job.Suppose the correct answer is 1. If the model predicts 0.2, it is far off. If it predicts 0.95, it is much closer. The loss function turns that difference into a single number that captures how well the network is doing:Good prediction → small lossBad prediction → large lossTraining is then a matter of adjusting the parameters to make that number smaller. Two loss functions appear again and again, so they are worth knowing.Squared Error and MSEThe first is squared error:Squared Error=(yactual−ypredicted)2\text{Squared Error} = (y_{\text{actual}} — y_{\text{predicted}})²Here, yactualy_{\text{actual}} is the true target, and ypredictedy_{\text{predicted}} is what the model produced.Squaring the difference makes every error positive, and it punishes big mistakes more heavily than small ones.With an actual value of 1 and a prediction of 0.2:(1−0.2)2=0.82=0.64(1–0.2)² = 0.8² = 0.64Now suppose training improves the prediction to 0.8:(1−0.8)2=0.22=0.04(1–0.8)² = 0.2² = 0.04The prediction got better, and the loss dropped from 0.64 to 0.04.In Python:def squared_error(y_actual, y_pred): return (y_actual - y_pred) ** 2print(round(squared_error(1, 0.2), 2))print(round(squared_error(1, 0.8), 2))Output:0.640.04The function subtracts the prediction from the true value and squares the result. Calling it twice shows the same drop we calculated by hand.Mean Squared Error (MSE)When you average the squared errors over many training examples, you get Mean Squared Error (MSE):MSE=1n∑i=1n(yi−y^i)2MSE = \frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y}_i)²MSE is a natural fit for predicting numeric values, especially when large errors are unacceptable.Cross-EntropyFor classification, the usual choice is cross-entropy.It measures how much the predicted probabilities differ from the true distribution, and it comes in binary and multiclass forms.For a single example, it boils down to looking at the probability the model gave to the correct class:Cross-Entropy=−log⁡(ptrue)\text{Cross-Entropy} = -\log(p_{\text{true}})If the model gives the correct class a high probability, the loss is small.If it gives the correct class a low probability, the loss becomes large.In Python:import mathdef cross_entropy(p_true): return -math.log(p_true)print(round(cross_entropy(0.90), 3))print(round(cross_entropy(0.20), 3))Output:0.1051.609Giving the right answer 90% probability costs only 0.105.Giving it 20% probability costs about 1.609, roughly fifteen times more.Confident, correct predictions are rewarded, while uncertain or wrong ones are penalized.Why Does Loss Matter So Much?A neural network cannot tell on its own whether its prediction is good.The loss function gives it a measurable objective.Without a loss, there would be no clear signal telling the model how to improve.With a loss function, training becomes a clear goal:High Loss → Weight Updates → Lower Loss → Better PredictionsThat is why the loss function sits at the center of Deep Learning.Putting It All TogetherNow we can connect the pieces.The complete journey looks like this:Input → Neural Network → Prediction → Loss Calculation → Weight Updates → Better PredictionThe model makes a prediction, compares it with the actual answer using a loss function, and then adjusts its weights to reduce the loss.For regression, we commonly use Squared Error or MSE.For classification, we commonly use Cross-Entropy.The overall goal of training is simple:Minimize Loss→Improve Predictions\boxed{\text{Minimize Loss} \rightarrow \text{Improve Predictions}}1. Inputs enter a neuron.2. Each input is multiplied by its weight.3. The products are summed and the bias is added, giving z.4. An activation function transforms z.5. The output flows to the next layer, and eventually becomes a prediction.6. A loss function compares the prediction with the true answer.7. The loss produces an error signal.In compact form: A useful mental model is to think of a neural network in three stages:• Transform: neurons combine inputs using weights and biases.• Activate: activation functions add non-linearity.• Measure: the loss tells us how far the prediction is from the target.And these lead to a fourth stage: Learn.Common QuestionsWhy not skip the activation function?Without it, stacked layers collapse into a single linear transformation, so depth adds nothing. Non-linearity is what makes deep networks expressive.Why does a neuron need a bias?It is an extra adjustable parameter. Without it, the neuron’s output would depend only on the weighted inputs, which limits what it can represent.Are weights and biases the only things the network learns?In the networks we have described so far, yes. Together they are the parameters that training adjusts.How Does a Neural Network Learn? Neurons, Activation Functions and Loss was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.