aiml

Lesson 3 of 21Module 2

Train, save and reload the user-return model

Prepare historical user-return examples, fit and evaluate a baseline, then reload its saved scaler and model to predict in a fresh process.

Prerequisites

Python functions, lists, dictionaries and CLI commands; basic features, labels and training. Complete the application and evaluation-date lessons first.

Preparation and term definitions

By the end, you can

  • Construct historical features and finalized labels using separate time cutoffs.
  • Fit preprocessing and model parameters on training data, then compare validation predictions.
  • Reload the saved full-precision model in a fresh process and reproduce its prediction.
Runtime
Python 3.12+; local CPU
Dependencies
Python standard library and SQLite

Lab code, tests and fixtures (ZIP, 1.6 MB)Quiz check your understanding

Progress is saved in this browser.

Problem

When you need this. A product analyst wants daily estimates of whether existing users will return during the following 24 hours. Before introducing registries, deployment or monitoring, the application needs a working path from historical data to a reusable prediction.

This lab builds that path with a single input: the count of recent events available before prediction. The model is deliberately small, so you can inspect the feature, training split, saved parameters and reload behavior.

Concepts

A feature is an input available at prediction time. A label is the later observed outcome. A model learns from training examples; validation examples let you inspect its behavior without fitting on them.

For a noon prediction, count events in the preceding 24 hours only if they arrived before noon. The target is a return between noon and noon the next day. In this fictional dataset, the label becomes ready two hours after that outcome window ends.

The baseline is logistic regression: it multiplies a standardized event count by a learned weight, adds a bias and maps the score to a value between zero and one. Standardization subtracts the training mean and divides by the training standard deviation. Keeping those two fitted values with the weights lets a later process apply the same calculation.

The fixture authors the labels as separate, finalized records; they do not come from the partial feature-event log. With real data, the label collector has to decide when an outcome is complete.

Architecture

Events + labelsoriginal synthetic fixturePrepare examplesrespect both time windowsFit baselinetraining rows onlySaved modelweights + fitted scalerRecent event countthe same feature definitionLoad + predictnew Python processReturn predictionprobability + decisionmodel fileEvents + labelssynthetic fixturePrepare examplesrespect time windowsFit baselinetraining rows onlySaved modelweights + fitted scalerRecent event countsame feature definitionLoad + predictnew Python processReturn predictionprobability + decision
The saved file contains the model and preprocessing needed for inference. The separate evaluation command reads validation rows; it does not refit the model. Tracking servers, pipeline orchestration and HTTP serving are later syllabus work.

workflow.py reuses the existing data-availability assembler and the existing baseline’s fitting functions. It configures the feature and class names for this application.

Working code

Download and unzip the complete lab, enter mlops-return-workflow/, then create an environment. No package installation is required.

Create the local environmentTerminal · bash
python3.12 -m venv .venv
source .venv/bin/activate

On PowerShell, activate with .venv\Scripts\Activate.ps1. Use a fresh output directory for another attempt; the commands refuse to replace existing files.

Prepare examples from events and labels

The assembler excludes events that arrived too late and admits a label only after its reporting delay. It then assigns the declared date windows.

Prepare the cohortTerminal · bash
python workflow.py prepare --out work/cohort.json

The recorded run produced 240 examples: 144 training, 48 validation and 48 test. The validation and test rows are later observations of the same users, so they do not test the model on unseen users. Gaps separate the training, validation and test outcome windows.

Fit the baseline and inspect validation predictions

Fit the scaler and logistic model on training rows only. Save their full-precision values, then evaluate the frozen candidate on the validation window.

Train and evaluateTerminal · bash
python workflow.py train --cohort work/cohort.json --out work/candidate.json
python workflow.py evaluate --cohort work/cohort.json --model work/candidate.json --out work/validation.json

In the saved synthetic run, the model correctly classified 29 of 48 validation examples. The majority rule, which always predicts the more common training outcome, correctly classified 27. These small synthetic results show how to compare the two; they do not show that this feature is useful for a real product. The saved walkthrough did not evaluate the final test window.

