Deep Learning Explained for Beginners: Neural Networks and Practical Examples
You write the number 7 on paper, photograph it, and ask a computer to identify it. A traditional program might need many hand-written rules about slants, loops, strokes and image positions. A neural network takes a different route: it studies many labeled examples, adjusts thousands of numerical parameters, and learns patterns that help it predict which digit appears in an unfamiliar picture. But how do those numbers, connections and layers actually produce a prediction?
This deep learning for beginners guide answers that question from the inside out. We will calculate the output of a single artificial neuron, trace signals through a small network, distinguish loss from accuracy, understand gradients and backpropagation, and build a functioning handwritten-digit classifier with Python. The practical charts and prediction counts below come from executed code, not decorative estimates.
Our project uses Keras 3 with the PyTorch backend and scikit-learn’s built-in 8×8 handwritten digits dataset. It has 1,797 images and is smaller than the famous 28×28 MNIST dataset. The installed runtime could not download MNIST, so we selected an openly documented, offline dataset rather than invent MNIST results. The architecture, training workflow and learning goals still demonstrate a genuine multilayer neural network, while all results are identified as belonging to the smaller dataset.
What you will be able to do: explain neural-network layers, weights, biases and nonlinear activations; calculate a neuron’s output; describe forward propagation, loss, backpropagation and optimization; train a 64-input/64-hidden-unit/10-output classifier; read authentic learning curves and misclassifications; and safely save and reload a model you created.
What is deep learning?
Deep learning is a family of machine learning methods built around neural networks with multiple learned processing layers. Each layer transforms its input into another numerical representation. During training, an optimization procedure adjusts internal parameters so the network can solve a task such as classifying images, recognizing speech or predicting quantities. The word deep refers to architecture—the number of successive learned transformations—not to consciousness, wisdom or human-like understanding.
In a digit-recognition task, the early numerical representation consists of pixel intensities. A hidden layer can learn combinations of pixel values that help distinguish shapes. Later layers can combine those intermediate patterns into scores for the ten possible digits. Our demonstration uses only one learned hidden layer because a small network is sufficient to teach the process; much larger deep networks may have many more layers and specialized structures.
Artificial neural networks are inspired in part by historical ideas about biological neurons, but they are mathematical models rather than literal digital brains. Their units, weighted sums and gradient-based training are simplified computational constructions. A network may perform its assigned task effectively without understanding the meaning of a digit or why a human wrote it.
How are AI, machine learning and deep learning related?
Artificial intelligence is the broad field of designing systems capable of tasks such as planning, search, perception and language processing. Machine learning is a collection of methods that learn relationships from data. Deep learning is one important family within machine learning, usually using multilayer neural networks. This relationship does not imply that every AI system uses deep learning or that every machine learning model is a neural network.

For contrast, a hand-crafted planning algorithm can be an AI technique without learning a neural representation. In our previous Python machine learning project, the supervised model was a small decision tree with interpretable feature thresholds. A neural network tackles a different modeling approach by combining learned numerical transformations, which may be particularly useful with complex inputs such as images and sounds.
Traditional machine learning vs. deep learning
| Dimension | Many traditional models | Deep learning |
|---|---|---|
| Typical methods | Decision trees, linear models, support vector machines | Multilayer neural networks |
| Input representation | Engineered numerical or categorical features are often important | Can learn useful intermediate representations |
| Typical data needs | Vary by method and task | May benefit from substantial labeled or self-supervised data |
| Compute demand | Ranges from small to large | Can be substantial for larger networks |
| Interpretability | Some models are easy to inspect; others are not | Many learned representations are harder to explain |
| Example | Classify Iris flower measurements | Classify numerical pixel arrays for handwritten digits |
These are tendencies, not laws. A well-designed decision tree may outperform a poorly selected neural network on a small table. Some neural networks are small enough for ordinary CPUs, while some classical methods also demand substantial resources. Select a method by task, data quality, evaluation evidence, cost and interpretability—not by assuming that the most fashionable model must be best.
What is an artificial neural network?
An artificial neural network is a connected system of mathematical units whose outputs feed other units. Each unit typically combines input values with adjustable weights, adds a bias and applies an activation function. A layer groups such computations. With enough appropriate structure, the network can learn nonlinear relationships between measurements and target outcomes.
Imagine that each handwritten image is represented by a grid of numerical pixel values. The first learned layer receives a set of these values and forms new combinations. An output layer then produces ten scores, one for each digit from zero to nine. During prediction, the category with the highest score becomes the chosen digit; during training, known correct digit labels are used to calculate how the network should be improved.
Anatomy of one artificial neuron: a verified calculation
Start with two inputs, x1 = 2 and x2 = 3. Their associated weights are w1 = 0.5 and w2 = 0.2, and the bias is b = 0.1. A simple artificial neuron’s pre-activation calculation is z = w1×x1 + w2×x2 + b. Substituting the numbers gives z = 2×0.5 + 3×0.2 + 0.1 = 1.0 + 0.6 + 0.1 = 1.7.
The bias lets a unit shift its response rather than being constrained to a weighted sum with no offset. A weight controls how strongly its corresponding input contributes to the sum, including whether the contribution is positive or negative. Weights are learned parameters, not conscious judgments about which input matters. Their interpretation becomes especially difficult when many layers interact.

