File size: 4,271 Bytes
75a56a3 | 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | import pandas as pd
import numpy as np
import flwr as fl
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
from utils import evaluation_metrics, load_config
from dnn_model import create_model
import argparse
import os
class Client(fl.client.NumPyClient):
'''Flower client class
'''
def __init__(self, path_to_config):
self.conf = load_config(path_to_config)
self.load_dataset()
self.X_train, self.Y_train = preprocess(self.data_train, self.conf['features_to_drop'])
self.X_test, self.Y_test = preprocess(self.data_test, self.conf['features_to_drop'])
self.eval_metrics_lst = []
self.model = create_model(self.X_train.shape[1], len(self.Y_train.value_counts()))
opt = tf.keras.optimizers.Adam(learning_rate=self.conf['learning_rate'], beta_1=0.99, beta_2=0.999, epsilon=1e-08)
self.model.compile(loss='sparse_categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
def load_dataset(self):
''' Loads the dataset'''
self.data_train = pd.read_csv(self.conf['dataset_path'] + '/Train.csv')
self.data_test = pd.read_csv(self.conf['dataset_path'] + '/Test.csv')
def normalize_data(self):
'''Normalize data with standard scaling'''
scaler = StandardScaler()
self.X_train = scaler.fit_transform(self.X_train)
self.X_test = scaler.transform(self.X_test)
def encode_labels(self, label_enc_path=None):
'''Encode the labels'''
enc_Y = LabelEncoder()
self.Y_train = enc_Y.fit_transform(self.Y_train.to_numpy().reshape(-1))
self.Y_test = enc_Y.transform(self.Y_test.to_numpy().reshape(-1))
def get_parameters(self, config):
return self.model.get_weights()
def fit(self, parameters, config):
'''Perform local training.'''
self.model.set_weights(parameters)
self.epochs = config['local_epochs']
self.model.fit(self.X_train, self.Y_train, epochs=self.epochs, batch_size=config['batch_size'])
return self.model.get_weights(), len(self.X_train), {}
def evaluate(self, parameters, config):
''' Evaluate model'''
self.model.set_weights(parameters)
print("\n")
print("Evaluation:")
loss, accuracy = self.model.evaluate(self.X_test, self.Y_test)
predicted_test = self.model.predict(self.X_test)
predicted_classes = np.argmax(predicted_test,axis=1)
eval_metrics = evaluation_metrics(self.Y_test, predicted_classes, predicted_test)
# a list of tuples: (accuracy, TPR, FPR f1)
self.eval_metrics_lst.append(eval_metrics)
return loss, len(self.X_test), {"accuracy": accuracy}
def gen_client(args):
''' Generate and return client instance, with data normalization,
and encoding
'''
# create client instance
client = Client(args.config_path)
client.encode_labels()
client.normalize_data()
return client
def preprocess(data, feats_to_drop):
'''Clean the data and remove certain features
'''
data = data.dropna(axis=0, how='any')
if 'Label' in data.columns:
label_name = 'Label'
elif 'label' in data.columns:
label_name = 'label'
Y = data[[label_name]]
data = data.drop(feats_to_drop, axis=1)
X = data.to_numpy()
return X, Y
def main():
# parser: takes only config file path
parser = argparse.ArgumentParser(description='Federated learning client')
parser.add_argument('config_path', type=str, help='Path to the configuration file of the client')
args = parser.parse_args()
# (optional): force TensorFlow to use the CPU only
tf.config.set_visible_devices([], 'GPU')
# generate client
client = gen_client(args)
# start client
fl.client.start_numpy_client(
server_address=client.conf['server_address'],
client=client,
)
# save the final model
path = client.conf['saved_model_path']
if not os.path.exists(path):
os.makedirs(path)
full_path = os.path.join(path, 'model.h5')
client.model.save(full_path)
if __name__ == "__main__":
main() |