成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

終于把 Transformer 中的注意力機制搞懂了!!!

人工智能
想象一下,當你讀到 “The cat sat on the mat” 這句話時,人類可以立即理解單詞之間的關系,可以知道 “sat” 與 “cat” 的關系比與“mat”的關系更密切。

大家好,我是小寒

注意力機制是深度學習領域中廣泛應用的技術,特別是在自然語言處理和計算機視覺任務中。它使模型能夠有選擇地關注輸入數據的特定部分,以此提升模型的性能。

想象一下,當你讀到 “The cat sat on the mat” 這句話時,人類可以立即理解單詞之間的關系,可以知道 “sat” 與 “cat” 的關系比與“mat”的關系更密切。

注意力機制使機器能夠捕捉類似的關系,幫助它們專注于輸入數據的特定部分。

圖片

Transformer 中的注意力機制

在 Transformer 模型中,注意力機制是其核心組件,它使得模型可以在處理輸入序列的過程中關注到最重要的信息,從而大幅提高了模型在長序列中的表現。

圖片

自注意力機制

在自注意力機制中,每個輸入向量可以“關注”同一序列中的其他向量,這使得模型能夠靈活地關注整個序列的不同部分。

圖片圖片

下面,我們一起來看一下如何使用代碼來實現上述過程。

import numpy as np

word_embeddings = {
    'she':    np.array([0.2, 0.9, 0.1, 0.5]),
    'likes':  np.array([0.8, 0.3, 0.7, 0.2]),
    'coffee': np.array([0.4, 0.6, 0.3, 0.9])
}

X = np.vstack([word_embeddings['she'], 
               word_embeddings['likes'], 
               word_embeddings['coffee']])
               
W_q = np.array([[0.9, 0.1, 0.1, 0.1],
                [0.1, 0.9, 0.1, 0.1],
                [0.1, 0.1, 0.9, 0.1],
                [0.1, 0.1, 0.1, 0.9]])

W_k = np.array([[0.9, 0.1, 0.1, 0.1],
                [0.1, 0.9, 0.1, 0.1],
                [0.1, 0.1, 0.9, 0.1],
                [0.1, 0.1, 0.1, 0.9]])
W_v = np.array([[0.8, 0.2, 0.1, 0.1],
                [0.2, 0.8, 0.2, 0.1],
                [0.1, 0.2, 0.8, 0.1],
                [0.1, 0.1, 0.1, 0.9]])
                
Q = np.dot(X, W_q)
K = np.dot(X, W_k)
V = np.dot(X, W_v)

scores = np.dot(Q, K.T)

d_k = K.shape[1]
scaled_scores = scores / np.sqrt(d_k)

exp_scores = np.exp(scaled_scores)
attention_weights = exp_scores / exp_scores.sum(axis=1, keepdims=True)

output = np.dot(attention_weights, V)

print(output)

多頭注意力機制(Multi-Head Attention)

多頭注意力機制進一步擴展了自注意力的表達能力。

通過設置多個注意力頭(head),每個頭從不同的子空間中獲取信息,最后將各頭的結果拼接起來并進行線性變換。

這樣模型可以更好地捕捉多維度的依賴關系,使其在復雜任務中表現更為優異。

圖片圖片

多頭注意力的計算流程

多頭注意力機制增加了模型的靈活性,能讓模型從不同角度學習到序列中詞匯間的關系。

