Skip to content

Commit

Permalink
Move init seed from compute package to separate script
Browse files Browse the repository at this point in the history
  • Loading branch information
benjaminastrand committed Nov 25, 2024
1 parent dac41b9 commit e407967
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 2 deletions.
6 changes: 4 additions & 2 deletions examples/async-clients/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,17 @@ Standing in the folder fedn/examples/async-clients
pip install -r requirements.txt
Create the compute package and seed model:
Create the compute package:

.. code-block::
fedn package create --path client
Create the seed model:

.. code-block::
fedn run build --path client
python init_seed.py seed.npz
You will now have a file 'seed.npz' in the directory.
Expand Down
65 changes: 65 additions & 0 deletions examples/async-clients/init_seed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import sys

import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

from fedn.utils.helpers.helpers import get_helper

HELPER_MODULE = "numpyhelper"


def make_data(n_min=50, n_max=100):
"""Generate / simulate a random number n data points.
n will fall in the interval (n_min, n_max)
"""
n_samples = 100000
X, y = make_classification(n_samples=n_samples, n_features=4, n_informative=4, n_redundant=0, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

n = np.random.randint(n_min, n_max, 1)[0]
ind = np.random.choice(len(X_train), n)
X_train = X_train[ind, :]
y_train = y_train[ind]
return X_train, y_train, X_test, y_test


def compile_model(max_iter=1):
clf = MLPClassifier(max_iter=max_iter)
# This is needed to initialize some state variables needed to make predictions
# We will overwrite weights and biases during FL training
X_train, y_train, _, _ = make_data()
clf.fit(X_train, y_train)
return clf


def save_parameters(model, out_path):
"""Save model to disk.
:param model: The model to save.
:type model: torch.nn.Module
:param out_path: The path to save to.
:type out_path: str
"""
helper = get_helper(HELPER_MODULE)
parameters = model.coefs_ + model.intercepts_

helper.save(parameters, out_path)


def init_seed(out_path="seed.npz"):
"""Initialize seed model.
:param out_path: The path to save the seed model to.
:type out_path: str
"""
# Init and save
model = compile_model()
save_parameters(model, out_path)


if __name__ == "__main__":
init_seed(sys.argv[1])

0 comments on commit e407967

Please sign in to comment.