At a Glance
- Fine-tuned an ImageNet-pretrained ResNet50 to predict a shopper's age from a face photo, helping a supermarket chain comply with alcohol-sale laws
- Reached a final validation MAE of 7.65 years (best 6.64 at epoch 17), under the 8-year target, across 7,591 labeled photos. Passed review on the second submission
- Python, TensorFlow/Keras, ResNet50, ImageDataGenerator, Pandas, Matplotlib, GPU training
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.
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.
Skills Acquired
- Transfer learning: reused a ResNet50 trained on ImageNet (
include_top=False) and fine-tuned it for age regression instead of training a CNN from scratch on a moderate-size dataset. - TensorFlow / Keras:
Sequential,GlobalAveragePooling2D,DenseandAdamfor the model, andflow_from_dataframewithclass_mode='raw'to feed a numeric target. - Image data pipelines: batch loading from disk, pixel rescaling to [0, 1], resizing to 224×224, and a seeded
validation_splitso the training and validation subsets never overlap. - Data augmentation: horizontal flips on training data only, because a mirrored face keeps the same age and validation results should stay unaltered.
- Exploratory analysis of image data: label distribution, data-quality checks, and visual inspection of sample photos for rotation, lighting, color and occlusions.
- GPU workflow: packaged the loader, model and training functions into a standalone script with
inspect.getsourceand ran it on a remote GPU platform. - Reading training logs: diagnosed overfitting and an unstable epoch from per-epoch training and validation metrics.
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.
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
- Why transfer learning beats training a CNN from scratch on a few thousand images
- How to stream thousands of images with
ImageDataGeneratorinstead of loading them all into memory - Why augmentation belongs on the training set only, and why horizontal flips suit face data
- How to spot overfitting and instability in a 20-epoch training log
- How to turn a regression metric into a practical business recommendation
Key Takeaways
- Target met: final validation MAE of 7.65 years, under the 8-year requirement. The margin is thin, so I treat it as a pass, not a comfortable one
- Best epoch was 17, with a validation MAE of 6.64. Early stopping with
restore_best_weights=Truewould have kept that model - Overfitting: by epoch 20 training MAE (3.18) was less than half of validation MAE (7.65)
- One unstable epoch: validation MAE spiked to 11.46 at epoch 12, then recovered at epoch 13
- Business verdict: useful as a screening filter that prompts ID checks, not as an automatic age gate
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.
| Column | Type | Description |
|---|---|---|
file_name | String | Image file in final_files/ (e.g. 000000.jpg) |
real_age | Integer | TARGET: age in years (1–100) |
- The distribution is right-skewed, peaking around ages 25–30. Most photos are of people in their 20s and 30s.
- Sparse groups: school-age children (about 5–14) and adults over 60. Very few photos are above 80.
- There is a cluster at ages 1–3, and spikes at round ages (50, 60, 70) that suggest some labels were estimated.
- Many photos fall in the 15–25 range, which is the zone that matters most for the alcohol decision.
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.
↓
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
⚡ Try It — Interactive Chart
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.
| Epoch | Train MAE | Val MAE | Note |
|---|---|---|---|
| 1 | 7.43 | 8.49 | Above target |
| 6 | 5.22 | 7.03 | First epoch under 8 for good |
| 12 | 4.04 | 11.46 | Instability spike |
| 17 | 3.22 | 6.64 | Best validation epoch |
| 20 | 3.18 | 7.65 | Final 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
| Metric | Value | Notes |
|---|---|---|
| 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.
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
- Transfer learning makes moderate datasets workable. ResNet50 already knows edges, textures and shapes from ImageNet, so 7,591 photos were enough to learn age cues on top of that.
- Let the EDA choose the augmentation. Flips keep a face's age, and the photos were already rotated, so heavy rotation would only add noise.
- The last epoch is not always the best epoch. Without early stopping, I kept a model about one year worse than my best.
- An average metric can hide the cases that matter. MAE across ages 1–100 says little about accuracy at 17–21, where the legal decision is made.
- Passing the metric is not the same as solving the problem. The honest recommendation is a cashier-assist tool, not an automatic age gate.
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 Requirement | Status |
|---|---|
| Exploratory data analysis performed | COMPLETE ✓ |
| EDA results presented in the notebook | YES — histogram + 15-photo grid ✓ |
| Model training code included | YES — 4 functions + GPU script ✓ |
| Training output included | YES — full 20-epoch log ✓ |
| Validation MAE ≤ 8 | 7.65 ✓ |
| Findings based on model results | YES — business recommendation ✓ |
Want to Explore the Full Notebook?
The complete EDA, model code, GPU script and training log are on GitHub.