Neural Mastery
← Practice
User Cohort Retention Matrix Enginemedium

User Cohort Retention Matrix Engine

medium NumPy & Data Wrangling 15-20 min

NumPy allowed · plain Python earns 10 bonus points

Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Track customer cohort lifecycles and retention decay over elapsed time periods.

Related Skills

Task

Implement build_cohort_retention_matrix(events): each event contains user_id, cohort_month, and activity_month. Calculate period = activity_month - cohort_month. The base size of a cohort is its total unique users. Compute retention percentage (active_users_in_period / cohort_base_size) * 100.0. Return nested dictionary {str(cohort): {'period_0': pct, ...}} with percentages rounded to 4 decimals.

Function Signature

build_cohort_retention_matrix(events: list[dict]) -> dict[str, dict[str, float]]

Examples

Example 1: 2 Cohorts Retention Tracking
Input: events = [{'user_id': 'u1', 'cohort_month': 1, 'activity_month': 1}, {'user_id': 'u1', 'cohort_month': 1, 'activity_month': 2}, {'user_id': 'u2', 'cohort_month': 1, 'activity_month': 1}, {'user_id': 'u3', 'cohort_month': 2, 'activity_month': 2}]
Output: {'1': {'period_0': 100, 'period_1': 50}, '2': {'period_0': 100}}
Explanation: Cohort 1 at period 0 is 100%, at period 1 is 50%.
Example 2: Single User Cohort
Input: events = [{'user_id': 'x', 'cohort_month': 5, 'activity_month': 5}]
Output: {'5': {'period_0': 100}}
Explanation: 100% retention on base period.

Constraints

  • cohort_month <= activity_month
  • 1 <= len(events) <= 50,000
Python3Saved ✓
def build_cohort_retention_matrix(events: list[dict]) -> dict[str, dict[str, float]]:
"""Build cohort retention percentage matrix {cohort: {'period_0': pct, 'period_1': pct, ...}}.
Round percentage values to 4 decimals."""
# Implement solution logic here
pass

Case 1: 2 Cohorts Retention Tracking
Input: events = [{'user_id': 'u1', 'cohort_month': 1, 'activity_month': 1}, {'user_id': 'u1', 'cohort_month': 1, 'activity_month': 2}, {'user_id': 'u2', 'cohort_month': 1, 'activity_month': 1}, {'user_id': 'u3', 'cohort_month': 2, 'activity_month': 2}]
Expected: {'1': {'period_0': 100, 'period_1': 50}, '2': {'period_0': 100}}
Case 2: Single User Cohort
Input: events = [{'user_id': 'x', 'cohort_month': 5, 'activity_month': 5}]
Expected: {'5': {'period_0': 100}}