Keras:两个嵌入层的连接失败

2024-04-19 02:07:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个简单的模型,该模型采用两个一维输入样本,使用嵌入层对它们进行映射,并基于串联嵌入计算分数:

from tensorflow.keras.layers import Dense, Input, Concatenate, Embedding
from tensorflow.keras.models import Model 

input_1 = Input(shape=(1,)) # each input sample is an integer from 0 to 9
input_2 = Input(shape=(1,))

embedding_1 = Embedding(input_dim=10, output_dim=2) # map each input to 2d embedding vector 
embedding_2 = Embedding(input_dim=10, output_dim=2)

combined = Concatenate()([embedding_1, embedding_2])

score = Dense(1, activation='linear')(combined)

model = Model(inputs=[input_1, input_2], outputs=score)

上述操作失败,出现以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-146-f8b1f9bf33a7> in <module>
     12 embedding_2 = Embedding(input_dim=10, output_dim=2)
     13 
---> 14 combined = Concatenate(axis=1)([embedding_1, embedding_2])
     15 
     16 score = Dense(1, activation='linear')(combined)

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, *args, **kwargs)
    980       with ops.name_scope_v2(name_scope):
    981         if not self.built:
--> 982           self._maybe_build(inputs)
    983 
    984         with ops.enable_auto_cast_variables(self._compute_dtype_object):

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in _maybe_build(self, inputs)
   2641         # operations.
   2642         with tf_utils.maybe_init_scope(self):
-> 2643           self.build(input_shapes)  # pylint:disable=not-callable
   2644       # We must set also ensure that the layer is marked as built, and the build
   2645       # shape is stored since user defined build functions may not be calling

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/utils/tf_utils.py in wrapper(instance, input_shape)
    321     if input_shape is not None:
    322       input_shape = convert_shapes(input_shape, to_tuples=True)
--> 323     output_shape = fn(instance, input_shape)
    324     # Return shapes from `fn` as TensorShapes.
    325     if output_shape is not None:

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/layers/merge.py in build(self, input_shape)
    490   def build(self, input_shape):
    491     # Used purely for shape validation.
--> 492     if not isinstance(input_shape[0], tuple) or len(input_shape) < 2:
    493       raise ValueError('A `Concatenate` layer should be called '
    494                        'on a list of at least 2 inputs')

TypeError: 'NoneType' object is not subscriptable

Tags: infrombuildselfinputoutputistensorflow