Attention Mechanism Explained

Deep Learning with Keras and TensorFlow 10 min min read Updated: Nov 16, 2026 Advanced
Attention Mechanism Explained
Advanced Topic 7 of 9

The Idea of Attention

When you translate a long sentence, you do not look at all words equally. For each word you write, you look at the most relevant source words. Attention lets a neural network do the same: for each position it decides how much to focus on every other position.

Simple example: In the sentence 'The animal did not cross the street because it was too tired', what does 'it' mean? Your brain links 'it' to 'animal'. Attention allows the model to learn this link.

Query, Key and Value

PartRoleLibrary analogy
Query (Q)What am I looking for?Your search question
Key (K)What do I contain?The label on each book
Value (V)The actual informationThe content of the book

The model compares the query with all keys to get scores, turns the scores into weights with softmax, and then returns the weighted sum of the values.

text Attention(Q, K, V) = softmax( Q * K^T / sqrt(d) ) * V

Attention from Scratch

python import numpy as np def softmax(x): e = np.exp(x - x.max(axis=-1, keepdims=True)) return e / e.sum(axis=-1, keepdims=True) def attention(Q, K, V): d = Q.shape[-1] scores = Q @ K.T / np.sqrt(d) weights = softmax(scores) return weights @ V, weights x = np.random.rand(4, 8) # 4 words, each a vector with 8 numbers out, w = attention(x, x, x) # self-attention: Q, K, V all come from x print(w.round(2)) # each row sums to 1: how much each word looks at the others print(out.shape) # (4, 8)

When Q, K and V all come from the same sequence, we call it self-attention. Every word looks at every other word in the same sentence.

Multi-Head Attention in Keras

Multi-head attention runs several attention operations in parallel. Each head can focus on a different kind of relation, such as grammar or meaning.

python import keras from keras import layers mha = layers.MultiHeadAttention(num_heads=4, key_dim=16) x = np.random.rand(2, 10, 64).astype("float32") # (batch, words, features) out, scores = mha(x, x, return_attention_scores=True) print(out.shape) # (2, 10, 64) print(scores.shape) # (2, 4, 10, 10): batch, heads, from-word, to-word

Why Attention is Better than RNNs

  • Looks at all positions at once, so long-range links are easy
  • Can be computed in parallel, so it trains much faster on GPUs
  • Scales to very large datasets and models

Conclusion

Attention lets the model focus on what matters. It is the core building block of Transformers, which power modern language models.

Quick Summary: Attention compares queries with keys to weight the values. Self-attention relates the words of one sentence to each other.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators