Zero Labs
Industry News / AI

Improving Deep Neural Learning Networks (Part 1): Practical Approaches and Applications to LLMs

Source · Towards AI By Amelia Nguyen

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

From foundational Deep Learning training techniques to the algorithms powering modern Agentic AI.As you probably already know, Artificial Intelligence is becoming the new Internet, or the new electricity, as many people are saying. And of course, the foundation behind AI that is rising rapidly and driving a lot of these development is Deep Learning. Deep Learning has quietly become the engine behind almost every major AI breakthrough of the past decade, from the face recognition system to the LLMs and modern Agentic AI that are currently bringing a revolution to the world. Yet, implementing a well-established Deep Neural Learning Networks that acquires high training reliability, good generalization, and fast convergence could be challenging. This series, Improving Deep Neural Learning Networks, aims to close that gaps, and throughout, draws a direct line from the fundamentals to how they operate at scale inside today’s LLMs and agentic systems.The series has 4 parts:Part 1: Practical Aspects ImprovementsPart 2: Optimization AlgorithmsPart 3: Hyperparameter Tuning, Batch Normalization & FrameworksPart 4: From Deep Neural Networks to LLMs and Agentic AIThis series builds on the Deep Learning Specialization curriculum developed by Dr. Andrew Ng at DeepLearning.AI with limited direct references from the course’s materials, extended with additional research and practical insights of my own.Let’s get into Part 1: Practical Aspects Improvements!1. Machine Learning Application Set UpTrain/ Dev/ TestWhen training a deep network, typically, we split the data into 3 distinct sets:Training set: where the model learn from, used to optimize the weights through gradient descent.Dev set (or Cross Validation set): is used to evaluate and compare models during development, including hyperparameters, selecting architectures, and making design decisions. Briefly, this set will influence your decisions.Test set: will only touched once at the very end to give an unbiased estimate of how the final model will perform on real-world data. If the test set is evaluated repeatedly, it would generate optimistic estimates that harm your decision.In some set-up, there can be only 2 sets: training and dev sets.Key rules:Dev and test sets must come from the same distribution. It doesn’t matter as much if your training set includes data from slightly different sources, but if dev and test diverge in distribution, you’re optimizing for the wrong target.For example, if the examples in dev set is images from Internet, while test set is user-uploaded images, the performance would not be great.Size: at large scale, absolute size matters more than percentage, i.e. 10,000 examples in your dev set is more than enough to reliably compare models, so there’s no reason to withhold more from training.Typical split set up:- Dataset Size = ~1000 => 60/20/20- Dataset Size = ~ 1000000+ => 98/1/11.2. Bias/VarianceBias: high bias ~ underfitting (high training error)Variance: high variance ~ overfitting (high dev set error)We usually heard of bias/variance tradeoff concept in Machine Learning, i.e. as model becomes more flexible (with more parameters), bias will decrease and variance will increase. However, the tradeoff is less rigid, and less of a popular concept in Deep Learning, as we can achieve both high bias and high variance, or both low bias and low variance simultaneously with larger networks and proper regularization. This is one of the core reasons deep learning has been so effective.1.3. Basic recipe for machine learningSource: Image by the authorThe practical workflow is to fix bias first, then address variance, because a model that can’t even fit the training data well has no hope of generalizing.Step 1: Does your model have high bias? Check your training set performance. If the model can’t even fit the training data well, try:Bigger network (more layers, more units)Train longer: never hurts, but doesn’t always helpDifferent architectureKeep iterating until training error is acceptable.Step 2: Does your model have high variance? Check the gap between train and dev error. If the model fails to generalize, try:Get more dataRegularizationDifferent architecture2. Regularization2.1. Dropout RegularizationThis regularization helps with overfitting. Dropout acts as a regularizer by adding noise to the learning process, similar to L1/L2 weight penalties but more powerful in deep networks. The intuition is: Can’t rely on any one feature, so we have to spread out weights.During training, dropout randomly “turns off” a percentage of neurons in a layer on each forward pass, typically 20–50% of them. Those neurons don’t contribute to the output and don’t get their weights updated for that round. This happens randomly and differently on every training step. When neurons can’t rely on their neighbors always being there, each one is forced to learn independently useful features rather than co-adapting with specific other neurons. The result is a more robust network where knowledge is distributed, not concentrated.Implement: At each training step, every neuron is kept with probability keep_prob and zeroed out with probability 1 - keep_prob.Mathematically explained: # 1. Each activation is multiplied by a Bernoulli random variableã = a * d, where d ~ Bernoulli(keep_prob)# 2. Then the surviving neurons scale up to preserve the expected value of the activationã = (a * d) / keep_prob# Ensure:E[ã] = keep_prob * (a / keep_prob) + (1 - keep_prob) * 0 = aimport torchimport torch.nn as nnclass NetworkWithDropout(nn.Module): def __init__(self, input_size, hidden_size, output_size, keep_prob=0.8): super().__init__() self.network = nn.Sequential( nn.Linear(input_size, hidden_size), nn.ReLU(), nn.Dropout(p=1 - keep_prob), # PyTorch takes drop prob, not keep prob nn.Linear(hidden_size, hidden_size), nn.ReLU(), nn.Dropout(p=1 - keep_prob), nn.Linear(hidden_size, output_size) # no dropout on output layer ) def forward(self, x): return self.network(x)model = NetworkWithDropout(input_size=784, hidden_size=256, output_size=10, keep_prob=0.8)# PyTorch handles train vs eval mode automaticallymodel.train() # dropout activemodel.eval() # dropout disabled - full network usedWith dropout rate p = 0.5, we are essentially training 2ⁿ different "thinned" networks that all share weights. At inference time, you use the full network — which acts like an ensemble of all those smaller networks averaged together.Caveats: Dropout may not be a good methods in these cases:Small Networks/ Limited data (underfitting network)Convolutional Layers: because neighboring pixels are spatially correlated -> use Batch Normalization as regularization.Recurrent Neural Networks: Naive dropout applied to recurrent connections destroys the memory the network is trying to maintain across time steps. Dropping hidden states randomly breaks the temporal signal entirely. Variational Dropout can be considered in this case instead.Batch Normalization is already used.Transformers & Modern Architectures (BERT, GPT, etc.) use dropout sparingly and often find that weight decay + large data is sufficient regularization. At very large scale, the data itself is the regularizer — the model can’t really overfit when trained on billions of examples.2.2. Other Regularization MethodsData Augmentation: Getting new data by augmenting existing examples. E.g: rotating, flipping or zooming in/out numbers/ images,..Early Stopping: Early stopping halts training at the point where dev set error stops improving, before the model transitions from learning genuine patterns to memorizing the training data. The weights from that optimal iteration are kept rather than the final ones. Its appeal is simplicity, no architecture changes, no additional hyperparameters. Its main criticism is that it couples two separate concerns into one decision: optimizing the cost function and controlling overfitting, which L2 or dropout handle independently. Despite this, it remains widely used for how little it costs to implement.Source: Image by the author3. Optimization Problem Set Up3.1. Input NormalizationInput normalization is the process of rescaling your input features so they share a consistent range and distribution before being fed into the network. It’s done in two steps:Subtract the mean to center the data around zero2. Divide by the variance to standardize the spread.The same mean and variance computed on the training set must be applied to the dev and test sets: you never recompute them on new data. The motivation is purely geometric: when features are on wildly different scales, the loss landscape becomes an elongated narrow bowl where gradient descent zigzags inefficiently and requires a very small learning rate to stay stable. Normalizing transforms that into a roughly spherical bowl where gradient descent can take more direct steps toward the minimum, converging faster and more reliably with a larger learning rate.3.2. Vanishing/Exploding GradientsRecalling the backpropagation concept: When a network makes an error, it corrects itself by sending an error signal backward through the layers: from output to input. Each layer uses this signal (the gradient) to adjust its weights. The problem is what happens to that signal as it travels through many layers.Following the chain rule problem: Each time the gradient passes backward through a layer, it gets multiplied by the weights of that layer. In a deep network with, say, 50 layers, that’s 50 multiplications in a chain. This results in two extreme scenarios:Vanishing Gradients: If the weights are small (values By the time the signal reaches the early layers, it’s essentially zero. Those layers stop learning — their weights barely move. The network only really trains its last few layers, wasting most of its depth.Exploding Gradients: The opposite: if weights are large (values > 1), repeated multiplication makes the gradient grow exponentially: 2 × 2 × 2 × … × 2 (50 times) = 1,125,899,906,842,624. Now weight updates are enormous and erratic. The network wildly overshoots, and loss becomes NaN. The training eventually fails. This can be more common in RNNs that process long sequences, where the same weights are multiplied many times through time steps.Common solutions:Vanishing Gradients: RELU activation (gradient is 1 for positive inputs, never squashed), ResNets for residual connection (skip connections let gradients flow directly), He or Xavier for better weight initialization, Batch Normalization ( keeps activations in a well-behaved range each layer), and LSTM/GRU for RNNs to control how much gradient flows through time.Exploding Gradients: Batch Normalization, Gradient clipping (caps the gradient magnitude), LSTM/GRU for RNNs.3.3. Weight InitializationWeight initialization is the process of setting the initial values of the weight matrices before training begins. It sounds like a minor detail but it directly determines whether your network trains successfully or immediately runs into vanishing or exploding gradients. At the start of training, the network performs a forward pass through potentially dozens of layers. Each layer multiplies its input by a weight matrix. If those weights are even slightly too large, activations explode exponentially through the layers. If slightly too small, they vanish to zero. Either way, gradients in backpropagation suffer the same fate, and the network fails to learn. That also explains why zero initialization for weight fail - every neuron will compute the same output, receive the same gradient and update the same!Intuition: For a neuron with n inputs, you want the variance of the output to roughly equal the variance of the input, so activations neither explode nor vanish as you go deeper. This means scaling the initial weights by a factor related to n:W = np.random.randn(shape) * scaling_factorThe scaling factor depends on the activation function used. Common schemes includes:Xavier for tanh activationsW = np.random.randn(n_l, n_prev) * np.sqrt(1 / n_prev)# In PyTorchimport torch.nn as nnlayer = nn.Linear(256, 128)nn.init.xavier_normal_(layer.weight) # Xavier for tanhnn.init.zeros_(layer.bias) # biases always start at zeroHe initialization for RELU activations (as RELU kills half its input, i.e. negative values — > 0, so we need to compensate with a larger variance)W = np.random.randn(n_l, n_prev) * np.sqrt(2 / n_prev)# in PyTorchlayer = nn.Linear(256, 128)nn.init.kaiming_normal_(layer.weight) # He initialization for ReLUnn.init.zeros_(layer.bias) # biases always start at zero3.4. Gradient CheckingWhen you implement backpropagation, it’s very easy to introduce bugs. The network might still train (loss goes down) but slower or to a worse solution, and you’d never know something was wrong.Gradient checking is a debugging technique that verifies your backpropation implementation by comparing it against a simpler, trustworthy (but slow) numerical estimate.Recalling Numerical Approximation of the Gradient: the two-sided approximation:Now you use this to audit your backprop for gradient checking, following the procedure:Step 1: Unroll all parameters (W¹, b¹, W², b²…) into a single giant vector θ.Step 2: For each parameter θᵢ, compute the numerical gradient:where J is your loss function.Step 3: Run your actual backprop to get dθ[i] for every parameter.Step 4: Compare the two vectors using the normalized difference:The division normalizes for scale — a difference of 0.1 means something very different if the gradients are size 0.001 vs. size 1000.Difference = ~ 10^(-7) => backprop is almost certainly correctDifference = ~ 10^(-5) => backprop needs a closer lookDifference = ~ 10^(-3) => bug likely.Some caveats of Gradient Checking:Only use in debugging, don’t use in trainingIf algorithms fails grad check, look at components to try to identify bugRemember regularizationDoesn’t work with dropoutRun at random initialization; perhaps again after some training.Improving Deep Neural Learning Networks (Part 1): Practical Approaches and Applications to LLMs was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.