import numpy as np
inputs = np.array([2.0, 3.0])
weights = np.array([0.5, 0.2])
bias = 0.1
z = float(np.dot(inputs, weights) + bias)
print('Weighted sum:', z)
print('ReLU output:', max(0.0, z))
The verified output is Weighted sum: 1.7 and ReLU output: 1.7. This program performs one forward calculation with fixed numbers; it does not train anything. Training requires data, an objective that measures errors, and a method for adjusting parameters. Keeping that distinction clear makes the full network much easier to understand.
Input, hidden and output layers explained
The input defines the numerical shape expected by the model. Our 8×8 image contains 64 pixel values. The hidden layer applies 64 learnable nonlinear transformations to those values. The output layer supplies ten scores, corresponding to the possible digit classes 0–9. In our model a Flatten operation changes the input’s shape before the learned dense layers; Flatten itself has no trainable parameters.
A hidden layer does not necessarily correspond to a recognizable human concept such as ‘a loop’ or ‘a stroke’. Its units form learned numerical features that may work together in ways that are difficult to interpret individually. Similarly, having 64 neurons in one layer is different from having 64 layers. The depth of a network concerns successive transformations, not simply its width.

The number of output units depends on the task. A multiclass classifier commonly needs one score per class; a binary prediction may use one sigmoid unit or two competing class scores; numerical regression may use one or more continuous outputs. The architecture and chosen loss function must agree. You cannot simply replace the output layer without checking how its outputs will be interpreted.
Activation functions: why neural networks need nonlinearity
An activation function transforms a neuron’s weighted sum. Without nonlinear activation functions between learned layers, stacking ordinary linear transformations would still represent only an overall linear transformation, limiting what a feedforward model can express. Nonlinear functions help the model represent more complex relationships such as digit shapes whose classes cannot be separated by one simple linear boundary.
ReLU, short for rectified linear unit, outputs the input if it is positive and zero otherwise: ReLU(z) = max(0, z). It is widely used in hidden layers because it is simple and often practical to optimize. Sigmoid maps a scalar to values between zero and one and can be useful for some binary probability outputs. Softmax converts an entire vector of class scores into nonnegative numbers that sum to one; it is not a single-input curve like ReLU or sigmoid.

For example, raw output scores of [2, 1, 0] become a normalized softmax distribution of approximately [0.665, 0.245, 0.090]. These are model-derived numbers, and high softmax values do not automatically guarantee good probabilistic calibration. Our project produces raw class scores called logits and uses a loss function configured to process them directly.
What is forward propagation?
Forward propagation is the sequence of computations that turns input features into an output. Each layer takes numerical values from the preceding stage, calculates new values with its parameters and activation, and sends the result onward. In our example, a grayscale image is normalized, reshaped into 64 features, transformed by a 64-unit ReLU layer, and converted into ten final digit scores.

