"""The model: logistic regression, written out in full. Given; read it, do not change it. README.md's primer explains every function here in plain terms. You do not need any machine-learning background to use it, and you do not need to change it: every part of the project calls these functions. A model is a list of weights `w` (one per feature) and a bias `b`. Training nudges them, a little at a time, so the model's predictions match the labels. Python reference: https://docs.python.org/3/library/math.html """ import math def zeros(d): """A fresh, untrained model with d features.""" return [0.0] * d, 0.0 def sigmoid(z): """Squash any number into a probability between 0 and 1.""" if z >= 0: return 1.0 / (1.0 + math.exp(-z)) e = math.exp(z) return e / (1.0 + e) def predict(w, b, x): """The model's probability that record x has label 1.""" return sigmoid(sum(wi * xi for wi, xi in zip(w, x)) + b) def gradient(w, b, batch): """Which way to nudge the weights to fit `batch` better, averaged over it. For ONE record (x, y) the gradient is: dw[j] = (predict(w, b, x) - y) * x[j] for each feature j db = (predict(w, b, x) - y) For a batch, it is the average of that over the records in the batch. This is what a phone sends to the server in federated learning. """ d = len(w) dw, db = [0.0] * d, 0.0 for x, y in batch: err = predict(w, b, x) - y for j in range(d): dw[j] += err * x[j] db += err n = len(batch) return [g / n for g in dw], db / n def step(w, b, dw, db, lr): """Move the model a small distance (lr) against the gradient.""" return [wi - lr * gi for wi, gi in zip(w, dw)], b - lr * db def local_train(w, b, records, lr=0.5, epochs=5, batch_size=8, rng=None): """Train a copy of the model on one phone's records and return it. `rng` (a random.Random) shuffles the records each pass so training does not see them in the same order every time. """ records = list(records) for _ in range(epochs): if rng is not None: rng.shuffle(records) for i in range(0, len(records), batch_size): dw, db = gradient(w, b, records[i:i + batch_size]) w, b = step(w, b, dw, db, lr) return w, b def accuracy(w, b, records): """Share of records the model labels correctly (predicting 1 when p >= 0.5).""" right = sum(1 for x, y in records if (predict(w, b, x) >= 0.5) == (y == 1)) return right / len(records)