class MultiHeadAttention(nn.Module):    
    
    def __init__(self, d_model, num_heads):
        super(MultiHeadAttention, self).__init__()
        # Ensure that the model dimension (d_model) is divisible by the number of heads
        assert d_model % num_heads == 0 
        
        # Initialize dimensions
        self.d_model = d_model # Model's dimension
        self.num_heads = num_heads # Number of attention heads
        self.d_k = d_model // num_heads # Dimension of each head's key, query, and value
        
        # Linear layers for transforming inputs
        self.W_q = nn.Linear(d_model, d_model) # Query transformation
        self.W_k = nn.Linear(d_model, d_model) # Key transformation
        self.W_v = nn.Linear(d_model, d_model) # Value transformation
        self.W_o = nn.Linear(d_model, d_model) # Output transformation
    
    # 縮放點積注意力機制
    def scaled_dot_product_attention(self, Q, K, V, mask=None):
        # Calculate attention scores
        attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
        
        # Apply mask if provided (useful for preventing attention to certain parts like padding)
        if mask is not None:
            attn_scores = attn_scores.masked_fill(mask == 0, -1e9)
        
        # Softmax is applied to obtain attention probabilities
        attn_probs = torch.softmax(attn_scores, dim=-1)
        
        # Multiply by values to obtain the final output
        output = torch.matmul(attn_probs, V)
        return output
        
    def split_heads(self, x):
        # Reshape the input to have num_heads for multi-head attention
        batch_size, seq_length, d_model = x.size()
        return x.view(batch_size, seq_length, self.num_heads, self.d_k).transpose(1, 2)
        
    def combine_heads(self, x):
        # Combine the multiple heads back to original shape
        batch_size, _, seq_length, d_k = x.size()
        return x.transpose(1, 2).contiguous().view(batch_size, seq_length, self.d_model)
        
    def forward(self, Q, K, V, mask=None):
        # Apply linear transformations and split heads
        Q = self.split_heads(self.W_q(Q))
        K = self.split_heads(self.W_k(K))
        V = self.split_heads(self.W_v(V))
        
        # Perform scaled dot-product attention
        attn_output = self.scaled_dot_product_attention(Q, K, V, mask)
        
        # Combine heads and apply output transformation
        output = self.W_o(self.combine_heads(attn_output))
        return output
責任編輯:武曉燕 來源: 程序員學長
相關推薦

2024-10-16 07:58:48

2024-12-03 08:16:57

2024-08-01 08:41:08

2024-07-17 09:32:19

2024-09-23 09:12:20

2025-02-17 13:09:59

深度學習模型壓縮量化

2024-08-23 09:06:35

機器學習混淆矩陣預測

2024-09-18 16:42:58

機器學習評估指標模型

2024-10-14 14:02:17

機器學習評估指標人工智能

2024-11-05 12:56:06

機器學習函數MSE

2024-10-08 15:09:17

2024-10-08 10:16:22

2024-10-28 15:52:38

機器學習特征工程數據集

2024-10-28 00:00:10

機器學習模型程度

2024-10-30 08:23:07

2025-01-15 11:25:35

2025-01-20 09:21:00

2024-12-26 00:34:47

2024-12-02 01:10:04

神經網絡自然語言DNN

2024-12-02 13:28:44

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 91久久国产综合久久91精品网站 | 午夜免费观看体验区 | 欧美福利视频一区 | 精品一区二区三区免费视频 | 亚洲性在线| 日韩精品视频中文字幕 | eeuss国产一区二区三区四区 | 中文字幕乱码视频32 | 日韩免费在线视频 | 国产特级毛片aaaaaa喷潮 | 欧美精品久久久 | 五月婷婷在线播放 | 久久精品亚洲 | 国产精品久久久久久久久久免费看 | 一区二区在线 | 在线看无码的免费网站 | 亚洲网在线 | 亚洲激情一区二区三区 | 龙珠z在线观看 | 成人午夜电影网 | 久草精品视频 | 国产精品精品久久久 | 精品国产一区二区三区观看不卡 | 亚洲乱码国产乱码精品精98午夜 | 国产精品久久久久久久久久久久冷 | 欧美日韩在线免费 | 日韩精品一区二区三区视频播放 | 午夜爽爽男女免费观看hd | 日本网站免费在线观看 | 成人久久久| 精品视频免费 | 一二三四av | 久久久久国产一区二区三区 | 青青草亚洲 | 久久aⅴ乱码一区二区三区 亚洲国产成人精品久久久国产成人一区 | 日操操 | 国产成在线观看免费视频 | 亚洲综合色视频在线观看 | 一区二区视频在线观看 | 国产精品高潮呻吟久久av野狼 | 欧美日批 |