During ordinary prediction, the network does not need to know the true digit label. It only needs the input pixel array in the expected shape and scale. During training, the correct label is additionally supplied so the model can quantify the mismatch. That separation helps you understand why a trained model can later work on a previously unseen image without being handed the correct answer.
Loss functions: measuring the mismatch, not the whole story
A loss function defines what a model is trying to minimize during training. In multiclass classification, categorical cross-entropy is a common choice: it penalizes a model when it assigns insufficient relative support to the correct class. Our digit labels are integer values from zero to nine, so we use SparseCategoricalCrossentropy(from_logits=True). The from_logits=True setting matters because our output layer produces ten unnormalized class scores, not ten explicit softmax probabilities.
Training loss and accuracy answer different questions. Accuracy counts how many predicted digit labels match the references. Loss also considers the pattern of model scores; two networks can make the same number of correct class decisions yet receive different loss values if their score distributions differ. A lower loss does not automatically mean every important subgroup or error type improved.
How do neural networks learn from data?
At the beginning of training, most weights are initialized to small numerical values rather than meaningful patterns. A batch of labeled images passes forward through the network, producing ten scores for each image. The loss function measures how well those outputs support the correct classes. A gradient-calculation procedure evaluates how the loss would respond to small changes in the parameters. An optimizer then updates the parameters. The cycle repeats over many batches.
The aim is not to memorize the labels of the exact images seen during training. It is to learn useful relationships that transfer to images held out from fitting. We therefore monitor both training performance and a validation set that helps us understand learning progress. Only after the model-building choices are finished do we consult the separate test set for a final evaluation.
Backpropagation explained for beginners
Backpropagation is an efficient way of calculating gradients of a network’s loss with respect to its trainable parameters. It uses the mathematical chain rule: because each layer’s output depends on earlier layer values, the influence of a small parameter change can be computed backward through those dependencies. The result is a set of gradients—directions and sensitivities that tell an optimizer how changing parameters may affect the loss.
The gradient calculation is distinct from the update itself. For example, the Adam optimizer uses gradients together with running estimates of their behavior to adjust weights. A common oversimplification says backpropagation ‘sends errors backwards.’ It is more accurate to say that it calculates derivatives of the objective through the computational graph. You do not need to derive all of these equations to begin, but the distinction prevents confusion when reading neural-network documentation.

