我想将使用 FedAvg 算法训练的 TensorFlow 联合模型保存为 Keras/.h5 模型。我找不到这方面的文件,想知道如何做。此外,如果可能的话,我想同时访问聚合服务器模型和客户端模型。
我用来训练联合模型的代码如下:
def model_fn():
model = tf.keras.models.Sequential([
tf.keras.layers.Input(shape=(segment_size,num_input_channels)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(units=400, activation='relu'),
tf.keras.layers.Dropout(dropout_rate),
tf.keras.layers.Dense(units=100, activation='relu'),
tf.keras.layers.Dropout(dropout_rate),
tf.keras.layers.Dense(activityCount, activation='softmax'),
])
return tff.learning.from_keras_model(
model,
dummy_batch=batch,
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
trainer = tff.learning.build_federated_averaging_process(
model_fn, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learningRate))
def evaluate(num_rounds=communicationRound):
state = trainer.initialize()
roundMetrics = []
evaluation = tff.learning.build_federated_evaluation(model_fn)
for round_num in range(num_rounds):
t1 = time.time()
state, metrics = trainer.next(state, train_data)
t2 = time.time()
test_metrics = evaluation(state.model, train_data)
roundMetrics.append('round {:2d}, metrics={}, loss={}'.format(round_num, metrics.sparse_categorical_accuracy , metrics.loss))
roundMetrics.append("The test accuracy is " + str(test_metrics.sparse_categorical_accuracy))
roundMetrics.append('round time={}'.format(t2 - t1))
print('round {:2d}, accuracy={}, loss={}'.format(round_num, metrics.sparse_categorical_accuracy , metrics.loss))
print("The test accuracy is " + str(test_metrics.sparse_categorical_accuracy))
print('round time={}'.format(t2 - t1))
outF = open(filepath+'stats'+architectureType+'.txt', "w")
for line in roundMetrics:
outF.write(line)
outF.write("\n")
outF.close()