Report the majority-rule count beside every candidate’s result. Without it, an accuracy figure does not tell you whether the feature adds anything beyond the class balance.

Load the saved model in a new process

The next command starts a fresh Python process and reads candidate.json. That file holds the fitted scaler and weights needed for inference; an evaluation report alone would not be enough.

Predict from the saved modelTerminal · bash
python workflow.py predict --model work/candidate.json --event-count 3
Saved fresh-process predictionRecorded output · jsonDownload
{
  "event_count": 3,
  "return_probability": 0.40381146876849405,
  "predicted_return": 0
}

The supplied count is 3. Read the logistic score as an estimated return probability; this lab does not check its calibration. The declared 0.5 threshold converts it into a binary decision.

Inspect the complete command output
Actual local workflow runRecorded output · textDownload
$ python workflow.py prepare --out recorded/cohort.json
{
  "written": "recorded/cohort.json",
  "rows": 240,
  "splits": {
    "training": 144,
    "validation": 48,
    "test": 48
  }
}

$ python workflow.py train --cohort recorded/cohort.json --out recorded/candidate.json
{
  "written": "recorded/candidate.json",
  "training_rows": 144,
  "features": [
    "recent_event_count"
  ]
}

$ python workflow.py evaluate --cohort recorded/cohort.json --model recorded/candidate.json --out recorded/validation.json
{
  "split": "validation",
  "rows": 48,
  "correct": 29,
  "accuracy": 0.6041666666666666,
  "majority_correct": 27,
  "model_sha256": "6ec6c622ac475213b6b13723e5cb8cdeb14d5bdccd93ca2ee42ba0d684917ab7",
  "cohort_sha256": "bacaa0053ffd5fd844af307b5ee5370515a4f99dea02a2fa7b76e7122c2ccf6b",
  "execution": "fresh local CPU fit; authored synthetic labels"
}

$ python workflow.py predict --model recorded/candidate.json --event-count 3
{
  "event_count": 3,
  "return_probability": 0.40381146876849405,
  "predicted_return": 0
}

The saved run wrote to recorded/; your commands write to work/. Run metadata and source identities.

Inspect workflow.py
workflow.pySource · pythonDownload
"""One local user-return workflow: prepare, train, evaluate, export and predict.

The synthetic fixture describes existing users. A prediction estimates a return
in the following 24 hours from the event count known in the preceding 24 hours.
No orchestration, registry, HTTP serving or production measurement is claimed.
"""
import argparse
import hashlib
import json
import math
from pathlib import Path
from vendor import availability, baseline

HERE = Path(__file__).resolve().parent
FEATURE = 'recent_event_count'
PROJECT = 'user-return-24h-v1'
# Reuse the published baseline's fitting and scaling arithmetic. Only this
# standalone adapter configures its feature and class names; Rice files/results
# are never loaded, altered or relabelled as user-return results.
baseline.FEATURES = [FEATURE]
baseline.LABELS = ['not_returned', 'returned']
baseline.POSITIVE = 'returned'