Epochs, batches, learning rate and optimization
An epoch is one pass through the designated training examples. A batch is a smaller collection processed together for a parameter update. The batch size determines how many examples appear in such a collection, and the learning rate controls the approximate scale of the optimizer’s parameter adjustments. Our project uses 18 epochs, batches of 32 images and Adam with a learning rate of 0.001.
With 1,149 training images and batch size 32, an epoch involves 36 batches, including a smaller final batch. The update process is not guaranteed to lower training loss on every individual batch: noisy gradients, initialization and model geometry can cause temporary increases. A very large learning rate may produce unstable training, while a very small one may make progress slow. There is no universally correct learning rate for every task.
Overfitting, underfitting and validation curves
If a neural network learns only a crude approximation and performs poorly even on training data, it may be underfitting. If it learns noise or unusual details from training images, it can perform much better on training data than on unfamiliar images; this is a common sign of overfitting. Validation loss and accuracy give an early indication of how the training process behaves beyond the images used for parameter updates.
Possible controls include better or more representative data, a suitable model size, regularization, dropout, stronger validation procedures and early stopping. None is a guarantee. A validation score can be optimistic if the same images or related examples leak into the training set, and repeated decisions based on the final test set undermine its independence.
For the executed project, final training accuracy was approximately 97.04% and final validation accuracy approximately 96.53%. The values are close, but this is one modest-sized educational dataset and one held-out validation split. The actual epoch-by-epoch curves later in the tutorial show how these quantities changed rather than relying on an invented smooth learning curve.
Major types of neural network architectures
Feedforward and multilayer perceptron networks
A feedforward network transforms inputs through a sequence of layers to outputs. Dense or multilayer perceptron models combine learned weighted sums with activations, often after input values are converted to a fixed-length numerical vector. Their simplicity makes them valuable introductory examples. The digit classifier you will build is a small feedforward neural network: one Flatten operation, one hidden Dense layer and one output Dense layer.
Convolutional neural networks (CNNs)
A convolutional neural network applies learned filters across nearby parts of an image or other structured signal. Its architecture can exploit spatial locality more directly than a flattened dense network. CNNs have a long history in visual recognition, scientific imaging and related applications. A CNN might outperform our simple dense classifier on some image problems, but it introduces additional concepts such as kernels, feature maps and pooling that are not required to understand the first training workflow.
Recurrent neural networks (RNNs)
Recurrent architectures maintain a representation that changes as a sequence is processed. They have been used for text, time series and speech-related tasks. Traditional RNNs can struggle with long-range dependencies and sequential computation. Variants such as LSTMs and GRUs address some of these issues. Although they remain useful in particular settings, they are not the only or necessarily the dominant architecture in modern language technologies.
Transformers and attention
Transformers use attention mechanisms to combine information across positions in a sequence or other structured input. Attention helps a model assign context-dependent influence to different tokens or features during a computation. Modern large language models often use transformer-based architectures, although systems can combine different methods. Transformers are more complex than our first dense network, so this article introduces their central purpose without requiring detailed attention-matrix mathematics.
Each architecture responds to the structure of a problem. Images contain spatial relationships, speech changes through time, language contains long-distance dependencies, and ordinary tables may favor simpler approaches. It is sensible to begin with a small feedforward classifier and move to specialized architectures only after the data and evaluation question are clear.
Real-world uses and boundaries of deep learning
Deep learning contributes to image classification, speech transcription, language translation, computer vision, accessibility tools and scientific image analysis. Environmental researchers may analyze authorized satellite or sensor data; medical researchers study models built under rigorous clinical, ethical and regulatory safeguards. Generative systems can produce text, images and other media by modeling statistical structure in training data. Robots may combine perception networks with planning and control methods.
Success in one controlled benchmark does not establish safety, fairness or reliability elsewhere. A handwritten-digit model trained on an educational dataset may fail on photographs with unfamiliar backgrounds, handwriting styles or visual noise. For consequential systems, designers need appropriate data governance, external validation, error monitoring, transparent limitations and human oversight rather than simply reporting a high test accuracy.
Practical project: train a handwritten-digit neural network with Python
We will now train a real dense neural network to recognize digits from images. The scikit-learn handwritten digits dataset contains 1,797 real 8×8 grayscale images with correct labels from zero to nine. Original pixel intensities range from zero to sixteen. The dataset loads locally through scikit-learn, making it suitable when a large download or specialized GPU is unavailable. It is not MNIST, which instead contains many more 28×28 images.
Our research question is: can a small neural network learn from a training subset of these images and predict the known labels on a separate group it has not trained on? The input is an 8×8 numerical array, and the target is an integer digit label. The model will use one hidden layer with 64 ReLU units and an output layer that produces ten unnormalized scores. It has 4,810 trainable parameters.
Step 1 — Prepare a compatible Keras environment
Keras 3 can use different computation backends. This verified project uses the PyTorch backend only; set KERAS_BACKEND before importing Keras. In a compatible Python environment, install the required packages with the following command. The first installation may take time, while later runs can reuse the packages. TensorFlow is not necessary for the Torch backend variant, and this code should not be mixed with tf.keras imports.
python -m pip install keras torch scikit-learn numpy matplotlib
In this runtime the project was executed using Python 3.13.5, Keras 3.13.2, PyTorch 2.10.0 (CPU), and scikit-learn 1.8.0. Framework availability changes across operating systems. Follow the Keras 3 getting-started guide and official digits dataset documentation if you use another system or Python version.
Step 2 — Import the framework and define a reproducible seed
import os
os.environ['KERAS_BACKEND'] = 'torch' # before importing keras
import numpy as np
import keras
from keras import layers
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
keras.utils.set_random_seed(42)
We identify the backend explicitly so that the example’s source code matches the framework that was actually executed. The random seed reduces avoidable run-to-run differences, but cross-platform numerical reproducibility is not always bit-for-bit guaranteed. You should record installed versions and the data split whenever you publish a result. The framework used for training is Keras with PyTorch backend, rather than multiple competing backends mixed inside one script.
Step 3 — Load genuine handwritten images and their labels
digits = load_digits()
X = digits.images.astype('float32') / 16.0
y = digits.target.astype('int64')
print(X.shape, y.shape)
print(X.min(), X.max())
The verified array shapes are (1797, 8, 8) for images and (1797,) for labels. Dividing each pixel value by 16 converts the original 0–16 intensity range to approximately 0–1. This helps keep the inputs on a convenient numerical scale. We have not altered labels, and we apply this same fixed scaling to all subsets.

