Attention in Neural Networks and How to Use It

this blog comes from: http://akosiorek.github.io/ml/2017/10/14/visual-attention.html 

Oct 14, 2017

Attention mechanisms in neural networks, otherwise known as neural attention or just attention, have recently attracted a lot of attention (pun intended). In this post, I will try to find a common denominator for different mechanisms and use-cases and I will describe (and implement!) two mechanisms of soft visual attention.

What is Attention?

Informally, a neural attention mechanism equips a neural network with the ability to focus on a subset of its inputs (or features): it selects specific inputs. Let x∈Rdx∈Rd an input, z∈Rkz∈Rk a feature vector, a∈[0,1]ka∈[0,1]k an attention vector and fϕ(x)fϕ(x) an attention network. Typically, attention is implemented as

aza=fϕ(x),=a⊙z,(1)(1)a=fϕ(x),za=a⊙z,

where ⊙⊙ is element-wise multiplication. We can talk about soft attention, which multiplies features with a (soft) mask of values between zero and one, or hard attention, when those values are constrained to be exactly zero or one, namely a∈{0,1}ka∈{0,1}k. In the latter case, we can use the hard attention mask to directly index the feature vector: za=z[a]za=z[a] (in Matlab notation), which changes its dimensionality.

To understand why attention is important, we have to think about what a neural network really is: a function approximator. Its ability to approximate different classes of functions depends on its architecture. A typical neural net is implemented as a chain of matrix multiplications and element-wise non-linearities, where elements of the input or feature vectors interact with each other only by addition.

Attention mechanisms compute a mask which is used to multiply features. This seemingly innocent extension has profound implications: suddenly, the space of functions that can be well approximated by a neural net is vastly expanded, making entirely new use-cases possible. Why? While I have no proof, the intuition is following: the theory says that neural networks are universal function approximators and can approximate an arbitrary function to arbitrary precision, but only in the limit of an infinite number of hidden units. In any practical setting, that is not the case: we are limited by the number of hidden units we can use. Consider the following example: we would like to approximate the product of NN inputs. A feed-forward neural network can do it only by simulating multiplications with (many) additions (plus non-linearities), and thus it requires a lot of neural-network real estate. If we introduce multiplicative interactions, it becomes simple and compact.

The above definition of attention as multiplicative interactions allow us to consider a broader class of models if we relax the constrains on the values of the attention mask and let a∈Rka∈Rk. For example,Dynamic Filter Networks (DFN) use a filter-generating network, which computes filters (or weights of arbitrary magnitudes) based on inputs, and applies them to features, which effectively is a multiplicative interaction. The only difference with soft-attention mechanisms is that the attention weights are not constrained to lie between zero and one. Going further in that direction, it would be very interesting to learn which interactions should be additive and which multiplicative, a concept explored in A Differentiable Transition Between Additive and Multiplicative Neurons. The excellent distill blog provides a great overview of soft-attention mechanisms.

Visual Attention

Attention can be applied to any kind of inputs, regardless of their shape. In the case of matrix-valued inputs, such as images, we can talk about visual attention. Let I∈RH×WI∈RH×W be an image and g∈Rh×wg∈Rh×wan attention glimpse i.e. the result of applying an attention mechanism to the image II.

Hard Attention

Hard attention for images has been known for a very long time: image cropping. It is very easy conceptually, as it only requires indexing. Hard-attention can be implemented in Python (or Tensorflow) as

  1. g = I[y:y+h, x:x+w]

The only problem with the above is that it is non-differentiable; to learn the parameters of the model, one must resort to e.g. the score-function estimator, briefly mentioned in my previous post.

Soft Attention

Soft attention, in its simplest variant, is no different for images than for vector-valued features and is implemented exactly as in equation 11. One of the early uses of this types of attention comes from the paper called Show, Attend and TellThe model learns to attend to specific parts of the image while generating the word describing that part.

This type of soft attention is computationally wasteful, however. The blacked-out parts of the input do not contribute to the results but still need to be processed. It is also over-parametrised: sigmoid activations that implement the attention are independent of each other. It can select multiple objects at once, but in practice we often want to be selective and focus only on a single element of the scene. The two following mechanisms, introduced by DRAW and Spatial Transformer Networks, respectively, solve this issue. They can also resize the input, leading to further potential gains in performance.

Gaussian Attention

Gaussian attention works by exploiting parametrised one-dimensional Gaussian filters to create an image-sized attention map. Let ay∈Rhay∈Rh and ax∈Rwax∈Rw be attention vectors, which specify which part of the image should be attended to in yy and xx axis, respectively. The attention masks can be created as a=ayaTxa=ayaxT.

In the above figure, the top row shows axax, the column on the right shows ayay and the middle rectangle shows the resulting aa. Here, for the visualisation purposes, the vectors contain only zeros and ones. In practice, they can be implemented as vectors of one-dimensional Gaussians. Typically, the number of Gaussians is equal to the spatial dimension and each vector is parametrised by three parameters: centre of the first Gaussian μμ, distance between centres of consecutive Gaussians dd and the standard deviation of the Gaussians σσ. With this parametrisation, both attention and the glimpse are differentiable with respect to attention parameters, and thus easily learnable.