def strict_json(path):
    def unique(pairs):
        result = {}
        for key, value in pairs:
            if key in result:
                raise ValueError('duplicate JSON field: ' + key)
            result[key] = value
        return result
    def reject(value):
        raise ValueError('non-finite JSON value: ' + value)
    return json.loads(Path(path).read_text(), object_pairs_hook=unique, parse_constant=reject)


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def save(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open('x') as file:
        file.write(json.dumps(value, indent=2, allow_nan=False) + '\n')


def partition(at):
    day = availability.instant(at).date().isoformat()
    for name, start, end in [('training', '2026-01-03', '2026-01-08'),
                             ('validation', '2026-01-10', '2026-01-11'),
                             ('test', '2026-01-13', '2026-01-14')]:
        if start <= day <= end:
            return name
    return 'excluded'


def prepare(source):
    fixture = strict_json(source)
    result = availability.assemble(fixture['observations'], fixture['events'],
                                   fixture['labels'], fixture['assemble_at'])
    rows = [dict(row, split=partition(row['predict_at'])) for row in result['rows']]
    return {'format': 'return-cohort-v1', 'project': PROJECT, 'feature': FEATURE,
            'source_sha256': sha(source), 'as_of': result['as_of'], 'rows': rows,
            'excluded': result['excluded']}


def cohort(path):
    data = strict_json(path)
    if (not isinstance(data, dict) or data.get('format') != 'return-cohort-v1'
            or data.get('project') != PROJECT or data.get('feature') != FEATURE
            or not isinstance(data.get('rows'), list) or not data['rows']):
        raise ValueError('unsupported or empty cohort')
    ids = set()
    for row in data['rows']:
        if not isinstance(row, dict):
            raise ValueError('each cohort row must be an object')
        availability.check_id(row.get('id'))
        if row['id'] in ids:
            raise ValueError('duplicate cohort observation')
        ids.add(row['id'])
        count(row.get('feature_count'))
        if type(row.get('label')) is not int or row['label'] not in (0, 1):
            raise ValueError('label must be integer 0 or 1')
        if row.get('split') != partition(row.get('predict_at')):
            raise ValueError('row differs from the declared time split')
        if row['split'] == 'excluded':
            raise ValueError('cohort contains a row from a gap or unsupported window')
    return data


def count(value):
    if type(value) is not int or not 0 <= value <= 1000:
        raise ValueError('event count must be an integer between 0 and 1000')
    return value


def train(path):
    data = cohort(path)
    rows = [dict(x=[row['feature_count']], label='returned' if row['label'] else 'not_returned')
            for row in data['rows'] if row['split'] == 'training']
    if {row['label'] for row in rows} != set(baseline.LABELS):
        raise ValueError('training needs both outcome classes')
    scaler = baseline.fit_scaler(rows)
    fitted = baseline.train_logistic(rows, scaler)
    return {'format': 'return-model-v1', 'project': PROJECT, 'features': [FEATURE],
            'cohort_sha256': sha(path), 'training_rows': len(rows),
            'preprocessing': scaler,
            'estimator': {'weights': fitted['weights'], 'bias': fitted['bias']},
            'training_positive_rate': sum(r['label'] == 'returned' for r in rows) / len(rows),
            'settings': {'epochs': baseline.EPOCHS, 'learning_rate': baseline.LEARNING_RATE,
                         'threshold': 0.5, 'scaler_fitted_on': 'training'}}


def load_model(path):
    model = strict_json(path)
    if (not isinstance(model, dict) or model.get('format') != 'return-model-v1'
            or model.get('project') != PROJECT or model.get('features') != [FEATURE]):
        raise ValueError('unsupported model or feature order')
    try:
        weights = model['estimator']['weights']
        means, stds = model['preprocessing']['mean'], model['preprocessing']['std']
        values = [*weights, *means, *stds, model['estimator']['bias']]
        valid = (len(weights) == len(means) == len(stds) == 1
                 and all(type(v) in (int, float) and math.isfinite(v) for v in values)
                 and stds[0] > 0)
    except (KeyError, TypeError):
        valid = False
    if not valid:
        raise ValueError('invalid model weights or preprocessing')
    return model


def predict(model, event_count):
    value = count(event_count)
    scaled = (value - model['preprocessing']['mean'][0]) / model['preprocessing']['std'][0]
    probability = baseline.sigmoid(model['estimator']['weights'][0] * scaled + model['estimator']['bias'])
    return {'event_count': value, 'return_probability': probability,
            'predicted_return': int(probability >= 0.5)}


def evaluate(cohort_path, model_path, split='validation'):
    if split not in ('validation', 'test'):
        raise ValueError('evaluate validation or final test data')
    data, model = cohort(cohort_path), load_model(model_path)
    if model['cohort_sha256'] != sha(cohort_path):
        raise ValueError('model and cohort identities differ')
    rows = [row for row in data['rows'] if row['split'] == split]
    if not rows:
        raise ValueError('evaluation split is empty')
    predictions = [predict(model, row['feature_count']) for row in rows]
    correct = sum(p['predicted_return'] == r['label'] for p, r in zip(predictions, rows))
    baseline_prediction = int(model['training_positive_rate'] >= 0.5)
    return {'split': split, 'rows': len(rows), 'correct': correct,
            'accuracy': correct / len(rows),
            'majority_correct': sum(r['label'] == baseline_prediction for r in rows),
            'model_sha256': sha(model_path), 'cohort_sha256': sha(cohort_path),
            'execution': 'fresh local CPU fit; authored synthetic labels'}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest='command', required=True)
    p = commands.add_parser('prepare');p.add_argument('--source', type=Path, default=HERE/'scenario.json');p.add_argument('--out', type=Path, required=True)
    p = commands.add_parser('train');p.add_argument('--cohort', type=Path, required=True);p.add_argument('--out', type=Path, required=True)
    p = commands.add_parser('evaluate');p.add_argument('--cohort', type=Path, required=True);p.add_argument('--model', type=Path, required=True);p.add_argument('--split', choices=['validation','test'], default='validation');p.add_argument('--out', type=Path, required=True)
    p = commands.add_parser('predict');p.add_argument('--model', type=Path, required=True);p.add_argument('--event-count', type=int, required=True)
    args = parser.parse_args()
    try:
        if args.command == 'prepare':
            value = prepare(args.source);save(args.out,value)
            value = {'written': str(args.out), 'rows': len(value['rows']),
                     'splits': {s:sum(r['split']==s for r in value['rows']) for s in ['training','validation','test']}}
        elif args.command == 'train':
            value = train(args.cohort);save(args.out,value)
            value = {'written': str(args.out), 'training_rows': value['training_rows'], 'features':value['features']}
        elif args.command == 'evaluate':
            value = evaluate(args.cohort,args.model,args.split);save(args.out,value)
        else:
            value = predict(load_model(args.model),args.event_count)
        print(json.dumps(value,indent=2,allow_nan=False))
    except (ValueError,KeyError,FileExistsError,FileNotFoundError) as error:
        parser.exit(2,str(error)+'\n')