The images may look small or blocky because they are only eight pixels across. This is normal for a compact educational dataset. MNIST uses 28×28 images, and the model input shape would have to change if you later chose to run an official MNIST tutorial. Do not put MNIST performance statistics next to this example as though they were produced by the same data or architecture.
Step 4 — Separate training, validation and test images
X_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.20, random_state=42, stratify=y
)
X_train, X_val, y_train, y_val = train_test_split(
X_dev, y_dev, test_size=0.20, random_state=42, stratify=y_dev
)
print(len(X_train), len(X_val), len(X_test))
The verified counts are 1,149 training images, 288 validation images and 360 test images. The training set updates parameters. Validation images help monitor whether learning is transferring beyond the training subset. The final test set stays separate until training and selection are finished. This split is stratified so that digits have broadly comparable proportions across subsets.
Data leakage can arise if near-duplicate recordings from the same source or different views of the same person appear across splits. The built-in digits example uses an ordinary stratified random split; a real handwriting-recognition application might require writer-level or source-level grouping to make the test representative of unseen users. That limitation should be documented rather than concealed.
Step 5 — Build a small neural network
model = keras.Sequential([
keras.Input(shape=(8, 8)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10) # logits, not softmax probabilities
])
print('Trainable parameters:', model.count_params())
The model returns 4,810 trainable parameters. Flatten converts an 8×8 image to 64 numbers without learning parameters. The hidden layer transforms those 64 inputs into 64 ReLU outputs; the final Dense layer generates ten class scores. We intentionally omit a softmax activation in the output layer and instead tell the loss function that its inputs are logits. Both choices can be valid when configured consistently, but mismatching them produces incorrect training behavior.
Step 6 — Compile the model with matching loss and optimizer
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=0.001),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy']
)
The optimizer defines how parameters update; the loss function defines the quantity to reduce; accuracy offers an easier-to-understand classification metric alongside that loss. Because the true labels are integers 0–9, SparseCategoricalCrossentropy is suitable. Because the last layer has no softmax activation, from_logits=True is essential. This pairing matches the documented Keras training API.
Step 7 — Train for 18 epochs, validating separately
history = model.fit(
X_train, y_train,
validation_data=(X_val, y_val),
epochs=18,
batch_size=32,
verbose=0
)
print('Final train accuracy:', history.history['accuracy'][-1])
print('Final validation accuracy:', history.history['val_accuracy'][-1])
In the executed run, the final training accuracy was approximately 0.9704 (97.04%) and the validation accuracy was 0.9653 (96.53%). The final training loss was approximately 0.1602, and the final validation loss approximately 0.1589. These are observed results from one specified run, not targets that every student’s computer must reproduce exactly.
Step 8 — Evaluate on images not used for training or validation
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
logits = model.predict(X_test, verbose=0)
predictions = logits.argmax(axis=1)
print('Test loss:', round(test_loss, 4))
print('Test accuracy:', round(test_accuracy, 4))
print('Correct:', int((predictions == y_test).sum()), 'of', len(y_test))
In the executed run, test loss was approximately 0.1738 and test accuracy was 0.9611 (96.11%). Out of 360 held-out handwritten images, the model classified 346 correctly and 14 incorrectly. That is a useful demonstration, but it does not establish that the network will perform equally well on different handwriting styles, image resolutions or photographs from the real world.
A final test score must be read in context. We used one specific train/validation/test split and 18 epochs; other random seeds, software versions or input distributions can change the outcome. Do not rerun the model repeatedly and select only the most flattering number while claiming it represents an unbiased single experiment. The score applies to this 8×8 dataset and setup, not to the larger MNIST benchmark.
Step 9 — Plot genuine training and validation history
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, metric in zip(axes, ['loss', 'accuracy']):
ax.plot(history.history[metric], label='Training')
ax.plot(history.history['val_' + metric], label='Validation')
ax.set_xlabel('Epoch')
ax.set_title(metric.title())
ax.legend()
plt.tight_layout()
plt.show()

