如何从 CSV 文件创建联合数据集?

Mah*_*san 4 tensorflow tensorflow-federated federated-learning

我选择了这个数据集:https : //www.kaggle.com/karangadiya/fifa19

现在,我想将此 CSV 文件转换为联合数据集以适应模型。

Tensorflow 提供了有关联邦学习的教程,其中使用了预定义的数据集。但是,我的问题是如何将此特定数据集用于联合学习场景?

jpg*_*ard 6

我将使用不同的 CSV 数据集,但这仍应解决这个问题的核心,即如何从 CSV 创建联合数据集。我们还假设该数据集中有一列您希望表示client_id数据的s。

import pandas as pd
import tensorflow as tf
import tensorflow_federated as tff

csv_url = "https://docs.google.com/spreadsheets/d/1eJo2yOTVLPjcIbwe8qSQlFNpyMhYj-xVnNVUTAhwfNU/gviz/tq?tqx=out:csv"

df = pd.read_csv(csv_url, na_values=("?",))

client_id_colname = 'native.country' # the column that represents client ID
SHUFFLE_BUFFER = 1000
NUM_EPOCHS = 1

# split client id into train and test clients
client_ids = df[client_id_colname].unique()
train_client_ids = client_ids.sample(frac=0.5).tolist()
test_client_ids = [x for x in client_ids if x not in train_client_ids]
Run Code Online (Sandbox Code Playgroud)

有几种方法可以做到这一点,但我将在此处说明的方式使用tff.simulation.ClientData.from_clients_and_fn,这要求我们编写一个函数,该函数接受 aclient_id作为输入并返回 a tf.data.Dataset。我们可以很容易地从数据框中构建它。

def create_tf_dataset_for_client_fn(client_id):
  # a function which takes a client_id and returns a
  # tf.data.Dataset for that client
  client_data = df[df[client_id_colname] == client_id]
  dataset = tf.data.Dataset.from_tensor_slices(client_data.to_dict('list'))
  dataset = dataset.shuffle(SHUFFLE_BUFFER).batch(1).repeat(NUM_EPOCHS)
  return dataset
Run Code Online (Sandbox Code Playgroud)

现在,我们可以使用上面的函数ConcreteClientData为我们的训练和测试数据创建一个对象:

train_data = tff.simulation.ClientData.from_clients_and_fn(
        client_ids=train_client_ids,
        create_tf_dataset_for_client_fn=create_tf_dataset_for_client_fn
    )
test_data = tff.simulation.ClientData.from_clients_and_fn(
        client_ids=test_client_ids,
        create_tf_dataset_for_client_fn=create_tf_dataset_for_client_fn
    )
Run Code Online (Sandbox Code Playgroud)

要查看数据集的一个实例,请尝试:

example_dataset = train_data.create_tf_dataset_for_client(
        train_data.client_ids[0]
    )
print(type(example_dataset))
example_element = iter(example_dataset).next()
print(example_element)
# <class 'tensorflow.python.data.ops.dataset_ops.RepeatDataset'>
# {'age': <tf.Tensor: shape=(1,), dtype=int32, numpy=array([37], dtype=int32)>, 'workclass': <tf.Tensor: shape=(1,), dtype=string, numpy=array([b'Local-gov'], dtype=object)>, ...
Run Code Online (Sandbox Code Playgroud)

的每个元素example_dataset都是一个 Python 字典,其中键是表示特征名称的字符串,值是具有一批这些特征的张量。现在,您拥有一个可以进行预处理并用于建模的联合数据集。