if __name__ == '__main__':
    main()

Failure cases

Run the failure tests before extending the workflow. They exercise the actual assembler, trainer, saved model and fresh-process prediction command.

Run the offline checksTerminal · bash
python -m unittest -v test_workflow.py
  • Late events and unready labels cannot enter their historical examples.
  • Training and preprocessing receive training rows only.
  • Changed cohort identity, forged split assignments and duplicate observations are refused.
  • Invalid counts, malformed model parameters and zero scaling deviations are refused.
  • An existing output file is left unchanged instead of overwritten.

These tests check the workflow’s behavior. They do not measure service capacity or real-world prediction quality.

Running and extending the lab

The deployment unit here is a local directory and a Python environment. There is no HTTP server, registry or scheduler. The training loop holds the whole dataset in memory. For a larger dataset, measure memory use and run time before you choose a different implementation.

Stage 3 will connect this application to versioned inputs and experiment tracking. Stage 4 will automate these same steps. The later registry and serving stages must use the model and feature contract that this lesson creates.

Key takeaways

  • The prediction has a fixed input cutoff and a separate future outcome window.
  • Fitted preprocessing belongs with the saved model.
  • Evaluation reads separate rows without refitting the candidate.
  • A new process can reload the model and make the same prediction.

Best practices

Keep the test window separate while choosing a model. Retain the actual preprocessing and model parameters, not only rounded display values. Rerun the fresh-process prediction whenever you change what train saves; load_model refuses a file that lacks the scaler or weights. Add operational tools only when they solve a problem you have seen in this application.

What must a fresh process load to reproduce the trained model’s prediction?

Choose one answer, then check your reasoning.

Read the explanation

The predictor applies the training-fitted scaler, weight and bias stored in candidate.json. It does not fit again.

References

Written by Arjun Prabhulal.

Module 2

Run a manual workflow