-
Notifications
You must be signed in to change notification settings - Fork 3
/
Federated learning with XAI(Client).py
209 lines (172 loc) · 7.08 KB
/
Federated learning with XAI(Client).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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# -*- coding: utf-8 -*-
"""
Created on Mon May 17 10:42:22 2021
@author: ali.raza
"""
import socket
import pickle
import threading
import time
from mlsocket import MLSocket
import pygad
import pygad.nn
import pygad.gann
import numpy
import pygad
import pygad.nn
import pygad.gann
import numpy
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from sklearn.metrics import confusion_matrix
from keras.utils.np_utils import to_categorical
from sklearn.utils import class_weight
import warnings
from keras.callbacks import TensorBoard
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
from keras.models import Model
from keras.models import Sequential
from keras.layers import Convolution1D, ZeroPadding1D, MaxPooling1D, BatchNormalization, Activation, Dropout, Flatten, Dense
from keras.layers import Conv1D, Dense, MaxPool1D, Flatten, Input
import tensorflow as tf
from sklearn.utils import resample
from sklearn.model_selection import train_test_split
from tensorflow.keras import datasets, layers, models
from sklearn.metrics import precision_recall_curve, roc_curve
from sklearn.preprocessing import label_binarize
from tensorflow.keras.models import Sequential, load_model
import cv2
import h5py
from sklearn.model_selection import train_test_split
warnings.filterwarnings('ignore')
#-----------------------------------------Data Preparation--------------------------------------------------------------------------
train_df=pd.read_csv('mitbih_train.csv',header=None)
test_df=pd.read_csv('mitbih_test.csv',header=None)
df_1=train_df[train_df[188]==1]
df_2=train_df[train_df[188]==2]
df_3=train_df[train_df[188]==3]
df_4=train_df[train_df[188]==4]
df_0=(train_df[train_df[188]==0]).sample(n=20000,random_state=42)
df_1_upsample=resample(df_1,replace=True,n_samples=20000,random_state=123)
df_2_upsample=resample(df_2,replace=True,n_samples=20000,random_state=124)
df_3_upsample=resample(df_3,replace=True,n_samples=20000,random_state=125)
df_4_upsample=resample(df_4,replace=True,n_samples=20000,random_state=126)
df=pd.concat([df_0,df_1_upsample,df_2_upsample,df_3_upsample,df_4_upsample])
dft_1=test_df[test_df[188]==1]
dft_2=test_df[test_df[188]==2]
dft_3=test_df[test_df[188]==3]
dft_4=test_df[test_df[188]==4]
dft_0=(test_df[test_df[188]==0]).sample(n=10000,random_state=42)
dft_1_upsample=resample(dft_1,replace=True,n_samples=10000,random_state=123)
dft_2_upsample=resample(dft_2,replace=True,n_samples=10000,random_state=124)
dft_3_upsample=resample(dft_3,replace=True,n_samples=10000,random_state=125)
dft_4_upsample=resample(dft_4,replace=True,n_samples=10000,random_state=126)
dft=pd.concat([dft_0,dft_1_upsample,dft_2_upsample,dft_3_upsample,dft_4_upsample])
data=pd.concat([dft,df])
y=data.iloc[:,-1]
X=data.iloc[:,:-1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
def add_gaussian_noise(signal):
noise=np.random.normal(0,0.01,187)
out=signal+noise
return out
target_train=y_train
target_test=y_test
y_train=to_categorical(target_train)
y_test=to_categorical(target_test)
X_train=X_train
X_test=X_test
X_train_noise=np.array(X_train)
X_test_noise=np.array(X_test)
plt.plot(X_train[10])
plt.show()
for i in range(len(X_train_noise)):
X_train_noise[i,:187]= add_gaussian_noise(X_train_noise[i,:187])
for i in range(len(X_test_noise)):
X_test_noise[i,:187]= add_gaussian_noise(X_test_noise[i,:187])
X_train_noise= X_train_noise.reshape(len(X_train_noise), X_train_noise.shape[1],1)
X_train= X_train.reshape(len(X_train), X_train.shape[1],1)
X_test = X_test.reshape(len(X_test), X_test.shape[1],1)
X_test_noise= X_test_noise.reshape(len(X_test_noise), X_test_noise.shape[1],1)
X_train=np.float32(X_train)
X_train_noise=np.float32(X_train_noise)
X_test=np.float32(X_test)
X_test_noise=np.float32(X_test_noise)
plt.plot(X_train[10])
plt.plot(X_train_noise[10])
plt.show()
def featureNormalize(dataset):
mu = np.mean(dataset,axis=0)
sigma = np.std(dataset,axis=0)
return (dataset-mu)/sigma
#normalize mean
X_train_noise=(X_train_noise-X_train_noise.mean())/X_train_noise.std()
X_test_noise=(X_test_noise-X_test_noise.mean())/X_test_noise.std()
plt.show()
s= MLSocket()
HOST = 'xxx.xx.xx.xx' #write the IP of host (server)
PORT = xxxx #Port number of host opened for communication.
s.connect((HOST, PORT)) # Connect to the port and host
autoencoder = s.recv(1024) #receive the model for server
def scheduler(epoch, lr):
if epoch < 40:
return lr
else:
return lr * tf.math.exp(-0.1)
callback = tf.keras.callbacks.LearningRateScheduler(scheduler)
autoencoder.compile(optimizer='RMSprop', loss='mse')
autoencoder.summary()
#-----------------------------------------Model Fitting--------------------------------------------------------------------------
trained_autoencoder=autoencoder.fit(X_train_noise,X_train,epochs=50,
batch_size=100,
shuffle=True,
validation_data=(X_test_noise,X_test),
callbacks=[TensorBoard(log_dir='/tmp/autoencoder'),callback])
#-----------------------------------------Print autoencoder metrics------------------------------------
x_train_pred = autoencoder.predict(X_test_noise)
train_mae_loss = np.mean(np.abs(x_train_pred - X_test), axis=1)
#Print
plt.hist(train_mae_loss, bins=50)
plt.xlabel("Train MAE loss")
plt.ylabel("No of samples")
plt.show()
loss=trained_autoencoder.history['loss']
val_loss=trained_autoencoder.history['val_loss']
plt.plot( loss, label='loss')
plt.plot( val_loss, label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
plt.figure()
s.send(autoencoder)
#-----------------------------------------Model Fitting--------------------------------------------------------------------------
def scheduler2(epoch, lr):
if epoch < 90:
return lr
else:
return lr * tf.math.exp(-0.1)
callback = tf.keras.callbacks.LearningRateScheduler(scheduler2)
s= MLSocket()
s.connect((HOST, PORT)) # Connect to the port and host
model = s.recv(1024)
print("received classifier")
classifier=model
for l1,l2 in zip(classifier.layers[:5],autoencoder.layers[0:5]):
l1.set_weights(l2.get_weights())
for layer in classifier.layers[0:5]:
layer.trainable = False
opt = keras.optimizers.RMSprop(learning_rate=0.001)
classifier.compile(optimizer=opt,
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
classifier.summary()
input_data = keras.Input(shape=(X_train_noise.shape[1], 1))
classify_train = classifier.fit(X_train_noise,y_train,shuffle=True, batch_size=100,epochs=150,verbose=1,
validation_split=0.1,callbacks=[TensorBoard(log_dir='/tmp/autoencoder'),callback])
s.send(classifier)