实现pytorch注意力机制-one demo

主要组成部分:

1. 定义注意力层

定义一个Attention_Layer类,接受两个参数:hidden_dim(隐藏层维度)和is_bi_rnn(是否是双向RNN)。

2. 定义前向传播:

定义了注意力层的前向传播过程,包括计算注意力权重和输出。

3. 数据准备

生成一个随机的数据集,包含3个句子,每个句子10个词,每个词128个特征。

4. 实例化注意力层:

实例化一个注意力层,接受两个参数:hidden_dim(隐藏层维度)和is_bi_rnn(是否是双向RNN)。

5. 前向传播

将数据传递给注意力层的前向传播方法。

6. 分析结果

获取第一个句子的注意力权重。

7. 可视化注意力权重

使用matplotlib库可视化了注意力权重。

python 复制代码
**主要函数和类:**
Attention_Layer类:定义了注意力层的结构和前向传播过程。
forward方法:定义了注意力层的前向传播过程。
torch.from_numpy函数:将numpy数组转换为PyTorch张量。
matplotlib库:用于可视化注意力权重。
python 复制代码
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt

# 定义注意力层
class Attention_Layer(nn.Module):
    def __init__(self, hidden_dim, is_bi_rnn):
        super(Attention_Layer,self).__init__()
        self.hidden_dim = hidden_dim
        self.is_bi_rnn = is_bi_rnn
        if is_bi_rnn:
            self.Q_linear = nn.Linear(hidden_dim * 2, hidden_dim * 2, bias = False)
            self.K_linear = nn.Linear(hidden_dim * 2, hidden_dim * 2, bias = False)
            self.V_linear = nn.Linear(hidden_dim * 2, hidden_dim * 2, bias = False)
        else:
            self.Q_linear = nn.Linear(hidden_dim, hidden_dim, bias = False)
            self.K_linear = nn.Linear(hidden_dim, hidden_dim, bias = False)
            self.V_linear = nn.Linear(hidden_dim, hidden_dim, bias = False)
        
    def forward(self, inputs, lens):
        # 获取输入的大小
        size = inputs.size()
        Q = self.Q_linear(inputs) 
        K = self.K_linear(inputs).permute(0, 2, 1)
        V = self.V_linear(inputs)
        max_len = max(lens)
        sentence_lengths = torch.Tensor(lens)
        mask = torch.arange(sentence_lengths.max().item())[None, :] < sentence_lengths[:, None]
        mask = mask.unsqueeze(dim = 1)
        mask = mask.expand(size[0], max_len, max_len)
        padding_num = torch.ones_like(mask)
        padding_num = -2**31 * padding_num.float()
        alpha = torch.matmul(Q, K)
        alpha = torch.where(mask, alpha, padding_num)
        alpha = F.softmax(alpha, dim = 2)
        out = torch.matmul(alpha, V)
        return out

# 准备数据
data = np.random.rand(3, 10, 128)  # 3个句子,每个句子10个词,每个词128个特征
lens = [7, 10, 4]  # 每个句子的长度

# 实例化注意力层
hidden_dim = 64
is_bi_rnn = True
att_L = Attention_Layer(hidden_dim, is_bi_rnn)

# 前向传播
att_out = att_L(torch.from_numpy(data).float(), lens)

# 分析结果
attention_weights = att_out[0, :, :].detach().numpy()  # 获取第一个句子的注意力权重

# 可视化注意力权重
plt.imshow(attention_weights, cmap='hot', interpolation='nearest')
plt.colorbar()
plt.show()
相关推荐
scdifsn几秒前
动手学深度学习12.1. 编译器和解释器-笔记&练习(PyTorch)
pytorch·笔记·深度学习·编辑器·解释器·命令式编程·符号式编程
David Bates5 分钟前
代码随想录第40天:图论1
python·算法·图论
白杆杆红伞伞8 分钟前
02_线性模型(回归线性模型)
人工智能·数据挖掘·回归
Johny_Zhao18 分钟前
堆叠、MLAG、VPC、VSS 技术对比及架构建议
linux·网络·人工智能·python·网络安全·ai·信息安全·云计算·cisco·等保测评·huawei·系统运维
颜淡慕潇18 分钟前
【Python】超全常用 conda 命令整理
chrome·python·conda
jie1889457586622 分钟前
Python中,正则表达式,
开发语言·python·正则表达式
waterHBO25 分钟前
python 上海新闻爬虫, 上观新闻 + 腾讯新闻
爬虫·python
OJAC近屿智能26 分钟前
英伟达发布Llama-Nemotron系列新模型,性能超越DeepSeek-R1
大数据·人工智能·ui·aigc·llama
白开水就盒饭34 分钟前
Python代码编程基础
windows·python·microsoft
Auc2435 分钟前
Java 原生实现代码沙箱(OJ判题系统第1期)——设计思路、实现步骤、代码实现
java·开发语言·python