You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Keras中为多模态情感识别LSTM模型添加Attention层遇错求助

问题分析与解决方案

错误根源

你的自定义Attention类与TensorFlow内置的tf.keras.layers.Attention重名,导致实例化时实际调用了内置的Attention层。而内置Attention层要求输入必须是[query, value]或[query, value, key]的列表形式,不是单个张量,因此触发报错。

修复步骤

1. 重命名自定义Attention类

将自定义类改为独特名称,避免与内置层冲突,同时优化偏置参数的shape以适配可变序列长度:

class CustomSelfAttention(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super(CustomSelfAttention, self).__init__(**kwargs)

    def build(self, input_shape):
        # 权重矩阵:(隐藏维度, 1)
        self.We = self.add_weight(
            shape=(input_shape[-1], 1),
            initializer='random_normal',
            trainable=True
        )
        # 偏置改为(1,),利用广播适配任意序列长度
        self.b = self.add_weight(
            shape=(1,),
            initializer='zeros',
            trainable=True
        )
        super(CustomSelfAttention, self).build(input_shape)

    def call(self, x):
        # 计算注意力得分
        q = tf.nn.tanh(tf.linalg.matmul(x, self.We) + self.b)
        # 归一化注意力权重
        a = tf.nn.softmax(q, axis=1)
        # 加权求和得到注意力输出
        return tf.reduce_sum(a * x, axis=1)

2. 更新模型调用代码

使用重命名后的自定义层:

self.features_audio_dim = self.train_x_audio.shape[2] #1611 
audio_input  = Input(shape=(self.sequence_length, self.features_audio_dim), dtype='float32')
lstm_audio = LSTM(128, return_sequences=True, dropout=0.3, recurrent_dropout=0.2)(audio_input)
# 调用自定义的自注意力层
attention_audio = CustomSelfAttention()(lstm_audio)

额外说明

原代码中self.b的shape设置为(input_shape[1],1)会固定序列长度,若后续输入的序列长度与训练时不一致(比如测试数据),会引发维度不匹配错误。改为(1,)后,借助TensorFlow的广播机制,可自动适配任意序列长度,提升模型的灵活性。

内容的提问来源于stack exchange,提问作者Mohamed Belhireche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:52:44