首页 > 解决方案 > 如何从 CSV 文件创建联合数据集?

问题描述

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

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

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

标签: tensorflowtensorflow-federatedfederated-learning

解决方案


我将使用不同的 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]

有几种方法可以做到这一点,但我将在这里说明的方式使用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

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
    )

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

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)>, ...

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


推荐阅读