Attention in the above form is still wasteful, as it selects only a part of the image while blacking-out all the remaining parts. Instead of using the vectors directly, we can cast them into matrices Ay∈Rh×HAy∈Rh×Hand Ax∈Rw×WAx∈Rw×W, respectively. Now, each matrix has one Gaussian per row and the parameter ddspecifies distance (in column units) between centres of Gaussians in consecutive rows. Glimpse is now implemented as

g=AyIATx.g=AyIAxT.

I used this mechanism in HART, my recent paper on biologically-inspired object tracking with RNNs with attention. Here is an example with the input image on the left hand side and the attention glimpse on the right hand side; the glimpse shows the box marked in the main image in green:

 

The code below lets you create one of the above matrix-valued masks for a mini-batch of samples in Tensorflow. If you want to create AyAy, you would call it as Ay = gaussian_mask(u, s, d, h, H), where u, s, d are μ,σμ,σ and dd, in that order and specified in pixels.

  1. def gaussian_mask(u, s, d, R, C):
  2. """
  3. :param u: tf.Tensor, centre of the first Gaussian.
  4. :param s: tf.Tensor, standard deviation of Gaussians.
  5. :param d: tf.Tensor, shift between Gaussian centres.
  6. :param R: int, number of rows in the mask, there is one Gaussian per row.
  7. :param C: int, number of columns in the mask.
  8. """
  9. # indices to create centres
  10. R = tf.to_float(tf.reshape(tf.range(R), (1, 1, R)))
  11. C = tf.to_float(tf.reshape(tf.range(C), (1, C, 1)))
  12. centres = u[np.newaxis, :, np.newaxis] + R * d
  13. column_centres = C - centres
  14. mask = tf.exp(-.5 * tf.square(column_centres / s))
  15. # we add eps for numerical stability
  16. normalised_mask /= tf.reduce_sum(mask, 1, keep_dims=True) + 1e-8
  17. return normalised_mask

We can also write a function to directly extract a glimpse from the image:

  1. def gaussian_glimpse(img_tensor, transform_params, crop_size):
  2. """
  3. :param img_tensor: tf.Tensor of size (batch_size, Height, Width, channels)
  4. :param transform_params: tf.Tensor of size (batch_size, 6), where params are (mean_y, std_y, d_y, mean_x, std_x, d_x) specified in pixels.
  5. :param crop_size): tuple of 2 ints, size of the resulting crop
  6. """
  7. # parse arguments
  8. h, w = crop_size
  9. H, W = img_tensor.shape.as_list()[1:3]
  10. uy, sy, dy, ux, sx, dx = tf.split(transform_params, 6, -1)
  11. # create Gaussian masks, one for each axis
  12. Ay = mask(uy, sy, dy, h, H)
  13. Ax = mask(ux, sx, dx, w, W)
  14. # extract glimpse
  15. glimpse = tf.matmul(tf.matmul(Ay, img_tensor, adjoint_a=True), Ax)
  16. return glimpse

Spatial Transformer

Spatial Transformer (STN) allows for much more general transformation that just differentiable image-cropping, but image cropping is one of the possible use cases. It is made of two components: a grid generator and a sampler. The grid generator specifies a grid of points to be sampled from, while the sampler, well, samples. The Tensorflow implementation is particularly easy in Sonnet, a recent neural network library from DeepMind.

  1. def spatial_transformer(img_tensor, transform_params, crop_size):
  2. """
  3. :param img_tensor: tf.Tensor of size (batch_size, Height, Width, channels)
  4. :param transform_params: tf.Tensor of size (batch_size, 4), where params are (scale_y, shift_y, scale_x, shift_x)
  5. :param crop_size): tuple of 2 ints, size of the resulting crop
  6. """
  7. constraints = snt.AffineWarpConstraints.no_shear_2d()
  8. img_size = img_tensor.shape.as_list()[1:]
  9. warper = snt.AffineGridWarper(img_size, crop_size, constraints)
  10. grid_coords = warper(transform_params)
  11. glimpse = snt.resampler(img_tensor, grid_coords)
  12. return glimpse

Gaussian Attention vs. Spatial Transformer

Both Gaussian attention and Spatial Transformer can implement a very similar behaviour. How do we choose which to use? There are several nuances:

  • Gaussian attention is an over-parametrised cropping mechanism: it requires six parameters, but there are only four degrees of freedom (y, x, height width). STN needs only four parameters.

  • I haven’t run any tests yet, but STN should be faster. It relies on linear interpolation at sampling points, while the Gaussian attention has to perform two huge matrix multiplication. STN could be an order of magnitude faster (in terms of pixels in the input image).

  • Gaussian attention should be (no tests run) easier to train. This is because every pixel in the resulting glimpse can be a convex combination of a relatively big patch of pixels of the source image, which (informally) makes it easier to find the cause of any errors. STN, on the other hand, relies on linear interpolation, which means that gradient at every sampling point is non-zero only with respect to the two nearest pixels.

