python - 如何使用 Tensorflow Federated 中的多个功能构建模型?

标签 python tensorflow tensorflow-federated

在尝试为多个特征输入(即特征 a-g)和一个标签 h 创建 OrderedDict 时,我遇到了以下代码和问题。


def preprocess(dataset):

  def batch_format_fn(element):

    return collections.OrderedDict(
        x=collections.OrderedDict(
            a=tf.TensorSpec(shape=[None,], dtype=tf.int32),
            b=tf.TensorSpec(shape=[None,], dtype=tf.int32),
            c=tf.TensorSpec(shape=[None,], dtype=tf.int32),
            d=tf.TensorSpec(shape=[None,], dtype=tf.int32),
            e=tf.TensorSpec(shape=[None,], dtype=tf.int32),
            f=tf.TensorSpec(shape=[None,], dtype=tf.int32),
            g=tf.TensorSpec(shape=[None,], dtype=tf.int32)),
        y=tf.TensorSpec(shape=[None,], dtype=tf.int32))
  return dataset.map(batch_format_fn).prefetch(PREFETCH_BUFFER)

preprocessed_sample_dataset = preprocess(example_dataset)

def create_keras_model():
    model = Sequential([
    feature_layer,
    Dense(64, activation='relu'),
    Dense(64, activation='relu'),
    Dense(3, activation='softmax') #classification 3 outputs
    ])
    return model

def model_fn():

  keras_model = create_keras_model()
  return tff.learning.from_keras_model(
      keras_model,
      input_spec=preprocessed_sample_dataset.element_spec,
      loss=losses.SparseCategoricalCrossentropy(),
      metrics=[metrics.SparseCategoricalAccuracy()])

在执行input_spec=preprocessed_sample_dataset.element_spec时显示如下错误:

TypeError: Unsupported return value from function passed to Dataset.map(): OrderedDict([('x', OrderedDict([('a', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), ('b', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), ('c', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), ('d', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), ('e', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), ('f', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), ('g', TensorSpec(shape=(None,), dtype=tf.int32, name=None))])), ('y', TensorSpec(shape=(None,), dtype=tf.int32, name=None))]).

我已阅读此备选方案 solution ,但是目前尚不清楚如何在我的案例中实现它。因此,如何为 TFF 中的多个特征正确分配有序字典?

当前example_dataset.element_spec如下:

OrderedDict([
('a', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('b', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('c', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('d', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('e', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('f', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('g', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('y', TensorSpec(shape=(None,), dtype=tf.int32, name=None))])

我希望 element_spec 变成这样:

OrderedDict([('x', OrderedDict([
('a', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('b', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('c', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('d', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('e', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('f', TensorSpec(shape=(None,), dtype=tf.int32, name=None)), 
('g', TensorSpec(shape=(None,), dtype=tf.int32, name=None))])), 
('y', TensorSpec(shape=(None,), dtype=tf.int32, name=None))])

如何使用batch_format_fn使element_spec成为后者?

最佳答案

batch_format_fn 目前返回张量类型的结构; tf.data.Dataset.map 期望接收一个 tensors 结构作为函数的返回值。

我们应该更新 batch_format_fn 以重新格式化其 element 参数并返回它。让我们尝试类似的事情:

def batch_format_fn(element):
  feature_dict = collections.OrderedDict(
      a=element['a'],
      b=element['b'],
      c=element['c'],
      d=element['d'],
      e=element['e'],
      f=element['f'],
      g=element['g'],
  )
  return collections.OrderedDict(x=feature_dict, y=element['y'])

并保持其他一切不变。

关于python - 如何使用 Tensorflow Federated 中的多个功能构建模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62893523/

相关文章:

python - 仅从数据框中选择每个月的最后一周 - Python/Pandas

python - psycopg2 "TypeError: not all arguments converted during string formatting"

python - 使用 PIP 安装程序在 MAC OS X LION 10.7.2 上安装 PIL

python - Python 2.7 中的奇怪异常.SystemExit

python - "tensorflow.math.multiply"和 "tensorflow.keras.layers.multiply"和有什么区别?

python - 每次将文件下载到特定文件夹时都会触发 python 脚本

python - Keras 中的 "Could not interpret optimizer identifier"错误

tensorflow-federated - TFF 是否序列化另一个库的函数?

tensorflow-federated - 在 tf federated 中运行事件循环

tensorflow-federated - 联邦学习中的 state = iterative_process.initialize() 是什么意思