← Back to Projects

At a Glance

Age verification computer vision project demo: sample photos, age distribution and training curve
01

Problem

The supermarket chain Good Seed must not sell alcohol to underage customers. Checkout cameras already capture a photo whenever someone buys alcohol, so the business question was: can computer vision estimate a customer's age from that photo well enough to help cashiers decide when to check ID?

The technical goal was a regression model that predicts age in years from a face image, with a validation Mean Absolute Error (MAE) of 8 years or less. MAE is the average size of the prediction error, so an MAE of 8 means predictions are off by about 8 years on average.


02

Solution

I explored the 7,591 labeled photos first, then used what I found to make modelling choices. I streamed the images from disk in batches with Keras ImageDataGenerator, split the data 75/25 into training and validation sets, and applied horizontal flips to the training set only. The model is a ResNet50 backbone pre-trained on ImageNet, followed by global average pooling and a single output neuron. I trained it end-to-end on a GPU for 20 epochs with Adam (learning rate 0.0001), MSE loss and MAE as the metric.

The final validation MAE was 7.65 years, which meets the target. My conclusion for the business was that the model works as a screening aid, not a replacement for ID checks, because a 7–8 year average error cannot reliably tell a 17-year-old from a 21-year-old.


03

Skills Acquired


04

Deep Dive

Age estimation is harder than it looks. Two people of the same age can look very different, and the same person can look years older or younger depending on lighting, angle, makeup, glasses or a hat. The labels themselves are imperfect too. Spikes at round ages such as 50, 60 and 70 in this dataset suggest that some ages were estimated rather than exact.

A model that meets the MAE target overall can still be weak exactly where the business needs it most. The decision Good Seed cares about happens around age 21, but MAE averages errors across ages 1 to 100.

Why This Project?

This was Sprint 14 of my TripleTen AI and Machine Learning Bootcamp, the computer vision sprint. Sprint 12 introduced neural networks on tabular data. This sprint moved to convolutional networks, image pipelines and transfer learning, which is how most production vision systems are built today.

The project also asks a responsible-AI question: what is a model with this error rate actually good for? Answering that honestly, instead of stopping at "the metric passed," is the part that carries over to real deployments.


What You'll Learn from This


Key Takeaways


The Dataset

A folder of 7,591 face photos plus a labels.csv file mapping each file name to the person's real age. There are no missing values and no duplicate file names, and the image generator found a photo for every label.

ColumnTypeDescription
file_nameStringImage file in final_files/ (e.g. 000000.jpg)
real_ageIntegerTARGET: age in years (1–100)
Histogram of ages in the dataset with a dashed line at the legal drinking age of 21
Age distribution of all 7,591 photos, with the legal drinking age (21) marked. Notebook output.
Grid of 15 sample face photos from the dataset, each titled with the person's age
One batch of 15 photos from the generator, with their labeled ages. Notebook output.
The faces are already cropped and centered, so no face-detection step is needed. But the photos vary a lot: some are rotated with black borders, one is black-and-white, some are dark, and several have glasses, caps, a veil or a microphone partly covering the face. All of these hide age cues and make prediction harder.

Model Architecture

ResNet50 without its classification head turns each 224×224 photo into a 7×7×2048 feature map. Global average pooling collapses that into one 2048-value vector per image, and a single dense neuron turns the vector into an age. The ReLU activation on the output keeps predictions non-negative. All layers, including the backbone, were trainable.

Input (224 × 224 × 3, pixels rescaled to [0, 1])
  ↓
ResNet50 backbone ← ImageNet weights, include_top=False, fine-tuned
  ↓ (7 × 7 × 2048)
GlobalAveragePooling2D ← one 2048-value vector per image
  ↓
Dense(1, ReLU) ← predicted age in years (non-negative)

Optimizer: Adam (lr = 0.0001)  |  Loss: MSE  |  Metric: MAE  |  Batch size: 16  |  Epochs: 20

My Process

Part 1

Load Labels & Stream Images

The labels load as a normal CSV file. The 7,591 photos are too many to hold in memory at once, so a generator reads them from disk in batches and confirms that every label has a matching file.

labels = pd.read_csv('/datasets/faces/labels.csv')   # 7,591 rows, 2 columns, no nulls

# Read photos in batches instead of all at once
datagen = ImageDataGenerator(rescale=1./255)
gen_flow = datagen.flow_from_dataframe(
    dataframe=labels,
    directory='/datasets/faces/final_files/',
    x_col='file_name',
    y_col='real_age',
    target_size=(224, 224),
    class_mode='raw',      # numeric target for regression
    batch_size=32,
    seed=12345
)
# Found 7591 validated image filenames.

Part 2

Exploratory Data Analysis

I checked data quality, plotted the age distribution with the legal drinking age marked, and displayed a batch of 15 photos to see what the model would actually be looking at (both figures are shown in The Dataset above).

print(f"Duplicate file names: {labels['file_name'].duplicated().sum()}")  # 0
print(f"Age range: {labels['real_age'].min()} to {labels['real_age'].max()}")  # 1 to 100

labels['real_age'].hist(bins=50, figsize=(10, 5))
plt.axvline(21, color='red', linestyle='--', label='Legal drinking age (21)')

# Display 15 sample photos with their ages
images, ages = next(gen_flow)
for i in range(15):
    fig.add_subplot(3, 5, i + 1)
    plt.imshow(images[i])
    plt.title(f"Age: {int(ages[i])}")

The EDA drove three modelling decisions: use transfer learning because 7,591 images is moderate for deep learning, use horizontal flips only because some photos are already rotated, and expect larger errors for school-age children and adults over 60.

Part 3

Train / Validation Loaders

Both loaders use the same dataframe, the same validation_split=0.25 and the same seed, so the two subsets never overlap. Only the training generator flips images.

