> For the complete documentation index, see [llms.txt](https://baozoulin.gitbook.io/neural-networks-and-deep-learning/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://baozoulin.gitbook.io/neural-networks-and-deep-learning/di-wu-men-ke-xu-lie-mo-xing-sequence-models/di-wu-men-kexulie-mo-578b28-sequence-models/di-san-zhou-xu-lie-mo-xing-he-zhu-yi-li-ji-zhi-ff08-sequence-models-and-attention-mechanism/38zhu-yi-li-mo-xing-ff08-attention-model.md).

# 3.8注意力模型（Attention Model）

注意力模型让一个神经网络只注意到一部分的输入句子。当它在生成句子的时候，更像人类翻译

假定有一个输入句子，并使用双向的**RNN**，或者双向的**GRU**或者双向的**LSTM**，去计算每个词的特征：

[![](https://github.com/fengdu78/deeplearning_ai_books/raw/master/images/1e6b86a4e3690b4a0c6b8146ffa2f791.png)](https://github.com/fengdu78/deeplearning_ai_books/blob/master/images/1e6b86a4e3690b4a0c6b8146ffa2f791.png)

用$$a^{\<t{'}>}$$表示时间步$$t$$上的特征向量。用$$t{'}$$来索引法语句子里面的词，由于是双向RNN，每个$$a^{\<t{'}>}$$：

$$
a^{\<t{'}>}=(a^{\rightarrow \<t{'}>},a^{\leftarrow \<t{'}>})
$$

注意力权重用$$\alpha$$表示，C是各个RNN神经元经过注意力权重得到的参数值。例如$$\alpha^{<1,t{'}>}$$表示机器翻译的第一个单词“jane”对应的第$$t{'}$$个RNN神经元，$$C^{<1>}$$表示机器翻译第一个单词“jane”对应的解码网络输入参数。满足：

$$
\sum\_{t{'}}\alpha^{<1,t{'}>}=1
$$

$$
C^{<1>}=\sum\_{t{'}}\alpha^{<1,t{'}>}\cdot a^{\<t{'}>}
$$

用状态$$S$$表示生成翻译。$$\alpha^{\<t,t{'}>}$$是输出$$\hat y^{<t>}$$在$$t{'}$$时对RNN单元花在$$a^{\<t{'}>}$$上的注意力权重因子。即在$$t$$处生成输出词应该花多少注意力在第$$t{'}$$个输入词上面

[![](https://github.com/fengdu78/deeplearning_ai_books/raw/master/images/b22dff4a3b1a4ea8c1ab201446e98889.png)](https://github.com/fengdu78/deeplearning_ai_books/blob/master/images/b22dff4a3b1a4ea8c1ab201446e98889.png)

为了让$$\alpha^{\<t,t{'}>}$$之和为1，利用softamx思想，引入参数$$e^{\<t,t{'}>}$$，使得：

$$
a^{\<t,t'>} = \frac{\text{exp}(e^{\<t,t'>})}{\sum^{T\_x}\_{t'=1} \text{exp}(e^{\<t,t'>})}
$$

只要求出$$e^{\<t,t{'}>}$$，就能得到$$\alpha^{\<t,t{'}>}$$

如何求出$$e^{\<t,t{'}>}$$：

建立一个简单的神经网络

![](https://2314428465-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Le0cHhI0S0DK8pwlrmD%2F-Le0cKOp1vaxoORIi4ak%2F-Le0ccoXO7600E96ZmL3%2F504import.png?generation=1556953106917563\&alt=media)

输入$$s^{<t-1>}$$，即神经网络在上个时间步的状态和$$a^{\<t{'}>}$$，训练一个很小的神经网络，利用反向传播算法、梯度下降算法迭代优化，学到一个正确的函数$$e^{\<t,t{'}>}$$ 和$$\alpha^{\<t,t{'}>}$$

缺点：计算量较大，$$T\_x$$个输入单词和$$T\_y$$个输出单词的注意力参数的总数是$$T\_x\times T\_y$$，但是在机器翻译的应用上，输入和输出的句子一般不会太长，消耗还是可以接受

注意力模型在图像捕捉方面也有应用。比如图片加标题（**image captioning**），即看一张图，写下这张图的标题

Attention model还能处理日期标准化的问题（**the date normalization problem**）：

[\
![](https://github.com/fengdu78/deeplearning_ai_books/raw/master/images/fa6769127cd98ea0058f600449833a21.png)](https://legacy.gitbook.com/book/baozou/neural-networks-and-deep-learning/edit#)

训练一个神经网络，输入任何形式的日期，生成标准化的日期形式

还有可视化的注意力权重（**the visualizations of the attention weights**）。颜色越白表示注意力权重越大，颜色越深表示权重越小。输出语句单词与其输入语句单词对应位置的注意力权重较大，即对角线附近
