Never stop learning, approaching the AI
  • 😄About
  • 🅰️AI-Candy on YouTube
    • 🎬YouTube 视频列表
    • 💠AI项目本地部署
      • 1️⃣安装 Pytorch 运行环境
      • 2️⃣在Python虚拟环境下使用 VS Code or PyCharm
        • VS Code Python format
      • 3️⃣Create python virtual environment in Linux
    • 👽AI 入门系列课程
      • 0️向量及向量运算
        • Reshape array code
      • 1️人工智能,机器学习,深度学习 和神经网络的区别
      • 2️卷积神经网络(CNN)
        • 3D CNN sample code
      • 3️Transformer 原理
      • 4️前馈神经网络 (FNN)
  • 🎭Artificial intelligence
    • 1️⃣Deep learning / machine learning
      • 👉Deep Learning Resources
      • 👉Deep learning notes
    • 2️⃣Python
      • Youtube音乐下载
      • Pytorch 安装环境配置 (old)
        • TorchEEG
      • Anaconda3 Python path
      • Data
      • IEEE-754 Floating Point Converter
        • ieee 754 conversion function
      • 文件读写
      • 文本清理
      • Python 下载在线视频
      • 修改Jupyter Notebook 默认工作目录
    • 3️⃣AI Websites
  • 🪤Programming
    • SQL
      • Delete data and reset auto-increment ID
    • Angular
      • Angular-datatables, dd/MM/yyyy, sorting (no paged list)
      • Datatables save state using localStorage
      • Variable storage method
      • Colour picker
      • Error fix for click columns on Datatable
      • Auto address use Google place
      • Auto address use Azure Maps
      • Upload file to Server
      • Validators.required OnChange input
      • Date, Time field
      • VS Code: Auto add missing imports when save
      • Datatable setting
      • Date time format
      • sticky <th> and <td> content
      • Filter booked time
      • Dropdown time selection with interval
      • Angular date online test
      • Updating data without refreshing the page
      • Object array sort and sum
      • Multi-type of columns use in one column
      • Select button for datatables
      • Switch button and event
      • Delete column from Array
      • Three-layer structure
      • Remove shadow when print mat-dialog content
      • JSON Parse && Object Array
      • Detect unused import in Typescript
      • Change location using radio button
      • display multi line message in the Toastr
      • Custom LOCALE_ID
      • Batch add data from csv to API server
        • Angular read csv and upload to Server
      • USB Port reader Web solution
      • Debug Angular app using JavaScript Debugger in VS Code
      • Skills
        • FormData & FormGroup to JSON
        • Dropdown list (customer)
        • Get current datetime
        • Get first day of year, month, and date
        • Call a function in a forEach loop
        • disable and readonly
        • Form element value
        • HTML input type
        • Input pattern (validation)
      • Display pipe (UI format)
        • Input upper case and button checked
        • Icons (Bootstrap and CoreUI)
        • Page Refresh
        • Selection list (two ways)
        • onChange Selection event
        • Random Password and Toggle
        • Password match
        • Select checkbox disable
      • Print and save to PDF
      • Import JS into Angular
      • LocalStorage
      • Angular DataTable
        • Data sort
        • A sample usage
        • Angular DataTable server side big data query
      • Change chart.js chart type
      • Angular UI - .NET API - .NET Auth
      • Angular - .NET API
      • *ngIf else && change to @if
      • Angular add reCAPTCHA v3 (Google)
      • Angular update
        • Update from v13 to v15
        • Update from v15 to v18
      • Angular application version central
      • Face detection
        • Face-api.js
      • Angular, Node version compatibility matrix
      • Clear cache
      • Angular oauth2 OIDC
      • Angular add header
    • .NET Skills
      • Add ID manually
      • Auto Mapping
        • Ignore Nesting
        • Startup setting
        • Datetime processing in AutoMapping
        • AutoMapper example
      • Validation filter
      • BaseController
      • Group by many
      • Database first, scaffold to class
      • Log setting and exception handler
      • Update appsetting.json value
      • Azure service bus message (queue)
      • Read appsetting.json value
      • Auth get user info by email
      • Azure Time zone
      • .NET API Add Service
      • Object comparison
      • Coravel Schedule
        • Read appsettings.json
      • .Net Core RDLC Report, Coravel and Email
      • Check Network and SQL server connections.
      • Datatime custom format
      • Many to Many EF
        • Many to Many CheckBox
      • PDFpig: Send Email with PDF attachment
      • .NET Core Middleware order
      • .NET API add Worker Service
      • .NET Router
      • Partial columns update
      • Add and Delete
      • 图片自适应宽度
      • ASP.NET Identity
      • Upload file to Azure
        • Upload file to Blob
      • Developer Guide
      • Code first one-many
      • ASP.NET MVC 5 Custom Error Page
      • VS can't debug
      • 通过邮编查 NSW COVID-19 感染人数
      • Jquery File Upload
      • Jquery Datepicker
      • ajax delete file from server
      • Autofac in MVC
      • Autofac in .NET Core
      • .NET Core
      • HTTP Return code
      • IdentityServer4
    • Power BI
      • Add parameter to PowerBI report
      • Convert UTC to Local time
      • Python in PowerBI
        • IEEE-754 conversion
      • PowerBI embed app - Server
      • PowerBI embed app - Client
        • Setting on portal
    • Azure service
      • Key Vault
      • Service bus - queue
      • Power Automate
      • Kusto Query Language
      • Azure Data Explorer
      • Reserved keyword on Azure Error
      • SQL Azure time convert
    • Azure blob
      • Azure blob setting
      • Display image from Blob
      • Upload image to Blob through .NET API
    • Html Bootstrap Icon, colour, size
      • Html spacing
      • Html text alignment
    • Video stream - JsMpeg
      • SSL - generate key
      • Client (SSL)
      • Websocket-Server (SSL)
      • Play RTSP video stream
    • ⏰Time Zone
      • datetime-local set date range
      • 🕐Get data by local time (UI, API)
      • 🕑Add offset hours for local UI and report
      • 🕒UTC time and Datetime convert
      • 🕓Angular - Timezone selection
      • 🕔Angular - Convert UTC to local time
      • 🕕C# Time Zone
  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>
  • 🪜Apps and Skills
    • 1️Windows system app skills
      • Brother HL-2130 打印机 Toner 报警
      • VS Code 快捷键
      • Check SHA256 on windows
      • blob 视频下载
      • Photoshop 制作证件照片
      • 获取 Windows Key
      • 10进制36进制互转
      • Error when publish to Azure
      • Disable windows automatic update
      • Outlook setup for Yahoo Email
      • IIS setting
      • Windows 8/10, IIS Service
      • 安装程序出错 2052,2053 报警
      • 6 Yao Chinese UI
    • 2️Linux command
    • 3️Git command
    • 4️Bitbucket
    • 5️Gitbook Skills
    • 6️GitHub Desktop
    • 7️⃣EndNote
      • EndNote V21
      • Endnote使用技巧
      • 批量删除/修改Endnote 中 notes 栏内容
  • Android mobile connect PC
  • 💎USEFUL LINKS
    • 1️Coding websites
      • Website links
    • 2️Windows 平台工具,网站
    • 3️PotPlayer 设置
  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>
  • 🚩Research >>EEG
    • 1️EEG基本知识的理论介绍
      • EEG 简介
      • EEG 的节律信号
      • EEG电极帽
      • EEG 伪迹
      • ERP 介绍
      • ERP 成分
      • EEG 数据分析软件
    • 2️LSL 应用
    • 3️EEG公开数据集汇总整理
    • 4️REDCap
      • Migration (Export & Import)
    • 5️⃣ScaneR
  • ☕Buy me a coffee