def load_train(path):
    labels = pd.read_csv(path + 'labels.csv')
    train_datagen = ImageDataGenerator(
        validation_split=0.25,
        rescale=1./255,
        horizontal_flip=True          # augmentation: training only
    )
    return train_datagen.flow_from_dataframe(
        dataframe=labels, directory=path + 'final_files/',
        x_col='file_name', y_col='real_age',
        target_size=(224, 224), batch_size=16,
        class_mode='raw', subset='training', seed=12345
    )

# load_test() is identical except: no horizontal_flip, subset='validation'

Part 4

Build the Model

A small learning rate (0.0001) lets the pre-trained weights adapt to faces without being overwritten by large early updates. MSE is the training loss, and MAE is tracked because it is the business metric and is easy to read in years.

def create_model(input_shape):
    backbone = ResNet50(
        input_shape=input_shape,
        weights='imagenet',
        include_top=False
    )
    model = Sequential()
    model.add(backbone)
    model.add(GlobalAveragePooling2D())
    model.add(Dense(1, activation='relu'))

    model.compile(optimizer=Adam(learning_rate=0.0001),
                  loss='mse', metrics=['mae'])
    return model

Part 5

Train on the GPU Platform

The notebook writes the imports and the four functions into run_model_on_gpu.py with inspect.getsource, so the script that runs on the GPU matches the notebook exactly. Training ran for 20 epochs at 356 steps per epoch, about 35 seconds each.

with open('run_model_on_gpu.py', 'w') as f:
    f.write(init_str)
    for fn_name in [load_train, load_test, create_model, train_model]:
        f.write(inspect.getsource(fn_name))

# GPU log, last epoch:
# Epoch 20/20  356/356 - 35s - loss: 17.0187 - mae: 3.1785 - val_loss: 93.4115 - val_mae: 7.6512

⚡ Try It — Interactive Chart

Training vs. validation MAE for all 20 epochs, from the GPU training log

⚡ Try It — Interactive Chart

Training vs. validation loss (MSE) for all 20 epochs, from the GPU training log

Part 6

Read the Training Log

Training MAE fell steadily from 7.43 to 3.18. Validation MAE improved more slowly. It stayed below 8 from epoch 6 onward with one exception, and it settled between about 6.6 and 7.7 after epoch 8.

EpochTrain MAEVal MAENote
17.438.49Above target
65.227.03First epoch under 8 for good
124.0411.46Instability spike
173.226.64Best validation epoch
203.187.65Final model, meets target

Two things stand out. First, overfitting: training error kept falling while validation error flattened, and validation loss jumped from about 81 to 93.41 in the final epoch alone. Second, the epoch 12 spike to 11.46 is the kind of instability you get when fine-tuning a large network on a moderate dataset. Because I trained a fixed 20 epochs with no early stopping, the saved model is the epoch 20 model (7.65), not the stronger epoch 17 model (6.64).


Final Results

MetricValueNotes
Final validation MAE 7.65 years Target ≤ 8: met, with a thin margin
Best validation MAE 6.64 years Epoch 17, not kept (no early stopping)
Final training MAE 3.18 years Less than half of validation: overfitting
Validation MAE range 6.64 – 11.46 Spike at epoch 12
Reviewer status PASSED — Iteration 2 ✓ Revision made the sample photos visible and completed the checklist

Can Computer Vision Help Good Seed?

Yes, as a support tool, not as a replacement for ID checks. An average error of 7–8 years is too large to separate a 17-year-old from a 21-year-old. A 17-year-old could easily be predicted as 24 or 25.

A practical design is a screening filter. If the predicted age is below a safe threshold (for example under 30, roughly 21 plus the MAE), the register prompts the cashier to check ID. Customers who clearly look older pass through without delay. The final decision stays with staff.

That threshold has a cost. Most shoppers in this data are in their 20s and 30s, so an "under 30" rule would still flag a large share of customers. Raising the threshold catches more minors but saves fewer ID checks, and this trade-off should be set with the business, not by the model.

The same model could also support customer analytics (age groups by store, time of day or season), other age-restricted products such as tobacco or lottery tickets, and self-checkout flagging for staff review.


Main Takeaways


What I Learned & Why It Matters to Employers

Sprint 14 took me from tabular neural networks to computer vision: image pipelines, pre-trained CNNs and GPU training. The more valuable lesson was judgment. The model met its target, but reading the log showed overfitting, an unstable epoch and a better checkpoint I didn't keep. Thinking about the business showed that a 7.65-year average error can't make a legal decision on its own. Being able to say clearly what a model can and cannot be trusted with is what makes a vision system safe to deploy.

Conclusion & Reflections

A fine-tuned ResNet50 estimated age from face photos with a final validation MAE of 7.65 years, meeting the project target. Transfer learning did most of the heavy lifting, and the EDA shaped the augmentation and set realistic expectations for where the model would struggle.

If I had more time, I would add EarlyStopping(restore_best_weights=True) and a ReduceLROnPlateau schedule to keep the best epoch and smooth spikes like epoch 12. I would add Dropout or freeze part of the backbone to narrow the train/validation gap, and measure MAE specifically on ages 15–25. I would also try a direct "under 21 vs. 21+" classifier, which matches the business question more closely than predicting an exact age.

Project RequirementStatus
Exploratory data analysis performedCOMPLETE ✓
EDA results presented in the notebookYES — histogram + 15-photo grid ✓
Model training code includedYES — 4 functions + GPU script ✓
Training output includedYES — full 20-epoch log ✓
Validation MAE ≤ 87.65 ✓
Findings based on model resultsYES — business recommendation ✓

Want to Explore the Full Notebook?

The complete EDA, model code, GPU script and training log are on GitHub.