Python Keras使用Lambda层错误和K.ctc_解码

Python Keras使用Lambda层错误和K.ctc_解码,python,keras,Python,Keras,在CTC功能方面,Keras似乎为您做了很多繁重的工作。然而,我发现很难建立一个解码函数,我不想把它作为我的神经网络的一部分运行。我有一个自定义函数,在epoch end上执行,然后迭代所有测试数据并评估度量,我目前正在手动执行此操作,但希望使用k.ctc_解码函数(贪婪函数和beam函数),但是我发现很难访问该函数并将其合并到自定义函数中 我有一个模型: # Define CTC loss def ctc_lambda_func(args): y_pred, labe

在CTC功能方面,Keras似乎为您做了很多繁重的工作。然而,我发现很难建立一个解码函数,我不想把它作为我的神经网络的一部分运行。我有一个自定义函数,在epoch end上执行,然后迭代所有测试数据并评估度量,我目前正在手动执行此操作,但希望使用k.ctc_解码函数(贪婪函数和beam函数),但是我发现很难访问该函数并将其合并到自定义函数中

我有一个模型:

 # Define CTC loss
    def ctc_lambda_func(args):
        y_pred, labels, input_length, label_length = args
        return K.ctc_batch_cost(labels, y_pred, input_length, label_length)

def ctc_decode(args):
     y_pred, input_length =args
     seq_len = tf.squeeze(input_length,axis=1)

     return K.ctc_decode(y_pred=y_pred, input_length=seq_len, greedy=True, beam_width=100, top_paths=1)

input_data = Input(name='the_input', shape=(None,mfcc_features))  
x = TimeDistributed(Dense(fc_size, name='fc1', activation='relu'))(input_data) 
y_pred = TimeDistributed(Dense(num_classes, name="y_pred", activation="softmax"))(x)

labels = Input(name='the_labels', shape=[None,], dtype='int32')
input_length = Input(name='input_length', shape=[1], dtype='int32')
label_length = Input(name='label_length', shape=[1], dtype='int32')

loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred,labels,input_length,label_length])

dec = Lambda(ctc_decode, output_shape=[None,], name='decoder')([y_pred,input_length])

model = Model(inputs=[input_data, labels, input_length, label_length], outputs=[loss_out])



iterate = K.function([input_data, K.learning_phase()], [y_pred])
decode = K.function([y_pred, input_length], [dec])
当前错误为:

dec=Lambda(ctc_decode,name='decoder')([y_pred,input_length])文件 “/home/rob/py27/local/lib/python2.7/site packages/keras/engine/topology.py”, 第604行,在呼叫中 output_shape=self.compute_output_shape(input_shape)文件“/home/rob/py27/local/lib/python2.7/site packages/keras/layers/core.py”, 第631行,计算输出形状 返回K.int_shape(x)文件“/home/rob/py27/local/lib/python2.7/site packages/keras/backend/tensorflow_backend.py”, 第451行,内部形状 shape=x.get\u shape()AttributeError:“tuple”对象没有属性“get\u shape”


你知道我该怎么做吗?

一个棘手的部分是
K.ctc\u decode
返回一个张量列表的元组,而不是一个张量,所以你不能直接创建一个层。相反,尝试使用
K.function
创建解码器:

top_k_decoded, _ = K.ctc_decode(y_pred, input_lengths)
decoder = K.function([input_data, input_lengths], [top_k_decoded[0]])
稍后,您可以调用解码器:

decoded_sequences = decoder([test_input_data, test_input_lengths])

您可能需要一些重塑,因为
K.ctc\u解码器
要求长度具有形状(样本),而长度张量具有形状(样本,1)。

为什么要将其包装成
K.function
而不是将
top\u K\u解码[0]
放在Lambda层中?