Powered by GitBook
On this page

Was this helpful?

  1. AI-Candy on YouTube
  2. AI 入门系列课程

Transformer 原理

<<Attention Is All You Need>> paper study

Previous3D CNN sample codeNext前馈神经网络 (FNN)

Last updated 11 months ago

Was this helpful?

Trasnformer 是基于循环神经网络Recurrent Neural Network (RNN) , 加入自注意力机制 (Self-Attention) 的深度学习模型。

  • RNN是一种序列模型,可以得到序列信息(前一个的顺序会传给后面)。但是,RNN 只能顺序执行,不能并行计算,若数据量大,早期信息容易丢失。Attention 可以并行。

  • CNN可以做多通道输出,但是,对于长数据,难以建模。

  • 序列模型中比较好的是 Encoder-Decoder架构。

Trasnformer 包含了两个主要组成:Encoder 和 Decoder。 (序列模型)

  • Encoder里边有6个小编码器,每一个的小编码器的输入是前一个小编码器的输出。

  • Decoders里边也有6个小解码器。每一个小解码器的输入,不光是它的前一个解码器的输出,还包括了整个编码部分的输出。

  1. Encoder

Encoder 的结构是一个自注意力机制(Self-Attention) + 前馈神经网络(FFN)。

自注意力机制 self-attention:是自己和自己计算一遍注意力(即 q, k, v 可以互换,是自身)。 输入为一个向量,再乘以三个矩阵,得到三个新的向量。如下图:输入向量为X, 乘以 WQ,WK,WV矩阵,就会分别得到新的权重矩阵 Q,K,V。

