-
Notifications
You must be signed in to change notification settings - Fork 2
/
example_01_twoSGDs.py
72 lines (53 loc) · 2.38 KB
/
example_01_twoSGDs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from src.model import FederatedSGDClassifier
from src.utils import get_logger
from sklearn.datasets import load_iris
LOGGER = get_logger('Example Two SGDs')
def step_example():
X, y = load_iris(return_X_y=True)
client = FederatedSGDClassifier(n_classes=3, n_features=4)
server = FederatedSGDClassifier(n_classes=3, n_features=4)
# Initialize SGDs
client.set_weights(client.generate_weights())
server.set_weights(server.generate_weights())
# TODO: one training epoch needs to be run to set "classes_" on SGD otherwise set_weights does not work
# TODO: this should be fixed
client.run_training_epoch(X, y)
server.run_training_epoch(X, y)
# Train client SGD
client.run_training_epoch(X, y)
# Set server SGD weights with client SGD wieghts
server.set_weights(client.get_weights())
# Evaluate server SGD
metrics = server.evaluate(X, y)
LOGGER.info(metrics)
# Metrics from server and client SGD should be the same
LOGGER.info("Sanity check : Server and Client SGDs evaluation should return the same metrics : {}".format(server.evaluate(X, y) == client.evaluate(X, y)))
def loop_example(loops=100):
X, y = load_iris(return_X_y=True)
client = FederatedSGDClassifier(n_classes=3, n_features=4)
server = FederatedSGDClassifier(n_classes=3, n_features=4)
# Initialize SGDs
client.set_weights(client.generate_weights())
server.set_weights(server.generate_weights())
# TODO: one training epoch needs to be run to set "classes_" on SGD otherwise set_weights does not work
# TODO: this should be fixed
client.run_training_epoch(X, y)
server.run_training_epoch(X, y)
for _ in range(loops):
# Train client SGD
client.run_training_epoch(X, y)
# Set server SGD weights with client SGD wieghts
server.set_weights(client.get_weights())
# Evaluate server SGD
metrics = server.evaluate(X, y)
LOGGER.info(metrics)
# Metrics from server and client SGD should be the same
LOGGER.info("Sanity check : Server and Client SGDs evaluation should return the same metrics : {}".format(server.evaluate(X, y) == client.evaluate(X, y)))
if __name__ =='__main__':
LOGGER.info('Running one step example')
step_example()
LOGGER.info('Running loop (100 steps) example')
loop_example()