Look for the overall direction of loss and accuracy rather than expecting an absolutely smooth line. A steadily improving training score alongside a deteriorating validation score may signal overfitting, but there are other possible explanations such as a small or unrepresentative validation set. In our short educational run, the final training and validation accuracies were close; this alone does not guarantee strong generalization under new image conditions.
Step 10 — Examine correct and incorrect digit predictions
wrong = np.flatnonzero(predictions != y_test)
print('Number of incorrect predictions:', len(wrong))
for i in wrong[:5]:
print('Actual:', y_test[i], 'Predicted:', predictions[i])

A model’s errors often teach more than a single score. Some handwritten digits are visually ambiguous at just eight pixels across; even a person may disagree about which digit a poorly formed shape represents. Compare the actual and predicted labels carefully, and resist the urge to describe every error as proof that one digit is inherently harder. We would need broader data and uncertainty analysis before drawing such conclusions.
Step 11 — Build a real confusion matrix
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
matrix = confusion_matrix(y_test, predictions, labels=list(range(10)))
ConfusionMatrixDisplay(matrix, display_labels=list(range(10))).plot(
cmap='Greens', colorbar=False
)
plt.show()

The diagonal contains correctly identified digits and the off-diagonal cells reveal specific mistakes. In this executed experiment, four actual 8s were predicted as 1s, while other errors occurred across several classes. This is a small-sample finding, not a universal ranking of digit difficulty. Inspecting confusion patterns helps guide future experiments without pretending accuracy alone describes every class equally well.
Step 12 — Save the neural network and reload your trusted file
model.save('digit_neural_network.keras')
reloaded = keras.models.load_model('digit_neural_network.keras')
reloaded_predictions = reloaded.predict(X_test, verbose=0).argmax(axis=1)
assert np.array_equal(predictions, reloaded_predictions)
print('Saved model matches the original predictions')
Keras 3 uses the .keras format for saving the full model. In the tested workflow, the saved file was successfully reloaded and its predictions matched the original predictions on all 360 test images. Store the model alongside source code and dependency versions. Reuse only model files with a trusted provenance, and refer to the official Keras saving guide for current compatibility guidance.
A student may want to change the architecture to improve validation performance, but do not secretly optimize against the final held-out test set. Modify one variable, create a fresh training run, observe the validation result and record the limitation. An exploratory project is more educational when a disappointing result is explained than when it is hidden.
What did this neural network learn that the previous decision tree did not?
| Feature | Topic 56: Iris decision tree | Topic 57: handwritten-digit neural network |
|---|---|---|
| Dataset | 150 flower measurement rows | 1,797 handwritten 8×8 images |
| Inputs | Four botanical measurements | 64 normalized pixel intensities |
| Model | DecisionTreeClassifier, maximum depth 3 | Dense feedforward Keras network with 4,810 parameters |
| Outputs | Three named species | Ten digit score values |
| Evaluation question | How accurately are flower species predicted? | How accurately are held-out digit labels predicted? |
| Interpretability | Learned splits are relatively easy to inspect | Weights combine nonlinear representations; harder to explain |
| Runtime requirements | Lightweight scikit-learn model | CPU-capable Keras 3 with PyTorch backend |
These experiments do not directly compare deep learning and traditional machine learning performance, because they use different datasets and questions. A higher numerical accuracy in the digit task would not prove that neural networks are universally superior to decision trees. The stronger comparison is methodological: image pixels invite representation learning, while a small table of flower measurements may be handled well by simpler interpretable methods.
Responsible AI: limitations, bias, privacy and computational costs
A digit classifier may perform differently on writing styles, image sensors, age groups or visual conditions missing from the training data. A model that performs well on a benchmark may fail when input images are noisy, rotated, badly cropped or intentionally manipulated. Good evaluation asks whether the dataset represents the intended use and whether the consequences of mistakes are acceptable. Human oversight matters especially in healthcare, education, security and other consequential decisions.
Use openly licensed, public or permissioned learning datasets. Do not collect classmates’ private handwriting samples, personal records or medical information without appropriate consent and safeguards. Document computational costs and choose a modest model when it serves the question; larger architectures consume more time and resources without automatically improving scientific validity. No medical or other high-stakes claim is justified by this beginner result.
Twelve common beginner deep learning mistakes
- Wrong input shape: The project requires 8×8 images, not 28×28 MNIST arrays.
- Backend confusion: Set KERAS_BACKEND before importing Keras and avoid mixing incompatible TensorFlow and PyTorch calls.
- Incorrect preprocessing: Divide the original 0–16 pixels by 16 and use the same scaling for validation and test images.
- Output/loss mismatch: Ten raw scores require a compatible classification loss with from_logits=True.
- Target leakage: Never pass test labels into the fit operation.
- Using the test set repeatedly: Make development choices based on training and validation, not repeated final test results.
- Misreading accuracy: Check misclassified digits and confusion matrices.
- Overfitting: Monitor training and validation performance instead of only training accuracy.
- Unnecessary model size: Begin with a small model that can run on a CPU.
- Misleading images: Use actual dataset samples and genuine training charts for numerical claims.
- Version mismatch: Record the Python, Keras, backend and scikit-learn versions.
- Unsafe model files: Reload only trusted and compatible saved models.
Ten student exercises with explained solutions
Complete each activity before opening the answer. The questions are based on the verified 8×8 handwritten-digit experiment, so they can be checked against the supplied notebook, real charts and worksheet. For programming extensions, change one setting at a time and record any variation instead of copying the published accuracy.
1. Define deep learning in your own words.
It is a family of machine learning methods using neural networks with multiple learned transformations to build useful representations and make predictions or generate outputs.
2. What is different about a decision tree and a neural network?
A decision tree learns conditional splits over features; a dense neural network learns weighted numerical transformations and nonlinear activations. Neither is always best.
3. Identify inputs, weights, bias and activation for a neuron.
Numerical inputs are multiplied by weights, their sum is shifted by a bias, and an activation function transforms the weighted result.
4. Calculate z for inputs 2 and 3, weights 0.5 and 0.2, and bias 0.1.
z = 2×0.5 + 3×0.2 + 0.1 = 1.7. ReLU(1.7) = 1.7. This calculation is a forward pass, not training.
5. Why is ReLU often used in a hidden layer?
Its nonlinearity helps stacked layers represent complex relationships. ReLU maps negative inputs to zero and leaves positive inputs unchanged.
6. Explain training loss versus validation loss.
Training loss is calculated on examples used to adjust parameters; validation loss is measured on separate examples to check behavior during development.
7. Why should training and validation curves be read together?
When training improves while validation becomes worse, it may indicate overfitting. Curves must be interpreted in context rather than as absolute proof.
8. Change the hidden layer from 64 units to 32. How should you compare?
Train a fresh model under the same data split and validation protocol; compare multiple suitable development results and document any uncertainty without retuning against the final test set.
9. What happened when four actual 8s were incorrectly predicted as 1s?
The confusion-matrix row for actual class 8 contains four predictions in the column for digit 1. These are genuine mistakes on the held-out test sample.
10. Write a two-sentence conclusion that includes a limitation.
Example: A small Keras 3 neural network classified 346 of 360 held-out 8×8 digit images correctly. This teaching result does not guarantee similar accuracy for MNIST or real-world handwriting.
Four-week beginner deep learning learning plan
| Week | What to learn | Practical result |
|---|---|---|
| 1 — Foundations | Artificial neurons, weights, biases, activations, network layers | Calculate z=1.7 and explain ReLU in plain language. |
| 2 — Training | Forward pass, loss, backpropagation, Adam, epochs and validation | Sketch the gradient-and-update workflow and interpret sample curves. |
| 3 — Python practice | Keras 3 Torch backend, offline digits data, preprocessing and training | Train the small 64-hidden-unit network in the executed notebook. |
| 4 — Evaluation and reporting | Test accuracy, confusion matrix, saved model, limitations | Reproduce charts, document errors and compare one controlled change. |
Four weeks is a flexible introductory schedule, not a guarantee of mastery. Learners who are new to Python may need more time to practise arrays, functions and notebooks before exploring other architectures.
Download worksheets and reproducible learning materials
The Topic 57 student worksheet (PDF) and the answer guide (PDF) are hosted in the Notes for SHS WordPress media library. A separately downloadable project package contains the fully executed Jupyter notebook, runnable Python script, authentic model charts, README, model file and the verified results record. The WordPress media connection does not support uploading the notebook or ZIP directly, so no broken WordPress download link is displayed here.
Optional further learning: Coursera and Udemy
A helpful next step is to follow a structured neural-network course after completing this free project. The official course pages below have been checked, but an approved affiliate URL was not available for verification; these are therefore normal course links rather than representations that affiliate commissions are being tracked. Prices, subscriptions and availability may vary.

