This lab uses the WHO life expectancy dataset to build a regression model with the TensorFlow Keras Sequential API. The notebook above covers loading the data, inspecting it and filling missing values. The sections below fix the data-cleaning code, then add the remaining steps: encoding and scaling the features, defining and training the Sequential model, evaluating it with R², and saving it.
What this lab builds
The goal is to predict Life expectancy (a continuous value in years) from 19 health and economic indicators per country and year. That makes this a regression problem. A Keras Sequential model fits well here: it is a plain stack of layers where each layer has one input and one output, and that is all a tabular regressor needs.
| Stage | What happens | Tooling |
|---|---|---|
| Load and inspect | Read the CSV, check shape, dtypes and null counts | pandas |
| Clean | Fill gaps with each country's mean, drop rows still missing values | pandas |
| Prepare | Drop Country, encode Status, split into train and test sets, scale | scikit-learn |
| Model | Stack Dense layers in keras.Sequential | TensorFlow / Keras |
| Train | Fit with a validation split, early stopping and TensorBoard | Keras callbacks |
| Evaluate | Compare predictions with the test set using MAE and R² | scikit-learn |
Prerequisites and setup
Use Python 3 in a virtual environment. Install the libraries that the notebook imports:
python3 -m venv tf-lab
source tf-lab/bin/activate
pip install --upgrade pip
pip install tensorflow pandas numpy scikit-learn matplotlib seaborn jupyter
python -c "import tensorflow as tf; print(tf.__version__)"Code language: JavaScript (javascript)
Download the Kaggle dataset kumarajarshi/life-expectancy-who. The CSV in that download is usually named Life Expectancy Data.csv, but the notebook reads datasets/life_expectancy.csv, so rename the file to match:
mkdir -p datasets
mv "Life Expectancy Data.csv" datasets/life_expectancy.csvCode language: JavaScript (javascript)
Corrected data cleaning
The cleaning code above has three problems. Several column names in the CSV have stray spaces ('Life expectancy ', ' BMI ', 'Diphtheria ', ' HIV/AIDS'), so the code has to copy those spaces exactly. Schooling has 163 nulls but is missing from na_cols, so all of those rows are later thrown away by dropna(). And the target column is filled with averages, which means the model partly learns from made-up labels. The version below strips the column names, fills every feature in one vectorised groupby, and drops rows with no target instead of imputing it.
data = pd.read_csv('datasets/life_expectancy.csv')
# Remove leading/trailing spaces and collapse double spaces in column names
data.columns = data.columns.str.strip().str.replace(r'\s+', ' ', regex=True)
TARGET = 'Life expectancy'
# Never impute the label: drop rows where it is missing
data = data.dropna(subset=[TARGET])
# Fill numeric features with the mean of the same country
feature_cols = [c for c in data.select_dtypes('number').columns if c != TARGET]
data[feature_cols] = (
data.groupby('Country')[feature_cols]
.transform(lambda s: s.fillna(s.mean()))
)
# Countries with no value at all for a column still have NaN; drop those rows
data = data.dropna()
print(data.shape)
print(data.isna().sum().sum()) # should print 0Code language: PHP (php)
Note: Because Schooling is now imputed too, you will usually keep more rows than the (2128, 22) shown above. The exact count depends on which countries have no data at all for a column.
Preparing features for the network
Neural networks only accept numbers, and they train best when inputs are on similar scales. Country is an identifier with 133 values, so drop it. Status has only two values, so map it to 0 or 1. Split the data before scaling, and fit the scaler on the training set only. If the scaler sees the test set, statistics from that set leak into training.
from sklearn.model_selection import train_test_split
df = data.drop(columns=['Country'])
df['Status'] = (df['Status'] == 'Developed').astype(int)
X = df.drop(columns=[TARGET]).values.astype('float32')
y = df[TARGET].values.astype('float32')
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train) # fit on train only
X_test_s = scaler.transform(X_test) # reuse train statistics
print(X_train_s.shape, X_test_s.shape)Code language: PHP (php)
Defining the Sequential model
tf.random.set_seed(42)
model = keras.Sequential([
layers.Input(shape=(X_train_s.shape[1],)),
layers.Dense(64, activation='relu'),
layers.Dense(32, activation='relu'),
layers.Dense(1) # linear output for regression
], name='life_expectancy_regressor')
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=1e-3),
loss='mse',
metrics=['mae']
)
model.summary()Code language: PHP (php)
layers.Input(shape=(n_features,))declares the input size, which lets Keras build the model and printsummary()straight away. Current Keras prefers this to passinginput_shapeto the firstDenselayer.Dense(..., activation='relu')hidden layers let the model learn non-linear relationships, for example how HIV/AIDS rates and schooling interact.Dense(1)has no activation, so it can output any real number. A sigmoid or softmax here would be wrong for regression.loss='mse'is the standard regression loss.maeis reported alongside it because it reads directly in years.
Training and evaluating
The os and datetime imports above are there to build a timestamped TensorBoard log directory. Early stopping watches the validation loss, stops training once it stops improving, and restores the best weights.
log_dir = os.path.join('logs', datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
callbacks = [
keras.callbacks.EarlyStopping(monitor='val_loss', patience=15,
restore_best_weights=True),
keras.callbacks.TensorBoard(log_dir=log_dir)
]
history = model.fit(
X_train_s, y_train,
validation_split=0.2,
epochs=300,
batch_size=32,
callbacks=callbacks,
verbose=0
)
print('Epochs run:', len(history.history['loss']))
test_mse, test_mae = model.evaluate(X_test_s, y_test, verbose=0)
y_pred = model.predict(X_test_s, verbose=0).flatten()
print(f'Test MAE: {test_mae:.2f} years')
print(f'Test R2 : {r2_score(y_test, y_pred):.3f}')
plt.plot(history.history['loss'], label='train')
plt.plot(history.history['val_loss'], label='validation')
plt.xlabel('Epoch'); plt.ylabel('MSE'); plt.legend(); plt.show()Code language: PHP (php)
An R² close to 1 means the model explains most of the variance in life expectancy, and 0 means it does no better than always predicting the mean. If the validation curve flattens or rises while the training curve keeps falling, the model is overfitting. Early stopping already limits this, and a layers.Dropout(0.2) between the hidden layers is another common fix. To view the logs, run tensorboard --logdir logs and open the URL it prints.
Saving and reusing the model
import joblib
model.save('life_expectancy.keras') # native Keras format
joblib.dump(scaler, 'scaler.joblib') # the scaler is part of the model
loaded = keras.models.load_model('life_expectancy.keras')
scaler = joblib.load('scaler.joblib')
print(loaded.predict(scaler.transform(X_test[:3]), verbose=0).flatten(), y_test[:3])Code language: PHP (php)
Note: Recent Keras releases require an explicit .keras or .h5 extension in model.save(). Always save the fitted scaler with the model. Predictions on unscaled input are meaningless.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
KeyError: 'Life expectancy' | The real column name has a trailing space | Strip the column names with data.columns.str.strip() |
FileNotFoundError: datasets/life_expectancy.csv | The Kaggle file has a different name or is in another folder | Rename the file or change the path in read_csv |
ValueError: could not convert string to float: 'Developing' | Text columns were passed to the model | Drop Country and encode Status as 0 or 1 |
Loss shows nan | NaNs are left in the data, or the features are unscaled | Check that isna().sum().sum() is 0 and apply StandardScaler |
| Very high MSE that barely drops | The learning rate is too low or the features are unscaled | Scale the inputs and try learning_rate=1e-3 or 3e-3 |
Frequently asked questions
When should I use the Keras Sequential API instead of the Functional API?
Use Sequential when the model is a single linear stack of layers with one input and one output, like this regressor. Switch to the Functional API if you need multiple inputs or outputs, shared layers or skip connections.
Why does the output layer have no activation function?
Regression targets such as life expectancy can be any real number. A linear output of Dense(1) with no activation is not restricted to a range, while sigmoid or softmax would squash predictions into 0 to 1.
Why scale features before training a neural network?
Features like GDP and Population are orders of magnitude larger than BMI or HIV/AIDS rates. Without scaling, gradient descent converges slowly or unstably. StandardScaler gives every feature a mean of zero and a variance of one.
Should I fit StandardScaler before or after train_test_split?
After. Fit it on the training data only, then apply the same scaler to the test data. Otherwise test-set statistics leak into training and the evaluation looks better than it really is.
How many epochs should I train for?
Set a generous upper limit and let the EarlyStopping callback stop training once validation loss stops improving. With restore_best_weights=True, you keep the best weights rather than the ones from the last epoch.
Related tutorials
- More Machine Learning tutorials
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals