使用tensorflow进行联邦学习
【摘要】 下载tensorflow_federated模块,此处使用较稳定的0.13.1版本,可根据实际情况选择版本 pip3 install --upgrade tensorflow_federated==0.13.1 -i http://pypi.douban.com/simple --trusted-host pypi.douban.com引入所需模块import tensorflow as ...
下载tensorflow_federated模块,此处使用较稳定的0.13.1版本,可根据实际情况选择版本
pip3 install --upgrade tensorflow_federated==0.13.1 -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
引入所需模块
import tensorflow as tf
import tensorflow_federated as tff
下载手写体数字识别数据集
source, _ = tff.simulation.datasets.emnist.load_data()
def client_data(n):
return source.create_tf_dataset_for_client(source.client_ids[n]).map(
lambda e: (tf.reshape(e['pixels'], [-1]), e['label'])
).repeat(10).batch(20)
# Pick a subset of client devices to participate in training.
train_data = [client_data(n) for n in range(3)]
# Grab a single batch of data so that TFF knows what data looks like.
sample_batch = tf.nest.map_structure(
lambda x: x.numpy(), iter(train_data[0]).next())
定义模型
# Wrap a Keras model for use with TFF.
def model_fn():
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(10, tf.nn.softmax, input_shape=(784,),
kernel_initializer='zeros')
])
return tff.learning.from_keras_model(
model,
dummy_batch=sample_batch,
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
训练模型
# Simulate a few rounds of training with the selected client devices.
trainer = tff.learning.build_federated_averaging_process(
model_fn,
client_optimizer_fn=lambda: tf.keras.optimizers.SGD(0.1))
state = trainer.initialize()
for _ in range(20):
state, metrics = trainer.next(state, train_data)
print (metrics.loss)
训练结果
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
11.67063
11.65545
11.121943
10.477433
8.830841
7.7931805
7.192688
5.1021852
5.1880836
3.3151658
3.3807354
3.3242536
2.30087
1.7061236
1.5317304
1.1874161
0.7962298
0.94748044
0.7774023
0.6510306
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)