DeveloperBootstrap

AI & Machine Learning

TensorFlow 2.15 Complete Guide

Master TensorFlow 2.15 machine learning development with Python 3.12, neural networks, deep learning models, GPU acceleration, model training, validation, and production deployment on Ubuntu 24.04 LTS.

What you'll learn

  • Install TensorFlow 2.15 with GPU support
  • Build neural networks with the Keras functional API
  • Train classification and regression models
  • Implement transfer learning with pre-trained models
  • Optimise models with callbacks and learning rate schedules
  • Export and serve models with TensorFlow Serving
  • Monitor training with TensorBoard

Installation & GPU Setup

Bash
1# Install CUDA 12.x (Ubuntu 24.04)
2wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64/cuda-keyring_1.1-1_all.deb
3sudo dpkg -i cuda-keyring_1.1-1_all.deb
4sudo apt update && sudo apt install -y cuda-toolkit-12-3
5
6# Install cuDNN
7sudo apt install -y libcudnn8 libcudnn8-dev
8
9# Install TensorFlow
10python3.12 -m venv .venv && source .venv/bin/activate
11pip install tensorflow==2.15.0
12
13# Verify GPU
14python -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"
15# [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

TensorFlow Basics

Python
1import tensorflow as tf
2import numpy as np
3
4# Tensors
5a = tf.constant([[1., 2.], [3., 4.]])
6b = tf.constant([[5., 6.], [7., 8.]])
7print(tf.matmul(a, b))
8
9# Variables (trainable parameters)
10w = tf.Variable(tf.random.normal([2, 3]))
11b = tf.Variable(tf.zeros([3]))
12
13# Automatic differentiation
14with tf.GradientTape() as tape:
15    y = tf.matmul(x, w) + b
16    loss = tf.reduce_mean(tf.square(y - y_true))
17
18gradients = tape.gradient(loss, [w, b])
19optimizer.apply_gradients(zip(gradients, [w, b]))

Building Neural Networks

Python
1from tensorflow import keras
2from tensorflow.keras import layers
3
4# Sequential API (simple)
5model = keras.Sequential([
6    layers.Input(shape=(784,)),
7    layers.Dense(256, activation='relu'),
8    layers.Dropout(0.3),
9    layers.Dense(128, activation='relu'),
10    layers.Dropout(0.3),
11    layers.Dense(10, activation='softmax')
12])
13
14# Functional API (flexible — multiple inputs/outputs)
15inputs = keras.Input(shape=(784,))
16x = layers.Dense(256, activation='relu')(inputs)
17x = layers.BatchNormalization()(x)
18x = layers.Dropout(0.3)(x)
19outputs = layers.Dense(10, activation='softmax')(x)
20model = keras.Model(inputs, outputs)
21
22model.summary()

Training & Optimisation

Python
1model.compile(
2    optimizer=keras.optimizers.Adam(learning_rate=1e-3),
3    loss='sparse_categorical_crossentropy',
4    metrics=['accuracy']
5)
6
7callbacks = [
8    keras.callbacks.EarlyStopping(patience=5, restore_best_weights=True),
9    keras.callbacks.ReduceLROnPlateau(factor=0.5, patience=3),
10    keras.callbacks.ModelCheckpoint('best_model.keras', save_best_only=True),
11    keras.callbacks.TensorBoard(log_dir='./logs'),
12]
13
14history = model.fit(
15    x_train, y_train,
16    epochs=50,
17    batch_size=128,
18    validation_split=0.2,
19    callbacks=callbacks
20)

Transfer Learning

Python
1# Use MobileNetV2 for image classification
2base_model = keras.applications.MobileNetV2(
3    input_shape=(224, 224, 3),
4    include_top=False,
5    weights='imagenet'
6)
7base_model.trainable = False   # freeze base layers
8
9inputs  = keras.Input(shape=(224, 224, 3))
10x       = keras.applications.mobilenet_v2.preprocess_input(inputs)
11x       = base_model(x, training=False)
12x       = layers.GlobalAveragePooling2D()(x)
13x       = layers.Dropout(0.2)(x)
14outputs = layers.Dense(num_classes, activation='softmax')(x)
15model   = keras.Model(inputs, outputs)
16
17model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
18model.fit(train_ds, epochs=10)
19
20# Fine-tune: unfreeze top layers
21base_model.trainable = True
22for layer in base_model.layers[:-20]:
23    layer.trainable = False
24model.compile(optimizer=keras.optimizers.Adam(1e-5), ...)
25model.fit(train_ds, epochs=5)

Model Serving

Bash
1# Save in SavedModel format
2model.save('/models/classifier/1')
3
4# Serve with TensorFlow Serving
5docker run -p 8501:8501   -v /models/classifier:/models/classifier   -e MODEL_NAME=classifier   tensorflow/serving
6
7# Predict via REST
8curl -X POST http://localhost:8501/v1/models/classifier:predict   -d '{"instances": [[0.1, 0.2, ...]]}'
9
10# Convert to TFLite for mobile/edge
11converter = tf.lite.TFLiteConverter.from_saved_model('/models/classifier/1')
12converter.optimizations = [tf.lite.Optimize.DEFAULT]
13tflite_model = converter.convert()
14open('model.tflite', 'wb').write(tflite_model)

TensorBoard

Bash
1# Launch TensorBoard
2tensorboard --logdir ./logs --port 6006
3# Open http://localhost:6006
4
5# Log custom scalars
6writer = tf.summary.create_file_writer('./logs/custom')
7with writer.as_default():
8    tf.summary.scalar('custom_metric', value, step=epoch)
9
10# Profile GPU utilisation
11tf.profiler.experimental.start('./logs/profile')
12model.fit(x_train, y_train, epochs=1)
13tf.profiler.experimental.stop()