Your First Keras Model — TensorFlow 2.x Sequential API
Lesson opener
In one line: How to build a neural network with tensorflow.keras Sequential API.
Why it matters: Keras is the standard high-level API for learning and shipping nets.
Before this lesson: Forward pass & backprop / Feature engineering
Before you start
| Resource | Link |
|---|---|
| Previous | Forward pass & backprop |
| Next | Epochs & early stopping |
| Prerequisites | Forward pass & backprop, Feature engineering |
| Time | ~55 minutes |
What you will learn
- How to build a neural network with
tensorflow.kerasSequential API - Choosing layers, activations, and compile settings for churn
- Training with
.fit()and evaluating on held-out data - TF 2.x defaults — eager execution, no session boilerplate
TensorFlow 2.x + Keras
The problem it solves: NumPy loops teach intuition; production needs GPU-ready frameworks. Keras (built into TensorFlow 2.x as tf.keras) handles forward pass, backprop, and optimisers.
import tensorflow as tf
print(tf.__version__) # expect 2.xWHY Keras is the standard high-level API for learning and shipping nets.
WHEN Tabular deep learning experiments, or before CNN/RNN modules.
Prepare data — same churn problem
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
df = pd.read_csv("data/customers.csv")
X = pd.get_dummies(
df[["tenure_months", "monthly_spend", "support_tickets", "segment"]],
drop_first=True,
)
y = df["churned"].values
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)WHY Neural nets need scaled numeric inputs.
WHEN Always for tabular nets — fit scaler on train only.
Build Sequential model
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Input(shape=(X_train_s.shape[1],)),
layers.Dense(16, activation="relu"),
layers.Dense(8, activation="relu"),
layers.Dense(1, activation="sigmoid"),
])
model.summary()Breaking it down:
Input(shape=(n_features,))— one row of customer featuresDense(16, activation="relu")— 16 hidden units- Final
Dense(1, sigmoid)— churn probability (binary) model.summary()— parameter count (~200–400 for this size)
Architecture rule of thumb: Start small (16 → 8 → 1) on tabular data; grow only if underfitting.
Compile — loss, optimiser, metrics
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=0.001),
loss="binary_crossentropy",
metrics=["accuracy", keras.metrics.AUC(name="auc")],
)| Setting | Choice | Why |
|---|---|---|
loss | binary_crossentropy | Binary classification + MLE |
optimizer | Adam | Adaptive learning rate — good default |
metrics | AUC | Better than accuracy on imbalanced churn |
WHY Compile wires loss to backprop and picks the update rule.
WHEN Once per model architecture — recompile if you change structure.
Train — .fit()
history = model.fit(
X_train_s, y_train,
validation_split=0.2,
epochs=50,
batch_size=32,
verbose=1,
)
test_loss, test_acc, test_auc = model.evaluate(X_test_s, y_test, verbose=0)
print(f"Test AUC: {test_auc:.3f}")Breaking it down:
validation_split=0.2— hold 20% of train for validation during fitepochs=50— 50 passes through training databatch_size=32— mini-batch gradient descenthistory— loss curves for plotting (dl4)
Use this when: benchmarking neural net vs random forest capstone.
Predict probabilities
proba = model.predict(X_test_s, verbose=0).flatten()
pred = (proba >= 0.5).astype(int)
from sklearn.metrics import classification_report
print(classification_report(y_test, pred, target_names=["Stayed", "Churned"]))WHY Same evaluation mindset as sklearn — test set only once for final numbers.
WHEN Presenting to stakeholders — compare AUC to forest baseline.
Save and reload
model.save("outputs/churn_keras_model.keras")
loaded = keras.models.load_model("outputs/churn_keras_model.keras")Indian workplace example: Pune analytics exports .keras file to engineering for batch scoring — same pattern as joblib in ml-sklearn-intro.
Sequential vs Functional API (preview)
Sequential — stack layers line by line (this lesson).
Functional API — branch/merge layers (needed for transfer learning in lesson 7).
Stick with Sequential until you need multiple inputs or shared layers.
Essential commands
| Command / action | What it does |
|---|---|
keras.Sequential([...]) | Linear stack of layers |
layers.Dense(n, activation="relu") | Fully connected layer |
model.compile(optimizer, loss, metrics) | Training configuration |
model.fit(X, y, epochs, batch_size) | Train network |
model.predict(X) | Probability scores |
model.evaluate(X_test, y_test) | Held-out metrics |
Practice
Do this now: Build, compile, and train the Sequential churn model. Report test AUC. Compare to your ML capstone random forest — which won? Write one sentence on whether the extra complexity was worth it.
Checklist
- [ ] Sequential model built with Input, Dense, sigmoid output
- [ ]
binary_crossentropy+ Adam compile - [ ] Scaler fit on train only
- [ ] Evaluated on held-out test set
- [ ] Next: Epochs & early stopping