Self-entertainment (自娱自乐)

本文通过一首歌词形式的内容探讨了自娱自乐的重要性,并强调个人幸福很多时候需要依靠自我创造。文中提到除了酒精和香烟之外,还需要另一个精神世界来获得真正的快乐。
自娱自乐Self-entertainment 我不知道什么是寂寞Loneliness is nothing to me 深夜与凌晨同样精彩I have my fancy midnight and down只要我的双手存在I can get happiness alone那么我就能得道自己的快乐Cause I have my hands with me不过Yes除了酒精和香烟I need another world我还需要另一个世界besides alcohol and cigaretter假若你告诉我Don't you know你不懂得自娱自乐what is self-entertainment?那么 我告诉你Then I tell you,girl其实大多数的高潮You are the last one最后还得靠自己!who makes you high!
### Self-Attention(自注意力机制)代码实现 为了更好地理解并实现自我注意力机制,下面提供了一个基于PyTorch框架的简单版本。此实现涵盖了查询(Q)、键(K)、值(V)三个核心组件以及它们之间的交互方式。 ```python import torch import torch.nn as nn import math class ScaledDotProductAttention(nn.Module): """Scaled dot-product attention mechanism.""" def __init__(self, d_k): super(ScaledDotProductAttention, self).__init__() self.d_k = d_k def forward(self, Q, K, V, attn_mask=None): # 计算注意力得分 scores: [batch_size, n_heads, seq_len, seq_len] scores = torch.matmul(Q, K.transpose(-1, -2)) / math.sqrt(self.d_k) # 如果提供了掩码,则应用掩码 if attn_mask is not None: scores.masked_fill_(attn_mask, -1e9) # 应用softmax函数得到权重分布 attn_weights = nn.Softmax(dim=-1)(scores) # 加权求和获得输出 output = torch.matmul(attn_weights, V) return output, attn_weights class MultiHeadAttention(nn.Module): """Multi-head self-attention layer""" def __init__(self, d_model, num_heads): super(MultiHeadAttention, self).__init__() assert d_model % num_heads == 0, "d_model must be divisible by num_heads" self.num_heads = num_heads self.d_k = d_model // num_heads # 定义线性变换层用于生成QKV self.W_Q = nn.Linear(d_model, d_model) self.W_K = nn.Linear(d_model, d_model) self.W_V = nn.Linear(d_model, d_model) self.fc_out = nn.Linear(d_model, d_model) def split_heads(self, x, batch_size): """ 将输入张量拆分为多个头,并调整维度顺序以便后续操作. 输入形状:[batch_size, seq_length, embed_dim] -> 输出形状:[batch_size, num_heads, seq_length, depth] """ x = x.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2) return x def combine_heads(self, x): """ 合并多头后的特征表示. 输入形状:[batch_size, num_heads, seq_length, depth]-> 输出形状:[batch_size, seq_length, embed_dim] """ x = x.transpose(1, 2).contiguous().view(x.size(0), -1, self.num_heads * self.d_k) return x def forward(self, Q, K, V, mask=None): batch_size = Q.size(0) # 对Q,K,V做线性变换后再分头处理 Q = self.split_heads(self.W_Q(Q), batch_size) K = self.split_heads(self.W_K(K), batch_size) V = self.split_heads(self.W_V(V), batch_size) # 使用缩放点积注意力机制计算加权平均值 out, _ = ScaledDotProductAttention(self.d_k)(Q, K, V, mask) # 合并各头部的结果并通过全连接层映射回原始维度空间 out = self.combine_heads(out) out = self.fc_out(out) return out ``` 上述代码实现了单个标度点乘法注意力模块及其扩展形式——多头注意力机制[^1]。通过这种方式可以有效地捕捉序列数据中的长期依赖关系,在自然语言处理等领域取得了显著效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值