federated-learning/data.py
2026-11-08 16:50:59 -07:00

86 lines
3.1 KiB
Python

"""The data: a wellness app on ten phones. Given; you do not change this file.
Every record is one person-day from a (synthetic) wellness app:
sleep hours slept
steps thousands of steps walked
resting_hr resting heart rate, beats per minute
screen hours of screen time
and a label: 1 if the app flagged that day as a burnout risk, 0 if not.
Nothing here is real, but it is the kind of record people would not want a
server to see, which is the point of the project: federated learning promises
that it never leaves the phone.
The model works on scaled features (roughly 0 to 1), so every record is stored
scaled; describe() turns one back into units a person would recognize.
"""
import random
FEATURES = ("sleep", "steps", "resting_hr", "screen")
# how each feature is scaled: value = (raw - low) / (high - low)
RANGES = {
"sleep": (3.0, 10.0),
"steps": (0.0, 16.0),
"resting_hr": (45.0, 100.0),
"screen": (0.0, 12.0),
}
def _scale(name, raw):
low, high = RANGES[name]
return (raw - low) / (high - low)
def describe(x):
"""A scaled record as a person would read it."""
raw = [RANGES[n][0] + v * (RANGES[n][1] - RANGES[n][0]) for n, v in zip(FEATURES, x)]
return (f"slept {raw[0]:.1f} h, walked {raw[1]:.1f}k steps, "
f"resting heart rate {raw[2]:.0f}, {raw[3]:.1f} h of screen time")
def _person_day(rng, habits):
sleep = min(10.0, max(3.0, rng.gauss(habits["sleep"], 1.0)))
steps = min(16.0, max(0.0, rng.gauss(habits["steps"], 2.0)))
hr = min(100.0, max(45.0, rng.gauss(habits["hr"], 6.0)))
screen = min(12.0, max(0.0, rng.gauss(habits["screen"], 1.5)))
# the hidden rule the app uses, with some noise: little sleep, few steps,
# a high resting heart rate and a lot of screen time mean risk
score = -0.9 * (sleep - 7) - 0.25 * (steps - 7) + 0.08 * (hr - 68) + 0.35 * (screen - 5)
label = 1 if score + rng.gauss(0, 0.8) > 0 else 0
x = [
_scale("sleep", sleep),
_scale("steps", steps),
_scale("resting_hr", hr),
_scale("screen", screen),
]
return x, label
def make_clients(n_clients=10, per_client=40, seed=4930):
"""One list of (features, label) records per phone.
Each phone belongs to one person, so its records share habits: one sleeps
less, another walks more. That is what makes federated data "non-IID":
no single phone looks like the whole population.
"""
rng = random.Random(seed)
clients = []
for _ in range(n_clients):
habits = {"sleep": rng.uniform(5.0, 8.5), "steps": rng.uniform(3.0, 12.0),
"hr": rng.uniform(55.0, 80.0), "screen": rng.uniform(2.0, 8.0)}
clients.append([_person_day(rng, habits) for _ in range(per_client)])
return clients
def make_test_set(n=400, seed=2026):
"""Held-out person-days from people who are not on any phone above."""
rng = random.Random(seed)
out = []
for _ in range(n):
habits = {"sleep": rng.uniform(5.0, 8.5), "steps": rng.uniform(3.0, 12.0),
"hr": rng.uniform(55.0, 80.0), "screen": rng.uniform(2.0, 8.0)}
out.append(_person_day(rng, habits))
return out