参考:keras-team / keras - github
keras 的实质就是对于张量的操作,所以对于某些函数的理解,需要自己通过张量的实操来体会。同时每一个网络层的输入和输出也都是张量的操作,可以参见下面链接进行简单张量 Tensor 的操作。
参考:【tensorflow】张量(tensor,数组)的定义和声明 —— 入门,简单了解
参考:TensorFlow官方文档 —— 完善,不过内容繁杂
参考:tensorflow学习笔记:张量介绍以及张量操作函数 —— 入门,简单了解
1. 环境配置
大部分操作还是要基于 TensorFlow,由于某些函数依赖于更高版本的 TensorFlow,因此需要将其升级到最新版,简单的方法就是:(参考:tensorflow指定版本的安装及升级到最新版)
# 升级到CPU最新版 # cmd输入如下代码 pip install--upgrade tensorflow # 升级到GPU最新版 # cmd输入如下代码 pip install --upgrade tensorflow-gpu # 查看当前TensorFlow版本 # python输入如下代码 import tensorflow as tf tf.__version__
升级的过程中可能可能遇到升级出错的以下错误“ERROR: Could not install packages due to an EnvironmentError: [WinError 5] 拒绝访问...”,可以将升级的代码改写如下:(参考:完美解决:ERROR: Could not install packages...)
pip install--upgrade tensorflow --user
2. 具体类及函数
2.1 keras.layers.Multiply
class Multiply(_Merge): """Layer that multiplies (element-wise) a list of inputs. It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). >>> tf.keras.layers.Multiply()([np.arange(5).reshape(5, 1), ... np.arange(5, 10).reshape(5, 1)]) <tf.Tensor: shape=(5, 1), dtype=int64, numpy= array([[ 0], [ 6], [14], [24], [36]])> >>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) >>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) >>> multiplied = tf.keras.layers.Multiply()([x1, x2]) >>> multiplied.shape TensorShape([5, 8]) """ def _merge_function(self, inputs): output = inputs[0] for i in range(1, len(inputs)): output *= inputs[i] return output
☀☀☀<< 举例 >>☀☀☀
>>> a = np.arange(20).reshape(5,4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]) >>> b = np.arange(5).reshape(5,1) >>> b array([[0], [1], [2], [3], [4]]) >>> tf.keras.layers.Multiply()([a, b]) <tf.Tensor: shape=(5, 4), dtype=int32, numpy= array([[ 0, 0, 0, 0], [ 4, 5, 6, 7], [16, 18, 20, 22], [36, 39, 42, 45], [64, 68, 72, 76]])>
点乘,并且满足 numpy 的广播机制。
2.2 keras.layers.Softmax
class Softmax(Layer): """Softmax activation function. Example without mask: >>> inp = np.asarray([1., 2., 1.]) >>> layer = tf.keras.layers.Softmax() >>> layer(inp).numpy() array([0.21194157, 0.5761169 , 0.21194157], dtype=float32) >>> mask = np.asarray([True, False, True], dtype=bool) >>> layer(inp, mask).numpy() array([0.5, 0. , 0.5], dtype=float32) Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as the input. Args: axis: Integer, or list of Integers, axis along which the softmax normalization is applied. Call arguments: inputs: The inputs, or logits to the softmax layer. mask: A boolean mask of the same shape as `inputs`. Defaults to `None`. Returns: softmaxed output with the same shape as `inputs`. """
这个说明主要是针对 Attention 实现中的 Softmax 使用,对于输入为 (a, b, 1) 的张量,经过 Softmax 之后,并不会对第 2 维度做 softmax,而是对最后一维的一个数字进行操作,因此所有的结果都变成了 1。正确方法是先 squeeze 成二维,即 (a, b),然后进行 Softmax 操作,然后再 expand_dim 到三维,即 (a, b, 1),举例如下:
>>> a = np.arange(6.0).reshape(2, 3, 1) >>> a array([[[0.], [1.], [2.]], [[3.], [4.], [5.]]]) >>> b = a.squeeze() >>> b array([[0., 1., 2.], [3., 4., 5.]]) >>> c = tf.keras.layers.Softmax()(b) >>> c <tf.Tensor: shape=(2, 3), dtype=float32, numpy= array([[0.09003057, 0.24472848, 0.66524094], [0.09003057, 0.24472848, 0.66524094]], dtype=float32)> >>> d = np.expand_dims(c, axis=-1) >>> d array([[[0.09003057], [0.24472848], [0.66524094]], [[0.09003057], [0.24472848], [0.66524094]]], dtype=float32)