Python Keras Lambda Layer和py_函数给出了一个错误,即不能在具有未知秩的形状上迭代

Python Keras Lambda Layer和py_函数给出了一个错误,即不能在具有未知秩的形状上迭代,python,tensorflow,keras,nlp,Python,Tensorflow,Keras,Nlp,我试图建立一个模型,在它的实现中,它需要两个文本输入,并根据输入的一个索引得到一个热向量 我创建了以下自定义函数: def get_index(text, word): # get index index = get_expression_indices(text, word) id_seq = [] for i in range(70): #length of the text if i == index : id_seq

我试图建立一个模型,在它的实现中,它需要两个文本输入,并根据输入的一个索引得到一个热向量

我创建了以下自定义函数:

def get_index(text, word):
    # get index
    index = get_expression_indices(text, word)
    id_seq = []
    for i in range(70): #length of the text
        if i == index :
            id_seq.insert(i, 1)
        else:
            id_seq.insert(i, 0)
    return np.array(id_seq)

def get_index_tensor(input):
    return tf.py_function(get_index, [input[0], input[1]], tf.string)
这是一个虚拟模型

# input layers
input_text_1 = Input(shape=(1,), dtype='string')
input_text_2 = Input(shape=(1,), dtype='string')
context = Lambda(emb_utils.get_index_tensor, output_shape=(None,))([input_text_1, input_text_2])
model = Model(inputs=[input_text_1, input_text_2], outputs=context)
我得到一个错误:
ValueError:无法迭代具有未知秩的形状。
输出形状应为(批次大小,70,1) 当我删除
output\u sape=(None,)
时,我得到
TypeError:类型为'NoneType'的对象没有len()

有没有关于问题可能是什么的想法?

您需要设置py_函数输出的形状:

def get_index_tensor(input):
    result = tf.py_function(get_index, [input[0], input[1]], tf.string)
    result.set_shape((None, 70, 1))
    return result