Download scripts/client.py from init5iv3/Federated-OCPP1.6-Intrusion-Detection: direct link, hf CLI and curl.
- Browser
- Download file 4.27 kB
-
https://huggingface.co/datasets/init5iv3/Federated-OCPP1.6-Intrusion-Detection/resolve/main/scripts/client.py
- Command line
-
hf download hf://datasets/init5iv3/Federated-OCPP1.6-Intrusion-Detection/scripts/client.py
-
curl -L -o client.py https://huggingface.co/datasets/init5iv3/Federated-OCPP1.6-Intrusion-Detection/resolve/main/scripts/client.py
4.27 kB
| 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() |