在 TensorFlow Federated 中创建自定义联合数据集

Create a custom federated data set in TensorFlow Federated

我想从这个 blog post 中调整循环自动编码器以在联合环境中工作。

我稍微修改了模型以符合 TFF image classification tutorial.

中显示的示例
def create_compiled_keras_model():
  model = tf.keras.models.Sequential([
      tf.keras.layers.LSTM(2, input_shape=(10, 2), name='Encoder'),
      tf.keras.layers.RepeatVector(10, name='Latent'),
      tf.keras.layers.LSTM(2, return_sequences=True, name='Decoder')]
  )

  model.compile(loss='mse', optimizer='adam')
  return model

model = create_compiled_keras_model()

sample_batch = gen(1)
timesteps, input_dim = 10, 2

def model_fn():
  keras_model = create_compiled_keras_model()
  return tff.learning.from_compiled_keras_model(keras_model, sample_batch)

gen函数定义如下:

import random

def gen(batch_size):
    seq_length = 10

    batch_x = []
    batch_y = []

    for _ in range(batch_size):
        rand = random.random() * 2 * np.pi

        sig1 = np.sin(np.linspace(0.0 * np.pi + rand, 3.0 * np.pi + rand, seq_length * 2))
        sig2 = np.cos(np.linspace(0.0 * np.pi + rand, 3.0 * np.pi + rand, seq_length * 2))

        x1 = sig1[:seq_length]
        y1 = sig1[seq_length:]
        x2 = sig2[:seq_length]
        y2 = sig2[seq_length:]

        x_ = np.array([x1, x2])
        y_ = np.array([y1, y2])
        x_, y_ = x_.T, y_.T

        batch_x.append(x_)
        batch_y.append(y_)

    batch_x = np.array(batch_x)
    batch_y = np.array(batch_y)

    return batch_x, batch_x #batch_y

到目前为止,我一直无法找到任何不使用 TFF 存储库中示例数据的文档。

如何修改它以创建联合数据集并开始训练?

在非常高的层次上,要使用带有 TFF 的任意数据集,需要以下步骤:

  1. 将数据集划分为每个客户 个子集(如何做是一个更大的问题)
  2. 为每个客户子集创建一个 tf.data.Dataset
  3. 将所有(或子集)数据集对象的列表传递给联合优化。

教程中发生了什么

Federated Learning for Image Classification tutorial uses tff.learning.build_federated_averaging_process 使用 FedAvg 算法建立联合优化。

在该笔记本中,以下代码正在执行一轮联合优化,其中将客户端数据集传递给进程的 .next 方法:

   state, metrics = iterative_process.next(state, federated_train_data)

这里 federated_train_data 是 Python listtf.data.Dataset,每个参与该回合的客户一个。

ClientData 对象

TFF 提供的固定数据集(在 tff.simulation.datasets) are implemented using the tff.simulation.ClientData 接口下,管理客户端 → 数据集映射和 tff.data.Dataset 创建。

如果您打算重新使用数据集,将其实现为 tff.simulation.ClientData 可能会使将来的使用更容易。

接受的答案解释得很好。如果你们需要将张量转换为 clientdata 对象的代码实现,可以在这个 github repository.

中找到

其中我使用 tff.simulation.FromTensorSlicesClientData 将 mnist 数据集转换为多个 tff 客户端数据。