【515】keras 张量操作
参考:keras-team / keras - github
keras 的实质就是对于张量的操作,所以对于某些函数的理解,需要自己通过张量的实操来体会。同时每一个网络层的输入和输出也都是张量的操作,可以参见下面链接进行简单张量 Tensor 的操作。
参考:【tensorflow】张量(tensor,数组)的定义和声明 —— 入门,简单了解
参考:TensorFlow官方文档 —— 完善,不过内容繁杂
参考:tensorflow学习笔记:张量介绍以及张量操作函数 —— 入门,简单了解
1. 环境配置
大部分操作还是要基于 TensorFlow,由于某些函数依赖于更高版本的 TensorFlow,因此需要将其升级到最新版,简单的方法就是:(参考:tensorflow指定版本的安装及升级到最新版)
1 2 3 4 5 6 7 8 9 10 11 12 | # 升级到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...)
1 | pip install - - upgrade tensorflow - - user |
2. 具体类及函数
2.1 keras.layers.Multiply
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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 |
☀☀☀<< 举例 >>☀☀☀
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | >>> 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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),举例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | >>> 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) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2013-01-01 【096】2012年总结(流水账式)