【问题标题】:Symbolic tensor value error when using Lambda layer in Keras在 Keras 中使用 Lambda 层时出现符号张量值错误
【发布时间】:2019-11-22 12:24:45
【问题描述】:
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 操作。我在创建允许权重更新的转换层时遇到问题。我读过 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”行。我已经搜索了所有相关的堆栈溢出帖子,但似乎没有一个说明这里嵌入了 tf 操作。请帮我解决这个问题!

这两天真的把我难住了。

【问题讨论】:

    标签: python tensorflow keras deep-learning keras-layer


    【解决方案1】:

    您不能将 元组 作为图层的输入传递给图层。相反,您应该使用列表。此外,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
    

    【讨论】:

    • 谢谢!我可以使用上面的代码训练我的模型,但由于某种原因,在完成训练后立即出现错误“NameError:name 'tf' is not defined”。在 google colab 中使用数据集 DeepSig Dataset: RadioML 2016.10A 训练,来自deepsig.io/datasets
    • 如果不能重现,请告诉我!不管怎样,谢谢!
    • @Mr.T 训练完成后你是否保存并重新加载你的模型?
    • 是的,'tf is not defined 错误'与我忘记为张量流图混淆的代码有关。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2017-07-26
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    相关资源
    最近更新 更多