Closing Thoughts

Attention mechanisms expand capabilities of neural networks: they allow approximating more complicated functions, or in more intuitive terms, they enable focusing on specific parts of the input. They have led to performance improvements on natural language benchmarks, as well as to entirely new capabilities such as image captioning, addressing in memory networks and neural programmers.

I believe that the most important cases in which attention is useful have not been yet discovered. For example, we know that objects in videos are consistent and coherent, e.g. they do not disappear into thin air between frames. Attention mechanisms can be used to express this consistency prior. How? Stay tuned.

Share this:

 
 

Generative timeseries modelling, but also attention, memory and other cool tricks.

(zhuan) Attention in Neural Networks and How to Use It的更多相关文章

  1. (zhuan) Building Convolutional Neural Networks with Tensorflow

    Ahmet Taspinar Home About Contact Building Convolutional Neural Networks with Tensorflow Posted on a ...

  2. (zhuan) Attention in Long Short-Term Memory Recurrent Neural Networks

    Attention in Long Short-Term Memory Recurrent Neural Networks by Jason Brownlee on June 30, 2017 in  ...

  3. Attention and Augmented Recurrent Neural Networks

    Attention and Augmented Recurrent Neural Networks CHRIS OLAHGoogle Brain SHAN CARTERGoogle Brain Sep ...

  4. 论文解读(ChebyGIN)《Understanding Attention and Generalization in Graph Neural Networks》

    论文信息 论文标题:Understanding Attention and Generalization in Graph Neural Networks论文作者:Boris Knyazev, Gra ...

  5. (zhuan) How to Train Neural Networks With Backpropagation

    this blog from: http://blog.demofox.org/2017/03/09/how-to-train-neural-networks-with-backpropagation ...

  6. 深度卷积神经网络用于图像缩放Image Scaling using Deep Convolutional Neural Networks

    This past summer I interned at Flipboard in Palo Alto, California. I worked on machine learning base ...

  7. Classifying plankton with deep neural networks

    Classifying plankton with deep neural networks The National Data Science Bowl, a data science compet ...

  8. 第十四章——循环神经网络(Recurrent Neural Networks)(第二部分)

    本章共两部分,这是第二部分: 第十四章--循环神经网络(Recurrent Neural Networks)(第一部分) 第十四章--循环神经网络(Recurrent Neural Networks) ...

  9. (转)A Recipe for Training Neural Networks

    A Recipe for Training Neural Networks Andrej Karpathy blog  2019-04-27 09:37:05 This blog is copied ...

随机推荐

  1. QT 继承QWidget && 继承QDialog

    工作项目中,利用到Qt对话框,场景需求: 1. 一部分窗体需要继承自QWidget 2. 一部分窗体需要继承自QDialog 3. 两者均需要去掉标题栏图标,同时能够自由拖动. 如果两者分开继承实现, ...

  2. Spring 无缝整合 quartz

    关键步骤: 1. 配置 SchedulerFactoryBean <bean class="org.springframework.scheduling.quartz.Schedule ...

  3. Linux基础命令---添加用户useradd

    useradd 创建新的系统用户,useradd指令只能以管理员的身份运行,创建的用户都在“/etc/passwd”文件中.当不加-D参数,useradd指令使用命令列来指定新帐号的设定值and使用系 ...

  4. 查询和修改mysql最大连接数的方法

    查询和修改mysql最大连接数的方法切换到mysql库里查询show variables like 'max_connections';show global status like 'Max_use ...

  5. Java 代码性能调优“三十六”策

    代码优化,一个很重要的课题.可能有些人觉得没用,一些细小的地方有什么好修改的,改与不改对于代码的运行效率有什么影响呢?这个问题我是这么考虑的,就像大海里面的鲸鱼一样,它吃一条小虾米有用吗?没用,但是, ...

  6. GROUP BY 和 ORDER BY 同时使用问题

    GROUP BY 和 ORDER BY一起使用时,ORDER BY要在GROUP BY的后面.

  7. SpringMVC之JSON交互

    #什么是json? json是一种用于储存数据格式,是js脚本语言的子集. #json的作用? 它可以传递对象.数组等数据结构.如果是单个数据,则要用数组,不用对象,因为对象都是键值对的 方式去存储, ...

  8. java.lang.Object.wait(Native Method)

    java.lang.Object.wait(Native Method) java.lang.Object.wait(Object.java:502) java.util.TimerThread.ma ...

  9. EDK II之USB主控制器(EHCI)驱动的实现框架

    本文简要介绍一下UEFI中EHCI驱动的代码实现框架: 下图是HCDI: 上图是Host驱动程序向上层驱动提供的接口图: 1.大部分接口的最后动作都是去操作主控制器寄存器,ECHI的spec:< ...

  10. JDK源码之ThreadLocal

    1.定义 ThreadLocal是线程变量,就是说每一个线程都有对应的该变量副本,线程修改该变量时,线程与线程之间的变量是相互隔离的,互相并看不见.这个结构附带在线程上,一个线程可以根据ThreadL ...