我想用两个输入(一个文本输入和一些数字功能)训练Keras模型,但是我很难使它工作。我已经按照Tensorflow documentation about models with multiple inputs中的说明设置了模型:
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()
中找到this 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()
失败,并显示一条无法理解的错误消息(请参阅full message here),该消息以(可能相关的)警告开头:]]
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
层进一步简化此虚拟模型确实使模型运行。
如果您想使用上述示例,我准备了a notebook on Google Colab for it。任何帮助表示赞赏。
我想用两个输入(一个文本输入和一些数字功能)训练Keras模型,但是我很难使它工作。我已经按照Tensorflow文档中关于...
作为fit
的文档说明: