attention = Flatten()(attention)  

transform your tensor of attention weights in a vector (of size max_length if your sequence size is max_length).

attention = Activation('softmax')(attention)

allows having all the attention weights between 0 and 1, the sum of all the weights equal to one.

attention = RepeatVector(20)(attention)
attention = Permute([2, 1])(attention)


sent_representation = merge([activations, attention], mode='mul')

RepeatVector repeat the attention weights vector (which is of size max_len) with the size of the hidden state (20) in order to multiply the activations and the hidden states element-wise. The size of the tensor variable activations is max_len*20.

sent_representation = Lambda(lambda xin: K.sum(xin, axis=-2), output_shape=(units,))(sent_representation)

This Lambda layer sum the weighted hidden states vectors in order to obtain the vector that will be used at the end.

Hope this helped!

Answer from valbarriere on Stack Overflow
Top answer
1 of 2
43

This can be a possible custom solution with a custom layer that computes attention on the positional/temporal dimension

from tensorflow.keras.layers import Layer
from tensorflow.keras import backend as K

class Attention(Layer):
    
    def __init__(self, return_sequences=True):
        self.return_sequences = return_sequences
        super(Attention,self).__init__()
        
    def build(self, input_shape):
        
        self.W=self.add_weight(name="att_weight", shape=(input_shape[-1],1),
                               initializer="normal")
        self.b=self.add_weight(name="att_bias", shape=(input_shape[1],1),
                               initializer="zeros")
        
        super(Attention,self).build(input_shape)
        
    def call(self, x):
        
        e = K.tanh(K.dot(x,self.W)+self.b)
        a = K.softmax(e, axis=1)
        output = x*a
        
        if self.return_sequences:
            return output
        
        return K.sum(output, axis=1)

it's build to receive 3D tensors and output 3D tensors (return_sequences=True) or 2D tensors (return_sequences=False). below a dummy example

# dummy data creation

max_len = 100
max_words = 333
emb_dim = 126

n_sample = 5
X = np.random.randint(0,max_words, (n_sample,max_len))
Y = np.random.randint(0,2, n_sample)

with return_sequences=True

model = Sequential()
model.add(Embedding(max_words, emb_dim, input_length=max_len))
model.add(Bidirectional(LSTM(32, return_sequences=True)))
model.add(Attention(return_sequences=True)) # receive 3D and output 3D
model.add(LSTM(32))
model.add(Dense(1, activation='sigmoid'))
model.summary()

model.compile('adam', 'binary_crossentropy')
model.fit(X,Y, epochs=3)

with return_sequences=False

model = Sequential()
model.add(Embedding(max_words, emb_dim, input_length=max_len))
model.add(Bidirectional(LSTM(32, return_sequences=True)))
model.add(Attention(return_sequences=False)) # receive 3D and output 2D
model.add(Dense(1, activation='sigmoid'))
model.summary()

model.compile('adam', 'binary_crossentropy')
model.fit(X,Y, epochs=3)

You can integrate it into your networks easily

here the running notebook

2 of 2
4

In case, someone is using only Tensorflow and not keras externally, this is the way to do it.

import tensorflow as tf

class Attention(tf.keras.layers.Layer):

    def __init__(self, return_sequences=True, name=None, **kwargs):
        super(Attention, self).__init__(name=name)
        self.return_sequences = return_sequences
        super(Attention, self).__init__(**kwargs)

    def build(self, input_shape):
    
        self.W=self.add_weight(name="att_weight", shape=(input_shape[-1],1),
                           initializer="glorot_uniform", trainable=True)
        self.b=self.add_weight(name="att_bias", shape=(input_shape[1],1),
                           initializer="glorot_uniform", trainable=True)
    
        super(Attention, self).build(input_shape)

    def call(self, x):
    
        e = tf.keras.activations.tanh(tf.keras.backend.dot(x, self.W) + self.b)
        a = tf.keras.activations.softmax(e, axis=1)
        output = x * a
    
        if self.return_sequences:
            return a, output
    
        return a, tf.keras.backend.sum(output, axis=1)

    def get_config(self):
        config = super().get_config().copy()
        config.update({
            'return_sequences': self.return_sequences 
        })
        return config
Discussions

tensorflow - BI LSTM with attention layer in python for text classification - Stack Overflow
I want to apply this method to implement Bi-LSTM with attention. The method is discussed here: Bi-LSTM Attention model in Keras I get the following error: 'module' object is not callable It can not... More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 4, 2020
deep learning - Any good Implementations of Bi-LSTM bahdanau attention in Keras? - Data Science Stack Exchange
From past few weeks I'm trying to learn sequence to sequence machine translation modelling but I couldn't find any good examples/tutorials with bahdanau attention implemented. I did come across a t... More on datascience.stackexchange.com
๐ŸŒ datascience.stackexchange.com
python 3.x - How to add an attention layer (along with a Bi-LSTM layer) in keras sequential model? - Stack Overflow
I am trying to find an easy way to add an attention layer in Keras sequential model. However, I met a lot of problem in achieving that. I am a novice for deep leanring, so I choose Keras as my beginning. My task is build a Bi-LSTM with attention model. On IMDB dataset, I have built a Bi-LSTM model. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to apply Attention layer to LSTM model - Stack Overflow
I am doing a speech emotion recognition machine training. I wish to apply an attention layer to the model. The instruction page is hard to understand. def bi_duo_LSTM_model(X_train, y_train, X_test, More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ nlp โ€บ adding-attention-layer-to-a-bi-lstm
Adding Attention Layer to a Bi-LSTM - GeeksforGeeks
July 23, 2025 - Output Layer: Use a dense layer ... an attention layer to a Bi-LSTM (Bidirectional Long Short-Term Memory), we can use Keras' TensorFlow backend....
๐ŸŒ
Alvinntnu
alvinntnu.github.io โ€บ python-notes โ€บ nlp โ€บ seq-to-seq-m21-sentiment-attention.html
Sequence Model (many-to-one) with Attention โ€” Python Notes for Linguistics
lstm = Bidirectional(LSTM(RNN_CELL_SIZE, return_sequences = True), name="bi_lstm_0")(embedded_sequences) # Getting our LSTM outputs (lstm, forward_h, forward_c, backward_h, backward_c) = Bidirectional(LSTM(RNN_CELL_SIZE, return_sequences=True, return_state=True), name="bi_lstm_1")(lstm) state_h = Concatenate()([forward_h, backward_h]) state_c = Concatenate()([forward_c, backward_c]) context_vector, attention_weights = Attention(10)(lstm, state_h) # `lstm` the input features; `state_h` the hidden states from LSTM dense1 = Dense(20, activation="relu")(context_vector) dropout = Dropout(0.05)(dense1) output = Dense(1, activation="sigmoid")(dropout) model = keras.Model(inputs=sequence_input, outputs=output)
๐ŸŒ
Nature
nature.com โ€บ scientific reports โ€บ articles โ€บ article
A Novel CNN-based Bi-LSTM parallel model with attention mechanism for human activity recognition with noisy data | Scientific Reports
May 12, 2022 - The original features of sensors are segmented into sub-segments by well-designed equal time step sliding window, and fed into 1-D CNN-based bi-directional LSTM parallel layer to accelerate feature extraction with noisy and missed data. The weights of extracted features are redistributed by attention mechanism and integrated into complete features.
๐ŸŒ
GitHub
github.com โ€บ SNUDerek โ€บ multiLSTM
GitHub - SNUDerek/multiLSTM: keras attentional bi-LSTM-CRF for Joint NLU (slot-filling and intent detection) with ATIS ยท GitHub
the attention layer weights each input according to how well it thinks that input affects the task (in this case, intent detection). intuitively, this would mean 'stopwords' such as 'a', 'the', etc. would be considered less important, and context ...
Starred by 125 users
Forked by 40 users
Languages ย  Jupyter Notebook 87.3% | Python 12.7%
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 64676148 โ€บ bi-lstm-with-attention-layer-in-python-for-text-classification
tensorflow - BI LSTM with attention layer in python for text classification - Stack Overflow
November 4, 2020 - It can not apply multiply in this line: sent_representation = merge([lstm, attention], mode='mul') from keras.layers import merge import tensorflow as tf from tensorflow.keras.layers import Concatenate, Dense, Input, LSTM, Embedding, Dropout, Activation, Flatten, Permute, RepeatVector from tensorflow.keras.layers import Bidirectional inp =Input(shape=(maxlen,), dtype='float32') x = Embedding(max_features, embed_size, weights=[emb_matrix])(inp) lstm = Bidirectional(LSTM(50, return_sequences=True), name="bi_lstm_0")(x) attention = Dense(1, activation='tanh')(lstm) attention = Flatten()(attention
Find elsewhere
๐ŸŒ
Aionlinecourse
aionlinecourse.com โ€บ blog โ€บ how-to-add-attention-layer-to-a-bi-lstm
How to add attention layer to a Bi-LSTM | Ai Online Course
You can adjust the number of units according to your needs. 2. Next, incorporate the attention layer into the Bi-LSTM model. To do this, you will need to define the input and output of the attention layer.
๐ŸŒ
ScienceDirect
sciencedirect.com โ€บ science โ€บ article โ€บ pii โ€บ S2352152X24011095
A self-attention-based CNN-Bi-LSTM model for accurate state-of-charge estimation of lithium-ion batteries - ScienceDirect
April 5, 2024 - In this study, the self-attention ... network effectively captures the Bi-LSTM output sequence and trains a separate layer to pay more attention to some of the most important output elements through weight assignments...
๐ŸŒ
Medium
medium.com โ€บ @kharbanda.sumeet โ€บ language-translation-using-bilstm-attention-keras-e0ba1db4c72c
Language Translation using BiLSTM & Attention(Keras) | by Sumeet Kharbanda | Medium
January 26, 2020 - Bidirectional LSTMs are supported in Keras via the Bidirectional layer wrapper. Dataset is available at: https://www.statmt.org/europarl/ ... 3 Bidirectional LSTM were used in encoder part and single LSTM for decoder part.
๐ŸŒ
Kaggle
kaggle.com โ€บ code โ€บ arcisad โ€บ keras-bidirectional-lstm-self-attention
Keras Bidirectional LSTM + Self-Attention | Kaggle
May 19, 2019 - Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources
๐ŸŒ
Medium
medium.com โ€บ @shouke.wei โ€บ a-bidirectional-lstm-attention-model-for-time-series-forecasting-91b6305aba1d
A Bidirectional LSTM Attention Model for Time Series Forecasting | by Dr. Shouke Wei | Medium
July 6, 2023 - The model architecture consists of a bidirectional LSTM layer followed by an attention layer and a dense output layer. We have trained the model, evaluated its performance, and visualized the training and validation loss.
๐ŸŒ
arXiv
arxiv.org โ€บ pdf โ€บ 1907.10370 pdf
1 Self-attention based BiLSTM-CNN classifier for the prediction of
The model was implemented in KERAS 2.0.8 with Tensorflow 1.7 ... The self-attention mechanism is used to store relevant information by suppressing the noise. It ยท makes optimization much easier and also helps in classifying the represented features. This ยท technique is applied to train the ...
๐ŸŒ
Teemukanstren
teemukanstren.com โ€บ 2019 โ€บ 03 โ€บ 26 โ€บ attention-for-bug-predictions
Attention for Bug Predictions โ€“ Random experiments in software engineering
March 26, 2019 - A neural network architecture that has been gaining some "attention" recently in NLP is Attention. This is simply an approach to have the network pay some more "attention" to specific parts of the input.โ€ฆ
๐ŸŒ
Medium
medium.com โ€บ @jeewonkim1028 โ€บ sentiment-analysis-in-keras-using-attention-mechanism-on-yelp-reviews-dataset-322bd7333b8b
Sentiment Analysis in Keras using Attention Mechanism on Yelp Reviews Dataset | by Jeewon Kim | Medium
June 26, 2022 - For this, a unidirectional LSTM ... and bidirectional LSTM. The model layers the process of the sentence in both directions and persists the information of both types (start to end) and (end to start) so that whenever the words like love or fantastic come again in any sentence model can classify them as love class. ... The attention mechanism ...