Deep Learning with TensorFlow and Keras: A Beginner’s Guide (2026)
TensorFlow is Google’s open-source deep learning framework; Keras is its high-level API. Together they power image recognition, language translation, and recommendation systems. This guide gets you building real models fast.
Installation
pip install tensorflow numpy matplotlib scikit-learnimport tensorflow as tf
print(tf.__version__)
print('GPU:', tf.config.list_physical_devices('GPU'))How Neural Networks Learn
A neural network is layers of nodes (neurons), each computing a weighted sum of inputs followed by an activation function. Training: make predictions, calculate loss, use backpropagation and gradient descent to adjust weights. Key ingredients: architecture, activation functions, loss function, optimizer.
MNIST: Your First Neural Network
from tensorflow import keras
import numpy as np
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
X_train, X_test = X_train / 255.0, X_test / 255.0
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dropout(0.2),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, y_train, epochs=10, batch_size=128, validation_split=0.1)
_, test_acc = model.evaluate(X_test, y_test)
print(f'Test accuracy: {test_acc:.4f}')Activation Functions
ReLU — max(0, x); default for hidden layers; avoids vanishing gradients.
Sigmoid — squashes to (0,1); for binary classification output.
Softmax — probabilities summing to 1; for multi-class output.
Tanh — squashes to (-1,1); used in RNNs.
CNNs for Image Classification
X_train_cnn = X_train.reshape(-1, 28, 28, 1)
X_test_cnn = X_test.reshape(-1, 28, 28, 1)
cnn = keras.Sequential([
keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
keras.layers.MaxPooling2D((2,2)),
keras.layers.Conv2D(64, (3,3), activation='relu'),
keras.layers.MaxPooling2D((2,2)),
keras.layers.Flatten(),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dropout(0.3),
keras.layers.Dense(10, activation='softmax')
])
cnn.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
cnn.fit(X_train_cnn, y_train, epochs=5, batch_size=64, validation_split=0.1)
_, cnn_acc = cnn.evaluate(X_test_cnn, y_test)
print(f'CNN accuracy: {cnn_acc:.4f}') # ~99.2%Preventing Overfitting
Dropout randomly zeros neuron outputs during training. L2 regularisation penalises large weights. Data augmentation for image tasks. Early stopping when validation loss stops improving.
Transfer Learning
base = keras.applications.MobileNetV2(input_shape=(96,96,3), include_top=False, weights='imagenet')
base.trainable = False
model = keras.Sequential([base, keras.layers.GlobalAveragePooling2D(),
keras.layers.Dense(128, activation='relu'), keras.layers.Dense(5, activation='softmax')])Saving and Loading
cnn.save('mnist_cnn.h5')
loaded = keras.models.load_model('mnist_cnn.h5')
print('Preds:', loaded.predict(X_test_cnn[:5]).argmax(axis=1))Conclusion
The pattern is always: define architecture, compile, fit, evaluate, iterate. Once comfortable with Sequential, explore the Functional API for complex architectures and transfer learning for production image tasks.



