Siamese网络损失函数异常:y_pred参数形状不符合预期
问题分析与解决方案
核心问题
你的代码存在两个关键问题:
- 多输出传递到Loss的错误:使用
tf.tuple()包装模型输出会干扰Keras的多输出处理逻辑,导致自定义Loss仅能接收到第一个输出张量。 - LSTM层的错误使用:LSTM默认
return_sequences=False,输出形状为(batch_size, d_model),后续的tf.reduce_mean(x, axis=1)会因axis=1维度不存在而报错。
修复步骤
1. 修正模型输出结构
去掉tf.tuple(),改用原生Python元组返回多输出,让Keras正确识别输出结构:
def create_model(vocab_size=512, d_model=128): def normalize(x): norm = tf.norm(x, axis=-1, keepdims=True) return tf.divide(x, norm) component = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, d_model), # 开启return_sequences=True,让LSTM返回完整序列输出,才能对序列维度做均值 tf.keras.layers.LSTM(d_model, return_sequences=True), tf.keras.layers.Lambda(lambda x: tf.reduce_mean(x, axis=1)), tf.keras.layers.Lambda(normalize), ]) inputs = [tf.keras.Input(shape=(None,)) for _ in range(2)] # 用原生元组返回两个输出 left_out = component(inputs[0]) right_out = component(inputs[1]) return tf.keras.Model(inputs=inputs, outputs=(left_out, right_out))
2. 正确传递多输出到自定义Loss
Keras默认会为每个输出分配单独的Loss,若要让单个Loss接收所有输出,最可靠的方式是在模型内部直接添加损失,绕过Keras的多输出Loss分配逻辑:
def create_model(vocab_size=512, d_model=128): def normalize(x): norm = tf.norm(x, axis=-1, keepdims=True) return tf.divide(x, norm) component = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, d_model), tf.keras.layers.LSTM(d_model, return_sequences=True), tf.keras.layers.Lambda(lambda x: tf.reduce_mean(x, axis=1)), tf.keras.layers.Lambda(normalize), ]) # 定义输入:两个文本输入 + 标签输入(用于计算损失) input_left = tf.keras.Input(shape=(None,)) input_right = tf.keras.Input(shape=(None,)) input_y_true = tf.keras.Input(shape=(1,)) left_out = component(input_left) right_out = component(input_right) # 定义你的损失计算逻辑(示例为对比损失,可替换为你的三元组损失) def compute_loss(y_true, left, right): margin = 1.0 cos_sim = tf.reduce_sum(tf.multiply(left, right), axis=1) loss = y_true * tf.square(tf.maximum(0.0, margin - cos_sim)) + (1 - y_true) * tf.square(cos_sim) return tf.reduce_mean(loss) # 将损失直接添加到模型 model_loss = compute_loss(input_y_true, left_out, right_out) model = tf.keras.Model(inputs=[input_left, input_right, input_y_true], outputs=[left_out, right_out]) model.add_loss(model_loss) return model
3. 训练时的调用方式
此时训练无需单独指定loss参数,因为损失已内置到模型中:
model = create_model() model.compile(optimizer='adam') # 输入数据格式:(left_texts, right_texts, labels) model.fit([left_data, right_data, y_true], epochs=10)
替代方案:合并输出后拆分
如果坚持使用自定义Loss类,可以将两个输出合并为单个张量,在Loss中拆分使用:
def create_model(vocab_size=512, d_model=128): def normalize(x): norm = tf.norm(x, axis=-1, keepdims=True) return tf.divide(x, norm) component = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, d_model), tf.keras.layers.LSTM(d_model, return_sequences=True), tf.keras.layers.Lambda(lambda x: tf.reduce_mean(x, axis=1)), tf.keras.layers.Lambda(normalize), ]) inputs = [tf.keras.Input(shape=(None,)) for _ in range(2)] left_out = component(inputs[0]) right_out = component(inputs[1]) # 合并两个输出为一个张量 merged_out = tf.keras.layers.Concatenate(axis=1)([left_out, right_out]) return tf.keras.Model(inputs=inputs, outputs=merged_out) class MyLoss(tf.keras.losses.Loss): def __init__(self): super().__init__(name='TripletLoss') def call(self, y_true, y_pred): # 拆分合并后的张量 d_model = tf.shape(y_pred)[1] // 2 l = y_pred[:, :d_model] r = y_pred[:, d_model:] # 这里替换为你的损失计算逻辑 margin = 1.0 cos_sim = tf.reduce_sum(tf.multiply(l, r), axis=1) loss = y_true * tf.square(tf.maximum(0.0, margin - cos_sim)) + (1 - y_true) * tf.square(cos_sim) return tf.reduce_mean(loss)
训练时正常指定Loss:
model = create_model() model.compile(optimizer='adam', loss=MyLoss()) model.fit([left_data, right_data], y_true, epochs=10)
内容的提问来源于stack exchange,提问作者Jakub
相关产品推荐
相关产品推荐