Neural Networks and Deep Learning
Coursera — Explore neural network architecture, vectorization and training principles in the Deep Learning Specialization.

Deep Learning A–Z
Udemy — Additional applied neural-network projects; review its current prerequisites before enrolling.
Frequently asked questions
What is deep learning in simple terms?
It is a family of machine learning methods that learns numerical representations and predictions using neural networks with multiple learned layers.
How is deep learning different from machine learning?
Deep learning is part of machine learning and focuses on multilayer neural networks; other machine learning methods include trees, linear models and many more.
Is an artificial neural network a digital brain?
No. It is a mathematical system inspired in part by biological ideas, but it does not reproduce a human brain or imply consciousness.
What do weights and biases do?
They control the numerical combinations of inputs within a neuron and are adjusted by learning procedures.
Why are activation functions important?
Nonlinear activations allow stacked transformations to represent patterns that ordinary chains of linear layers cannot express.
What is backpropagation?
It is an efficient method of calculating gradients of the loss with respect to model parameters, commonly using the chain rule.
Do I need advanced mathematics to begin?
No. Arithmetic, functions, graphs and basic algebra are enough to follow this first lesson, though deeper study benefits from linear algebra, probability and calculus.
Can I train a neural network without a GPU?
Yes. The verified small 8×8 digit-classifier experiment ran on a CPU. Larger networks can require much more compute.
Why does this article not use MNIST?
The MNIST download was unavailable in the execution environment. Instead, the example uses scikit-learn’s built-in 8×8 handwritten digits dataset and reports only results for that dataset.
What should students learn after this tutorial?
Study data validation, convolutional networks, responsible evaluation, experimental design and the specific practical problems you want to solve.
Related Notes for SHS lessons and official references
This guide builds on Machine Learning for High School Students, Supervised vs. Unsupervised Learning and How to Build Your First Machine Learning Model Using Python. For programming prerequisites, review Python for Data Science Beginners, NumPy Tutorial and Jupyter Notebook for Data Science. All linked Notes for SHS articles were verified as published on staging.
Primary technical documentation: Keras 3 introduction, training and evaluation, model persistence, scikit-learn digits dataset, PyTorch documentation and Google’s Machine Learning Crash Course. These are authoritative learning references rather than substitutes for the reproducible experiment.
Conclusion: from a single neuron to a working digit classifier
We began with one weighted sum that evaluates to 1.7, then expanded the idea to a multilayer network whose weights and biases change through training. You learned what nonlinear activations accomplish, why the forward pass and backpropagation are distinct, how the optimizer acts on gradients, and why validation and honest test evaluation are necessary. You also trained a real small neural network, examined its authentic learning curves and digit errors, and verified that a saved model reproduced its predictions.
The model correctly classified 346 of 360 previously held-out 8×8 digit images in the tested run, but the number alone is not the achievement. Understanding the data source, network architecture, evaluation protocol, uncertainty and limitations makes your work scientifically valuable. Reproduce the project on your own device, change one element deliberately, observe the outcome, and keep clear records. These habits form a strong foundation for deeper studies in computer vision, neural networks and responsible artificial intelligence.
1 response to “Deep Learning Explained for Beginners: Neural Networks and Practical Examples”