在 Keras 中使用 Lambda 层时符号张量值错误

Symbolic tensor value error when using Lambda layer in Keras

ValueError: Layer lambda_47 was called with an input that isn't a symbolic tensor. Received type: <class 'tuple'>. Full input: [(<tf.Tensor 'lambda_45/Slice:0' shape=(110000, 1, 128) dtype=float32>, <tf.Tensor 'lambda_46/Slice:0' shape=(110000, 1, 128) dtype=float32>)]. All inputs to the layer should be tensors

我一直在尝试在模型定义中使用 keras 前端实现 tensorflow 操作。我在创建允许权重更新的 t运行sformation 层时遇到问题。我读过 Keras 的 Lambda 函数是执行此操作的关键,但我 运行 进入此错误。

这是我的代码:

### CONTROL VARIABLES (i.e. user input parameters)
dropout_rate = 0.5 
batch_size = 128
nb_epochs = 40
#with tf.device('/gpu:0'):


### MODEL CREATION
X_input = Input(shape=input_shape, name='input_1')
# Input
X_i = Lambda(lambda x: tf.slice(x, [0,0,0], [110000,1,128]))(X_input)                               # Slicing out inphase column
X_q = Lambda(lambda x: tf.slice(x, [0,1,0], [110000,1,128]))(X_input)                               # Slicing out quadrature column
X_mag = Lambda(lambda x_i, x_q: tf.math.sqrt(tf.math.add(tf.math.square(x_i), tf.math.square(x_q))))((X_i, X_q))     # Acquiring magnitude of IQ
## THE SOURCE OF THE ERROR IS THE LINE ABOVE ^
## ITS USING TENSORFLOW OPERATORS TO FIND ABSOLUTE VALUE
X_phase = Lambda(lambda x_i, x_q: tf.math.atan2(x_i, x_q))((X_i, X_q))                                               # Acquiring phase of IQ
X = Concatenate(axis=1)([X_mag, X_phase])                                                           # Combining into two column (magnitude,phase) tensor
X = Conv2D(128, kernel_size=(2,8), padding='same',data_format='channels_last')(X)
X = Activation('relu')(X)
X = Dropout(dropout_rate)(X)
X = Conv2D(64, kernel_size=(1,8), padding='same',data_format='channels_last')(X)
X = Activation('relu')(X)
X = Dropout(dropout_rate)(X)
X = Flatten()(X)
X = Dense(128, kernel_initializer='he_normal', activation='relu')(X)
X = Dropout(dropout_rate)(X)
X = Dense(len(classes), kernel_initializer='he_normal')(X)
X = Activation('softmax', name = 'labels')(X)

model = Model(inputs = X_input, outputs = X)
model.summary()
model.compile(optimizer=Adam(learning_rate), loss='categorical_crossentropy', metrics =['accuracy'])

完整堆栈跟踪错误:

The shape of x is  (220000, 2, 128)
(110000, 2, 128) [2, 128]

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py in assert_input_compatibility(self, inputs)
    278             try:
--> 279                 K.is_keras_tensor(x)
    280             except ValueError:

3 frames

/usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py in is_keras_tensor(x)
    473         raise ValueError('Unexpectedly found an instance of type `' +
--> 474                          str(type(x)) + '`. '
    475                          'Expected a symbolic tensor instance.')

ValueError: Unexpectedly found an instance of type `<class 'tuple'>`. Expected a symbolic tensor instance.


During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)

<ipython-input-22-dba00eef4193> in <module>()
    108 X_i = Lambda(lambda x: tf.slice(x, [0,0,0], [110000,1,128]))(X_input)                                # Slicing out inphase column
    109 X_q = Lambda(lambda x: tf.slice(x, [0,1,0], [110000,1,128]))(X_input)                                # Slicing out quadrature column
--> 110 X_mag = Lambda(lambda x_i, x_q: tf.math.sqrt(tf.math.add(tf.math.square(x_i), tf.math.square(x_q))))((X_i, X_q))     # Acquiring magnitude of IQ
    111 X_phase = Lambda(lambda x_i, x_q: tf.math.atan2(x_i, x_q))((X_i, X_q))                                               # Acquiring phase of IQ
    112 X = Concatenate(axis=1)([X_mag, X_phase])                                                           # Combining into two column (magnitude,phase) tensor

/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    412                 # Raise exceptions in case the input is not compatible
    413                 # with the input_spec specified in the layer constructor.
--> 414                 self.assert_input_compatibility(inputs)
    415 
    416                 # Collect input shapes to build layer.

/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py in assert_input_compatibility(self, inputs)
    283                                  'Received type: ' +
    284                                  str(type(x)) + '. Full input: ' +
--> 285                                  str(inputs) + '. All inputs to the layer '
    286                                  'should be tensors.')
    287 

ValueError: Layer lambda_47 was called with an input that isn't a symbolic tensor. Received type: <class 'tuple'>. Full input: [(<tf.Tensor 'lambda_45/Slice:0' shape=(110000, 1, 128) dtype=float32>, <tf.Tensor 'lambda_46/Slice:0' shape=(110000, 1, 128) dtype=float32>)]. All inputs to the layer should be tensors.

所以错误发生在 "X_mag = Lambda" 行。我搜索了所有相关的堆栈溢出帖子,none 似乎说明了此处嵌入的 tf 操作。请帮我解决这个问题!

这两天真是难倒我了。

您不能将 元组 传递给层作为它们的输入。相反,您应该使用 lists。此外,因此,Lambda 层中的 lambda 函数仅接受 一个 输入参数,即一个列表,您可以使用索引访问其元素:

X_mag = Lambda(lambda x: tf.math.sqrt(
             tf.math.add(tf.math.square(x[0]), tf.math.square(x[1]))))([X_i, X_q])     # Acquiring magnitude of IQ

X_phase = Lambda(lambda x: tf.math.atan2(x[0], x[1]))([X_i, X_q])   # Acquiring phase of IQ