Chapter 22: TensorFlow Models
TensorFlow Models — one of the most important and practical parts of TensorFlow.
I’m going to explain it like your favorite teacher: slowly, clearly, with lots of real-life stories (Hyderabad-style examples where possible), analogies, code you can actually run, and the full picture of what “a model” really means in TensorFlow in 2026. No rush — by the end you’ll know exactly what people mean when they say “I trained a TensorFlow model” or “I deployed a TensorFlow model”.
Step 1: What Exactly is a “TensorFlow Model”?
A TensorFlow model is simply:
A saved, reusable object that contains:
- The architecture (layers, connections)
- The trained weights/parameters
- The computation graph (ops and flows)
- Metadata (input/output shapes, optimizer state, etc.)
In other words: It’s the “trained brain” you get after teaching (training) a neural network. You can later use this brain to make predictions on new data (inference), fine-tune it further, export it to mobile/web/edge, or share it with others.
There are two main ways people create and work with models in TensorFlow (both valid in 2026):
- Keras-style models (most common today) → tf.keras.Model or tf.keras.Sequential
- Low-level custom models → subclass tf.Module or tf.keras.Model and define call() manually
In 2026, 95%+ of people use the Keras API — it’s clean, powerful, and production-ready.
Step 2: Analogy Everyone Understands – The “Trained Chef”
Think of a model like a chef who learned to cook Hyderabadi biryani:
- Architecture = the chef’s kitchen layout (stove, vessels, order of steps)
- Weights = the exact spice proportions, timing, heat levels the chef perfected after cooking 10,000 biryanis
- The model = the complete trained chef + kitchen → you give him raw ingredients (new data) → he cooks (predicts) biryani (output)
Once trained → you can:
- Ask him to cook for new guests (inference)
- Teach him a new dish with a few tweaks (fine-tuning)
- Send him to another restaurant (deploy to mobile/web/cloud)
Step 3: How a TensorFlow Model is Born (The Lifecycle)
- Define the architecture → layers, connections
- Compile → choose optimizer, loss, metrics
- Train → fit on data (adjust weights)
- Evaluate → check on test data
- Save → model.save(‘my_model.keras’) or model.save(‘my_model’)
- Load & Use → tf.keras.models.load_model(‘my_model.keras’)
- Deploy → convert to TFLite, TF.js, TF Serving, etc.
Step 4: Real Example 1 – Simple House Price Predictor (Regression)
Very common beginner TensorFlow model.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import numpy as np # Fake Hyderabad flat data X = np.array([[800, 2, 7], [1200, 3, 8], [1500, 3, 9], [1800, 4, 9]], dtype=np.float32) # size, bedrooms, location_score y = np.array([48, 72, 90, 108], dtype=np.float32) # price in lakh # 1. Define the model (Sequential = stack of layers) model = keras.Sequential([ layers.Dense(64, activation='relu', input_shape=(3,)), # hidden layer layers.Dense(32, activation='relu'), # another hidden layers.Dense(1) # output: price ]) # 2. Compile model.compile( optimizer='adam', loss='mean_squared_error', metrics=['mae'] # mean absolute error ) # 3. Train model.fit(X, y, epochs=500, verbose=0) # 4. Predict new flat new_flat = np.array([[1400, 3, 8.5]], dtype=np.float32) predicted_price = model.predict(new_flat)[0][0] print(f"Predicted price for 1400 sq ft, 3BHK, good location: ₹{predicted_price:.1f} lakh") |
After training → this model object is your TensorFlow model.
Step 5: Saving & Loading a TensorFlow Model (Very Important!)
After training:
|
0 1 2 3 4 5 6 7 8 9 |
# Save (recommended format in 2026) model.save('hyderabad_flat_model.keras') # Keras v3 format (recommended) # OR older SavedModel format # model.save('hyderabad_flat_model') |
Later (even in another script or on server/mobile):
|
0 1 2 3 4 5 6 7 8 9 10 |
loaded_model = tf.keras.models.load_model('hyderabad_flat_model.keras') # Use it instantly new_price = loaded_model.predict(new_flat)[0][0] print(new_price) |
Step 6: Real Example 2 – Image Classification Model (MNIST Digits)
Classic TensorFlow model — everyone’s first deep learning model.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() x_train = x_train.astype("float32") / 255.0 x_test = x_test.astype("float32") / 255.0 x_train = x_train[..., tf.newaxis] # add channel dimension x_test = x_test[..., tf.newaxis] model = keras.Sequential([ layers.Conv2D(32, 3, activation='relu', input_shape=(28, 28, 1)), layers.MaxPooling2D(), layers.Conv2D(64, 3, activation='relu'), layers.MaxPooling2D(), layers.Flatten(), layers.Dense(128, activation='relu'), layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5, validation_split=0.1) # Now THIS is your TensorFlow model! test_loss, test_acc = model.evaluate(x_test, y_test) print(f"Test accuracy: {test_acc:.4f}") # ~0.98–0.99 |
Save it → convert to TensorFlow Lite → run on Android phone to recognize handwritten digits from camera!
Step 7: Different Ways to Create TensorFlow Models (2026 Overview)
| Style | Code Example | When to Use | Popularity in 2026 |
|---|---|---|---|
| Sequential | keras.Sequential([…]) | Linear stack of layers (most beginner cases) | Very high |
| Functional API | inputs = layers.Input(…) x = layers.Dense(…)(inputs) | Complex graphs, multiple inputs/outputs, branches | High |
| Subclassing (custom) | class MyModel(keras.Model): def call(self, x): … | Very custom behavior, research, control flow | Medium (research) |
Step 8: Final Teacher Summary (Repeat This!)
A TensorFlow model = the complete, trained, savable object that contains:
- Architecture (layers & connections)
- Trained weights
- Ability to predict on new data
- Option to save/load/deploy
In Hyderabad 2026:
- Every property site uses regression models like the flat price one
- Medical apps use CNN models like the MNIST one (but for X-rays)
- You can train on your laptop → deploy to phone/web with TensorFlow Lite / TensorFlow.js
Understood the full concept now? 🌟
Want next?
- How to convert this model to TensorFlow.js / TFLite?
- Full functional API example with multiple inputs?
- Save/load custom subclassed model?
Just tell me — class is still in session! 🚀
