Python TensorFlow Keras: The 9 Key Steps to Go from Zero to Operational

Python TensorFlow Keras: The Essentials in One Article — Real Code, Diagrams and Concrete Steps, Excerpts from a 34-Lesson Course.

Python TensorFlow Keras: The 9 Key Steps to Go from Zero to Operational

Everyone can learn Python TensorFlow Keras — provided they follow the steps in the right order. We have condensed a complete 34-lesson course into a clear path, with the most useful code snippets.

tl;dr
  • Introduction and installation
  • TensorFlow Basics
  • Keras Sequential API
  • Dense MLP Network
  • Convolutional Neural Networks
~$ cat ./parcours.md # Python TensorFlow Keras — 10 chapters
01
Introduction and installation
→ What is deep learning?→ Install TensorFlow 2.x+ 1 more lessons
02
TensorFlow Basics
→ Tensors and operations→ GradientTape and autodiff+ 1 more lessons
03
Keras Sequential API
→ Sequential — stack layers→ Compiler — optimizer, loss, metrics+ 1 more lessons
04
Dense MLP Network
→ MLP Architecture (Multi-Layer Perceptron)→ MNIST Classification with MLP+ 1 more lessons
05
Convolutional Neural Networks
→ Convolutions and pooling→ CNN on CIFAR-10+ 2 more lessons
06
Recurrent Networks and NLP
→ RNN, LSTM, GRU→ Embeddings for text+ 2 more lessons
07
Transfer learning
→ Why and when to use transfer learning→ Fine-tuning MobileNet+ 1 more lessons
08
Tuning and optimization
→ Optimizers SGD, Adam, RMSprop→ Learning rate scheduling+ 2 more lessons
🏁
Final project (+ 2 chapters along the way)
→ You come away with a concrete, demonstrable project

Why and when to use transfer learning

NOTEGoal — Understand how to reuse pre-trained models on ImageNet for your own tasks.

The idea

Instead of training a model from scratch (costs days and requires millions of images), we take a model already trained on ImageNet (1.4M images, 1000 classes) and adapt it.

Why it works?

TIPMagic result — Reach 95% accuracy on 1000 custom images instead of 70% from scratch.

2 main strategies

StrategyWhenHow
Feature extractionSmall dataset (<1000)Freeze the base, train a head
Fine-tuningMedium dataset (1k-10k)Unfreeze the last layers

Popular pre-trained models

ModelDomainSize
MobileNetV2 / V3Images, mobile3-5 MB
EfficientNet B0-B7Images, top precision20-200 MB
ResNet50 / 152Images, classic100-200 MB
VGG16 / 19Images, vintage500 MB+
BERTNLP400 MB
DistilBERTFast NLP250 MB

Loading a pre-trained model

output
from tensorflow.keras.applications import MobileNetV2

base = MobileNetV2(
    input_shape=(224, 224, 3),
    include_top=False,    # remove the ImageNet head
    weights="imagenet"
)
base.trainable = False     # freeze the weights

print(base.summary())

Building the new model

output
from tensorflow.keras import models, layers

n_classes = 5   # your classes

model = models.Sequential([
    layers.Input(shape=(224, 224, 3)),
    
    # Model-specific preprocessing
    tf.keras.applications.mobilenet_v2.preprocess_input,
    
    # Frozen base
    base,
    
    # New head
    layers.GlobalAveragePooling2D(),
    layers.Dropout(0.3),
    layers.Dense(n_classes, activation="softmax")
])

model.compile(optimizer="adam",
              loss="sparse_categorical_crossentropy",
              metrics=["accuracy"])

Model-specific pre-processing

MobileNetpreprocess_input : [-1, 1]
ResNetImageNet mean subtracted
EfficientNetpreprocess_input : [0, 255]
WARNINGAlways apply the original model's preprocessing. Without it, performance will be poor.

When to use transfer learning

YES

NO

Summary

NOTEKey takeaways
  • Transfer learning = reuse a pre-trained model
  • Feature extraction if little data
  • Fine-tuning if medium dataset
  • Always apply the model's preprocessing
  • tf.keras.applications = ready-to-use models

Next step: Part 2 — Fine-tuning MobileNet

What is deep learning?

NOTEGoal — Understand what distinguishes deep learning from classical ML, and when to use it.

Definition

Deep learning is a sub-branch of machine learning that uses deep neural networks (multiple hidden layers) to learn hierarchical representations of data.

Classical ML vs Deep Learning

AspectClassical MLDeep Learning
DataHundreds to thousandsThousands to millions
FeaturesManual (engineering)Learned automatically
HardwareCPU is enoughGPU/TPU recommended
Training timeSeconds to minutesHours to days
InterpretabilityGoodLow (black box)
Use casesTabularImages, audio, text

