首页 > 解决方案 > 如何在 Tensorflow 2.2 中训练具有多个输入的 Keras 模型?

问题描述

我想用两个输入(一个文本输入和一些数字特征)训练一个 Keras 模型,但我很难让它工作。我已经按照有关具有多个输入的模型的 Tensorflow 文档中的描述设置了一个模型:

import tensorflow as tf
from tensorflow.keras import Input, Model, models, layers


def build_model():
    input1 = Input(shape=(50,), dtype=tf.int32, name='x1')
    input2 = Input(shape=(1,), dtype=tf.float32, name='x2')
    y1 = layers.Embedding(1000, 10, input_length=50)(input1)
    y1 = layers.Flatten()(y1)
    y = layers.Concatenate(axis=1)([y1, input2])
    y = layers.Dense(1)(y)
    return Model(inputs=[input1, input2], outputs=y)

构建该模型也可以正常工作:

model = build_model()
model.compile(loss='mse')
model.summary()

summary()您可以在此 gist中找到 的输出。

然后需要一些(虚拟)数据来拟合模型:

def make_dummy_data():
    X1 = tf.data.Dataset.from_tensor_slices(tf.random.uniform([100, 50], maxval=1000, dtype=tf.int32))
    X2 = tf.data.Dataset.from_tensor_slices(tf.random.uniform([100, 1], dtype=tf.float32))
    X = tf.data.Dataset.zip((X1, X2)).map(lambda x1, x2: {'x1': x1, 'x2': x2})
    y_true = tf.data.Dataset.from_tensor_slices(tf.random.uniform([100, 1], dtype=tf.float32))
    return X, y_true


X, y_true = make_dummy_data()
Xy = tf.data.Dataset.zip((X, y_true))
model.fit(Xy, batch_size=32)

...但现在fit()失败并出现无法理解的错误消息(请参阅此处的完整消息),该消息以(可能相关的)警告开头:

WARNING:tensorflow:Model was constructed with shape (None, 50) for input Tensor("x1:0", shape=(None, 50), dtype=int32), but it was called on an input with incompatible shape (50, 1).

咦,那个1号的额外维度是从哪里来的?而且,我该如何摆脱它?

还有一件事:通过删除Embedding-layer 进一步简化这个虚拟模型确实会突然使模型运行。

如果你想玩弄上面的示例,我在 Google Colab 上为它准备了一个笔记本。任何帮助表示赞赏。

标签: pythontensorflow

解决方案


作为fit国家的文件:

batch_size
整数或None。每次梯度更新的样本数。如果未指定,batch_size将默认为 32。batch_size如果您的数据是数据集、生成器或keras.utils.Sequence实例的形式(因为它们生成批次),请不要指定。

也就是说,如果您使用数据集来训练您的模型,则预计它将提供批次,而不是单个示例。该形状(50, 1)可能来自 Keras,假设单个 50 元素示例实际上是一批 50 个 1 元素示例。

您可以像这样简单地修复它:

Xy = tf.data.Dataset.zip((X, y_true)).batch(32)
model.fit(Xy)

推荐阅读