- الرئيسية
- أساسيات التعلم الاتحادي
- المعمارية وسير العمل
- المحاكي التفاعلي
- الخوارزميات
- التجارب
- التطبيقات الطبية
- الخصوصية والأمان
- التعلم العميق الاتحادي
- التطبيقات
- المشاريع والأكواد
- مركز البحث
- الاختبارات
- تجاربي
- المراجع العلمية
- المصطلحات والأسئلة الشائعة
FedAvg بـ NumPy
المشاريع والأكواد · كود
الوصف
تنفيذ كامل صغير يقسّم بيانات اصطناعية IID وNon-IID ويشغّل FedAvg مع اختبار الوزن 0.6.
المتطلبات
- Python 3.9+
- numpy
الكود
"""FedAvg from scratch with NumPy: softmax regression on synthetic blobs, 5 clients, IID vs non-IID. Educational."""
import numpy as np
def make_blobs(n=900, k=3, d=2, noise=0.9, seed=0):
rng = np.random.default_rng(seed)
centers = rng.normal(0, 3, size=(k, d))
y = rng.integers(0, k, size=n)
X = centers[y] + rng.normal(0, noise, size=(n, d))
return X, y
def dirichlet_partition(y, n_clients, alpha, seed=0):
rng = np.random.default_rng(seed)
idx = [[] for _ in range(n_clients)]
for c in np.unique(y):
ids = rng.permutation(np.where(y == c)[0])
p = rng.dirichlet(alpha * np.ones(n_clients))
cuts = (np.cumsum(p) * len(ids)).astype(int)[:-1]
for i, part in enumerate(np.split(ids, cuts)):
idx[i] += part.tolist()
return [np.array(i) for i in idx]
def softmax(z):
z = z - z.max(axis=1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
def local_sgd(W, X, y, epochs, lr, k, batch=16, seed=0):
rng = np.random.default_rng(seed)
W = W.copy()
Xb = np.hstack([X, np.ones((len(X), 1))])
for _ in range(epochs):
order = rng.permutation(len(Xb))
for s in range(0, len(order), batch):
b = order[s:s + batch]
P = softmax(Xb[b] @ W)
P[np.arange(len(b)), y[b]] -= 1
W -= lr * Xb[b].T @ P / len(b)
return W
def accuracy(W, X, y):
Xb = np.hstack([X, np.ones((len(X), 1))])
return float((np.argmax(Xb @ W, axis=1) == y).mean())
def fedavg(parts, X, y, Xte, yte, rounds=20, epochs=3, lr=0.1, k=3):
W = np.zeros((X.shape[1] + 1, k))
n_k = np.array([len(p) for p in parts], dtype=float)
for t in range(rounds):
locals_ = [local_sgd(W, X[p], y[p], epochs, lr, k, seed=t * 100 + i) for i, p in enumerate(parts)]
W = sum((n_k[i] / n_k.sum()) * locals_[i] for i in range(len(parts))) # weighted mean
return W
if __name__ == "__main__":
Xall, yall = make_blobs(n=1500, seed=1) # one dataset, then split (same class centres)
X, y, Xte, yte = Xall[:900], yall[:900], Xall[900:], yall[900:]
iid = np.array_split(np.random.default_rng(0).permutation(len(y)), 5)
skew = dirichlet_partition(y, 5, alpha=0.1)
for name, parts in (("IID", iid), ("non-IID (alpha=0.1)", skew)):
W = fedavg(parts, X, y, Xte, yte)
print(f"{name:22s} test accuracy = {accuracy(W, Xte, yte):.3f}")
# sanity check from the lab's spec: weighted mean of 0.2/0.5/0.8 with 100/200/300 samples is 0.6
n = np.array([100, 200, 300.0]); w = np.array([0.2, 0.5, 0.8])
assert abs((n / n.sum() * w).sum() - 0.6) < 1e-12
print("weighted mean check OK: 0.6")دفتر Jupyter (نُفِّذ فعلياً، المخرجات محفوظة)
ملاحظات
للتعلم فقط؛ ليس بديلاً عن أطر الإنتاج.
نُفِّذ هذا الكود فعلياً أثناء بناء الإضافة وتحقّقنا من خرجه.
