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.
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.
- Introduction and installation
- TensorFlow Basics
- Keras Sequential API
- Dense MLP Network
- Convolutional Neural Networks
Why and when to use transfer learning
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?
2 main strategies
| Strategy | When | How |
|---|---|---|
| Feature extraction | Small dataset (<1000) | Freeze the base, train a head |
| Fine-tuning | Medium dataset (1k-10k) | Unfreeze the last layers |
Popular pre-trained models
| Model | Domain | Size |
|---|---|---|
| MobileNetV2 / V3 | Images, mobile | 3-5 MB |
| EfficientNet B0-B7 | Images, top precision | 20-200 MB |
| ResNet50 / 152 | Images, classic | 100-200 MB |
| VGG16 / 19 | Images, vintage | 500 MB+ |
| BERT | NLP | 400 MB |
| DistilBERT | Fast NLP | 250 MB |
Loading a pre-trained model
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
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
| MobileNet | preprocess_input : [-1, 1] |
| ResNet | ImageNet mean subtracted |
| EfficientNet | preprocess_input : [0, 255] |
When to use transfer learning
YES
NO
Summary
- 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?
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
| Aspect | Classical ML | Deep Learning |
|---|---|---|
| Data | Hundreds to thousands | Thousands to millions |
| Features | Manual (engineering) | Learned automatically |
| Hardware | CPU is enough | GPU/TPU recommended |
| Training time | Seconds to minutes | Hours to days |
| Interpretability | Good | Low (black box) |
| Use cases | Tabular | Images, audio, text |
An artificial neuron
# 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
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?
- Images, audio, video, text
- Large amounts of data (10k+ examples)
- Maximum performance required
- Complex non-linear patterns
- Tabular data < 10k rows (prefer GBM)
- Interpretability is critical
- No GPU available
- Simple linearly separable problem
TensorFlow vs PyTorch
| TensorFlow / Keras | Production-ready, easy deployment, mobile (TFLite) |
| PyTorch | Research, more Pythonic, dominant in NLP |
| JAX | Raw performance, internal Google |
Summary
- 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
Project structure
mask-api/ âââ app/ â âââ main.py # FastAPI â âââ mask_final.keras # model â âââ __init__.py âââ requirements.txt âââ Dockerfile âââ README.md
requirements.txt
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
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
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
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
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
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 CodeFAQ
How long does it take to learn Python TensorFlow Keras?
Are there any prerequisites?
Where to start concretely?
📬 Want to receive this type of guide every week? Subscribe for free — real code, zero fluff.