TensorFlow batch_dot函数理解

本文详细介绍了在TensorFlow框架下使用Keras的batch_dot函数进行矩阵运算的方法。通过实例演示了不同axes参数设置下batch_dot的计算过程,并与tf.reduce_sum和tf.multiply结合使用验证结果的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

batch_dot实现

载入库

import tensorflow as tf
tf.enable_eager_execution()
import keras.backend as K
import numpy as np

生成输入数据

x1 = tf.convert_to_tensor([[1,2,3],[4,5,6]])
x2 = tf.convert_to_tensor([[1,2,3],[4,5,6]])

K.batch_dot(x1,x2,axes=1).numpy()

axes为1 的batch_dot输出如下:

array([[14],
       [77]], dtype=int32)

axes为2的batch_dot输出如下:

K.batch_dot(x1,x2,axes=0).numpy()
array([[17],
       [29],
       [45]], dtype=int32)

实际上与先经过位对位乘法然后按某一个轴作聚合加法返回的结果一直,下面是验证结果。

tf.reduce_sum(tf.multiply(x1 , x2) , axis=0).numpy()
array([17, 29, 45], dtype=int32)
tf.reduce_sum(tf.multiply(x1 , x2) , axis=1).numpy()
array([14, 77], dtype=int32)
### TensorFlow 中自注意力机制的实现 在TensorFlow中,自注意力机制(self-attention)能够帮助模型聚焦于输入序列的不同部分,从而增强对特定位置的关注程度。这种机制特别适用于自然语言处理(NLP),但也广泛应用于计算机视觉领域。 #### 实现细节 自注意力机制的核心在于计算查询(query)、键(key)以及值(value)三者间的交互关系[^1]。具体而言: - 查询、键和值都是由同一组输入数据变换而来; - 计算过程中会先通过线性投影(linear projection)分别得到这三个矩阵; - 接着利用softmax函数计算出注意力分数(attention scores),这一步骤决定了哪些部分应该被赋予更高的权重; - 最终加权求和获得输出表示。 下面是使用TensorFlow实现简单版多头自注意力(Multi-head Self Attention, MSA)的例子: ```python import tensorflow as tf from tensorflow.keras.layers import Dense, LayerNormalization, Dropout class MultiHeadAttention(tf.keras.Model): def __init__(self, d_model, num_heads): super().__init__() self.num_heads = num_heads self.d_model = d_model assert d_model % self.num_heads == 0 self.depth = d_model // self.num_heads self.wq = Dense(d_model) self.wk = Dense(d_model) self.wv = Dense(d_model) self.dense = Dense(d_model) def split_heads(self, x, batch_size): """Split the last dimension into (num_heads, depth).""" x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth)) return tf.transpose(x, perm=[0, 2, 1, 3]) def call(self, v, k, q, mask=None): batch_size = tf.shape(q)[0] q = self.wq(q) k = self.wk(k) v = self.wv(v) q = self.split_heads(q, batch_size) k = self.split_heads(k, batch_size) v = self.split_heads(v, batch_size) scaled_attention, attention_weights = scaled_dot_product_attention( q, k, v, mask) scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3]) concat_attention = tf.reshape(scaled_attention, (batch_size, -1, self.d_model)) output = self.dense(concat_attention) return output, attention_weights def scaled_dot_product_attention(q, k, v, mask=None): matmul_qk = tf.matmul(q, k, transpose_b=True) dk = tf.cast(tf.shape(k)[-1], tf.float32) logits = matmul_qk / tf.math.sqrt(dk) if mask is not None: logits += (mask * -1e9) attention_weights = tf.nn.softmax(logits, axis=-1) output = tf.matmul(attention_weights, v) return output, attention_weights ``` 此代码片段展示了如何定义一个多头自注意层,并提供了`scaled_dot_product_attention`辅助函数用于执行缩放点积操作。 #### 应用场景 自注意力机制已经被证明可以在多个方面提升性能,尤其是在涉及长期依赖性的任务上表现优异。例如,在机器翻译、文本摘要生成等领域有着广泛应用;而在图像识别任务中,则可通过引入空间维度上的自注意力来捕捉更加丰富的局部模式[^2]。 此外,当面对具有复杂内部结构的数据集时,如文档级别的分类问题或是视频分析等场合下,分层(hierarchical)或多尺度(multi-scale)版本的自注意力架构同样显示出巨大潜力[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值