(Q: Query, K: key, V: value。K 和 V长度相同)

Attention: 将新向量内容分别与K1, K2, Kt 向量进来点积运算,得到相似度(值越大,相似度越高)。再除以根号dk。再将结果进行softmax运算,即:将分数标准化, 归一化运算。(得到大约0,小于1的数,总和为1的权重).

最后,将上述结果分别与V1,V2,Vt 向量进来点积运算,再将结果加起来,得到一个权重矩阵Z。

通过Softmax 将高分值,分给重要的词

自注意力机制:Q, K, V 都来自内部,与外部无关。 Q向量 与 K向量的转置 点积, 生成因子矩阵,如下图:

矩阵 再与 V向量 进行加权合计算, 得到 Z 注意力分数向量 (Attention Score Vector)

Z4 = Q4K1V1 + Q4K2V2 + Q4K3V3 + Q4K4V4

多头注意力机制,顾名思义,包含多个自注意力机制,然后将多个自注意力机制的输出进行拼接,最后通过全连接层得到输出。

输入X, 通过上述方法,得到多组Q/K/V权重矩阵,

然后按照上节描述的那样,得到多个Z。

对多个注意力机制的输出Z进行拼接, 就得到了self-attention层的输出。

最后, 再乘以一个矩阵,得到一个前馈神经网络层的输入。

总结一下: Encoder的架构是对输入进行编码,使用自注意力机制 + 前馈神经网络Position-Wise Feed-Forward Network (FFN) 的结构。

  1. Decoder

Decoder中使用的也是同样的结构。 不同的地方在于,在Encoder的前端增加了一个掩码(Masked)多头自注意力机制(t时间后的信息置为0), 其输出Q。再与前面的 Encoder 的输出(K, V), 作为输入, 进入下一层类似一个Encoder 模块。其输出,计算一遍注意力机制的得分(点积加权平均)。 最后,再进入前馈神经网络模块。

解码器输出本来是一个浮点型的向量。如何实现将“机器学习”翻译成“machine learing”。

  1. 输入,输出

Decoder 后,接上一个softmax变成一个线性层。 使用全连接神经网络,它将解码器产生的向量投影到一个更高维度的向量(logits)上。 之后的softmax层将这些分数转换为概率。选择概率最大的维度, 并对应地生成与之关联的单词作为此时间步的输出就是最终的输出。

但是,上述方法不含有顺序信息。为了实现Transformer的顺序信息,在每个输入词向量加上一个有顺序特征的向量(Positional Encoding), 研究发现sin和cos函数能够很好的表达这种特征。


输入 Embedding: 转换输入和输出(Softmax前) token 映射到一个 512维度 的向量里。在Embedding层是将权重 乘以根号d, (d=512)

输出 Positional Encoding:Attention的输出是一个Value的加权和,没有时序信息。权重是Query与Key之间的距离。意味着,输入不同的顺序词,输出的值相同。为了使得Attention含有顺序信息,使用的Sin , Cos 函数(-1 ~ +1)。


Reference:

🅰️
👽
3️
https://towardsdatascience.com/transformers-explained-visually-not-just-how-but-why-they-work-so-well-d840bd61a9d3
https://papers.nips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf
https://mp.weixin.qq.com/s/slOlE8fe91jZBMYhAV9Z7A https://mp.weixin.qq.com/s?__biz=Mzg3MjY1MzExMA==&mid=2247514134&idx=1&sn=2efa12ff4b0c5211a2bdc13596cc44b9&chksm=cfb6f9ebd0f6539bc5bbcdd305f27b47a3546100e444b43ac2a8e78c8e48a280aea55d61bcc2&scene=132&exptype=timeline_recommend_article_extendread_samebiz&show_related_article=1&subscene=0&poc_token=HC0s7mWjrZK5vW9esQvZFLfHgXa8Sqph7wWBf-Wb https://blog.csdn.net/keyue123/article/details/89209888
使用多头注意力是为了增加学习机会,即W. h=8个头。 d(model)/h=64
计算图
Position-wise Feed-Forward Network
The Transformer - model architecture
:
:
:
Author
Ketan Doshi
Author
Ketan Doshi
Author
Ketan Doshi