An artificial neuron

output
# Output = activation(sum(weights * inputs) + bias)
y = activation(w1*x1 + w2*x2 + ... + w_n*x_n + b)

Multiple neurons in parallel = layer. Multiple layers = deep network.

Anatomy of a dense network

output
Input (28x28=784)
   |
   v
Hidden layer 1 (128 neurons, ReLU)
   |
   v
Hidden layer 2 (64 neurons, ReLU)
   |
   v
Output layer (10 neurons, Softmax)
   |
   v
Probabilities for the 10 classes

Main architectures

MLP (Dense)

Tabular, simple classification. The foundation of DL.

CNN (Convolutional)

Images. Detects local patterns via convolutions.

RNN / LSTM / GRU

Sequences: text, audio, time series.

Transformers

Modern NLP (BERT, GPT). Attention mechanism.

When to use DL?

TIPGood cases
  • Images, audio, video, text
  • Large amounts of data (10k+ examples)
  • Maximum performance required
  • Complex non-linear patterns
WARNINGBad cases
  • Tabular data < 10k rows (prefer GBM)
  • Interpretability is critical
  • No GPU available
  • Simple linearly separable problem

TensorFlow vs PyTorch

TensorFlow / KerasProduction-ready, easy deployment, mobile (TFLite)
PyTorchResearch, more Pythonic, dominant in NLP
JAXRaw performance, internal Google

Summary

NOTEKey takeaways
  • DL = deep networks that learn features themselves
  • Excellent for images, audio, text
  • Requires GPU and lots of data
  • 4 families: MLP, CNN, RNN, Transformer
  • TensorFlow + Keras = production-ready

FastAPI API + Docker deployment

Final project • FastAPI • Docker • production

NOTEGoal — Serve the mask detection model via a FastAPI API, package it in a Docker container, and test in production.

Project structure

output
mask-api/
  ⓜ── app/
  │   ⓜ── main.py          # FastAPI
  │   ⓜ── mask_final.keras # model
  │   └── __init__.py
  ⓜ── requirements.txt
  ⓜ── Dockerfile
  └── README.md

requirements.txt

output
fastapi==0.109.0
uvicorn[standard]==0.27.0
tensorflow==2.16.1
pillow==10.2.0
python-multipart==0.0.6

app/main.py

output
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
import tensorflow as tf
import numpy as np
from PIL import Image
import io

app = FastAPI(title="Face Mask Detection", version="1.0")
model = tf.keras.models.load_model("app/mask_final.keras")
LABELS = ["with_mask", "without_mask"]

@app.get("/")
def root():
    return {"service": "face-mask-detection", "version": "1.0"}

@app.get("/health")
def health():
    return {"status": "ok", "model_loaded": True}

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    if file.content_type not in ["image/jpeg", "image/png"]:
        raise HTTPException(400, "Only JPEG/PNG allowed")
    
    contents = await file.read()
    img = Image.open(io.BytesIO(contents)).convert("RGB").resize((224, 224))
    arr = np.expand_dims(np.array(img), axis=0).astype("float32")
    
    proba = float(model.predict(arr, verbose=0)[0][0])
    label = LABELS[int(proba > 0.5)]
    confidence = proba if proba > 0.5 else 1 - proba
    
    return {
        "prediction": label,
        "confidence": round(confidence, 4),
        "with_mask_proba": round(1 - proba, 4),
        "without_mask_proba": round(proba, 4)
    }

Testing locally

output
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

# Auto-generated docs at http://localhost:8000/docs

# curl test
curl -X POST "http://localhost:8000/predict" \
     -F "file=@test.jpg"

Dockerfile

output
FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY app/ ./app/

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=10s \
    CMD curl -f http://localhost:8000/health || exit 1

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Build and run

output
docker build -t mask-detection:1.0 .
docker run -d -p 8000:8000 --name mask-api mask-detection:1.0

# Verify
docker logs mask-api
curl http://localhost:8000/health
go-further

This article covers the most useful snippets — the complete Python TensorFlow Keras course (10 chapters, 34 lessons, corrected exercises and final project) will take you all the way.

./access-the-full-course free course: Mastering Claude Code

FAQ

How long does it take to learn Python TensorFlow Keras?
With a structured progression (10 chapters, 34 short and practical lessons), you can reach an operational level in a few weeks at 30 to 60 minutes per day. The key is to practice each concept immediately.
Are there any prerequisites?
Basic computer science knowledge is enough. If you can use a terminal and read simple code, you're ready.
Where to start concretely?
Reproduce the commands from this article, then follow the full Python TensorFlow Keras course: it chains the 34 lessons in order, with exercises and a final project.

📬 Want to receive this type of guide every week? Subscribe for free — real code, zero fluff.