我想训练一个具有两个输入(一个文本输入和一些数字特征)的 Keras 模型,但我很难让它工作。我已经按照中所述设置了一个模型有关具有多个输入的模型的 Tensorflow 文档 https://www.tensorflow.org/guide/keras/functional#models_with_multiple_inputs_and_outputs:
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()
in 这个要点 https://gist.github.com/hohl/8befac56b7137b1c54ca73735f1058f9.
然后需要一些(虚拟)数据来适应模型:
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()
失败并出现无法理解的错误消息(请参阅完整消息在这里 https://gist.github.com/hohl/93ad258d01229e3505fe857c73501102),以(可能相关的)警告开头:
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 上的笔记本 https://colab.research.google.com/drive/1PaCe0vdhfcbQgEWkfG_-Ys3ezccpIT1e?usp=sharing。任何帮助表示赞赏。