Pytorch实现Transformer

使用Pytorch从零实现Transformer模型 2017年Google在论文《Attention is All You Need》中提出了Transformer模型,并成功应用到NLP领域。该模型完全基于自注意力机制Attention mechanism实现,弥补了传统的RNN模型的不足。本文笔者将详解使用Pytorch从零开始逐步实现Transformer模型。 阅读详情

实现add&Normalize

在这里插入图片描述
首先实现这个部分是因为不论解码器还是编码器都需要这一部分。
首先我们假设归一化(LayerNorm)已经做好了。

class SublayerConnection(nn.Module):
    def __init__(self,size,dropout=0.1):
        super(SublayerConnection,self).__init__()
        self.layer_norm = LayerNorm(size)
        # 假设LayerNorm已经做好,做一个dropout防止过拟合
        self.dropout = nn.Dropout(p=dropout)
    def forward(self,x,sublayer):
        # x+sublayer(x)就是add,sublayer就是上一步的操作
        return self.dropout(self.layer_norm(x+sublayer(x)))

因为我们不确定是Encoder还是Decoder,所以用sublayer传入来作为上一层。
接下来实现LayerNorm

class LayerNorm(nn.Module):
    def __init__(self,x_size,eps=1e-6):
        super(LayerNorm,self).__init__()
        self.a_2 = nn.Parameter(torch.ones(x_size))
        self.b_2 = nn.Parameter(torch.zeros(x_size))
        self.eps = eps
    def forward(self,x):
        mean = x.mean(-1,keepdim = True)
        std = x.std(-1,keepdim = True)
        return self.a_2*(x-mean)/(math.sqrt(std)+self.eps)+self.b_2

这一串代码很简单,就是公式的实现而已,注意要把a_2和b_2作为可以学习的变量。

实现多头注意力机制和自注意力机制

自注意力机制

def self_attention(query,key,value,dropout = None,mask = None):
    d_k = query.size(-1)
    sores = np.matmul(query,key.transpose(-2,-1))/math.sqrt(d_k)
    attn_softmax = F.softmax(sores,dim=-1)
    if dropout is not None:
        attn_softmax = dropout(attn_softmax)
    return np.matmul(attn_softmax,value),attn_softmax

实现QKV的相乘,除以dk\sqrt{d_k}dk​​为了便于softmax得出的概率差距不会太极端。

多头自注意力机制

class MultiHeadattention(nn.Module):
    def __init__(self,head,d_model,dropout = 0.1):
        super(MultiHeadattention,self).__init__()
        assert(d_model % head == 0)
        self.d_k = d_model//head
        self.head = head
        self.d_model = d_model
        self.linear_quary = nn.Linear(d_model,d_model)
        self.linear_key = nn.Linear(d_model,d_model)
        self.linear_value = nn.Linear(d_model,d_model)
        self.linear_out = nn.Linear(d_model,d_model)
        self.dropout = nn.Dropout(p=dropout)
        self.attn = None
    def forward(self,quary,key,value,mask = None):
        n_batch = quary.size(0)
        quary = self.linear_quary(quary).view(n_batch,-1,self.head,self.d_k).transpose(1,2)
        key = self.linear_key(key).view(n_batch,-1,self.head,self.d_k).transpose(1,2)
        value = self.linear_value(value).view(n_batch,-1,self.head,self.d_k).transpose(1,2)
        x,self.attn = self_attention(quary,key,value,dropout=self.dropout,mask=mask)
        x = x.transpose(1,2).contiguous().view(n_batch,-1,self.head*self.d_k)
        return self.linear_out(x)

还有掩码自注意力需要添加,此时没有添加,等讲解到掩码的时候添加。
QKV实现分割并行计算之后,对x进行拼接重塑维度,做一个线性变换输出x。

位置编码

class PositionalEncoding(nn.Module):
    def __init__(self,dim,dropout,max_len=5000):
        super(PositionalEncoding,self).__init__()
        if dim%2 != 0:
            raise ValueError("Can't use sin/cos positional encoding with"
                             "odd dim (got dim={:d})".format(dim))
        '''
        维度必须是偶数,这个if就是如果维度是奇数的情况下跳出异常,
        只有维度是偶数的情况下才能都有对称性,确保每一个位置都有一个sin一个cos
        能够提供更完整的位置属性   
        '''
        pe = torch.zeros(max_len,dim)
        position = torch.arange(0,max_len).unsqueeze(1)
        div_term = torch.exp((torch.arange(0,dim,2,dtype=torch.float)*-(math.log(10000.0)/dim)))
        pe[:,1::2] = torch.sin(position.float() * div_term)
        pe[:,0::2] = torch.cos(position.float() * div_term)
        pe = pe.unsqueeze(1)
        self.register_buffer('pe',pe)
        # 创建pe的时候用的zeros使得pe是一个可学习的参数,但是位置编码是一直不变的,因此用这个函数使得pe不会改变,但会存储
        self.drop_out = nn.Dropout(p = dropout)
        self.dim = dim
    def forward(self,emb,step=None):
        if step == None:
            emb = emb + self.pe[:emb.size(0)]
        else:
            emb = emb + self.pe[:step]
        emb = self.drop_out(emb)
        return emb

FeedForward实现

class PositionWiseFeedForward(nn.Module):
    def __init__(self,d_model,d_ff,dropout=0.1) -> None:
        super(PositionWiseFeedForward,self).__init__()
        self.w_1 = nn.Linear(d_model,d_ff)
        self.w_2 = nn.Linear(d_ff,d_model)
        self.relu = nn.ReLU()
        self.layer_norm = nn.LayerNorm(d_model,eps=1e-6)
        self.dropout1 = nn.Dropout(p=dropout)
        self.dropout2 = nn.Dropout(p=dropout)
    def forward(self,x):
        inter = self.dropout1(self.relu(self.w_1(self.layer_norm(x))))
        output = self.dropout2(self.relu(self.w_2(inter)))
        return output

FFN非常简单,就是两次wx+b,加一个激活函数即可,代码里面初始w1,w2,reluw_1,w_2,reluw1​,w2​,relu等,为什么没有b呢,pytorch linear在初始化的时候已经帮助我们初始化好了不需要我们自己初始化。

EncoderDecoder层实现

def clones(module,n):
    return nn.ModuleList([deepcopy(module) for _ in range(n)])

class EncoderLayer(nn.Module):
    def __init__(self,size,attn,feed_forward,dropout=0.1):
        super(EncoderLayer,self).__init__()
        self.attn = attn
        self.feed_forward = feed_forward
        self.sublayer_connection_list = clones(SublayerConnection(size,dropout),2)
    def forward(self,x,mask):
        first_x = self.sublayer_connection_list[0](x,lambda x_attn:self.attn(x,x,x,mask))
        return self.sublayer_connection_list[1](x,self.feed_forward)
        
class Encoder(nn.Module):
    def __init__(self,n,encoder_layer):
        super(Encoder,self).__init__()
        self.encoder_layer_list = clones(encoder_layer,n)
    def forward(self,x,src_mask):
        for encoder_layer in self.encoder_layer_list:
            x = encoder_layer(x,src_mask)
        return x

class DecoderLayer(nn.model):
    def __init__(self,d_model,attn,feed_forward,sublayer_num,dropout=0.1):
        super(DecoderLayer,self).__init__()
        self.attn = attn
        self.feed_forward = feed_forward
        self.sublayer_connection_list = clones(SublayerConnection(d_model,dropout),sublayer_num)
    def forward(self,x,l2r_memory,src_mask,trg_mask,r2l_memory=None,r2l_trg_mask = None):
        first_x = self.sublayer_connection_list[0](x,lambda x_attn: self.attn(x,l2r_memory,l2r_memory,trg_mask))
        second_x = self.sublayer_connection_list[1](first_x,lambda sencond_x_attn:self.attn(first_x,l2r_memory,l2r_memory,src_mask))
        if r2l_memory is not None:
            third_x = self.sublayer_connection_list[-2](second_x,lambda third_x_attn:self.attn(second_x,r2l_memory,r2l_memory,r2l_trg_mask))
            return self.sublayer_connection_list[-1](third_x,self.feed_forward)
        else:
            return self.sublayer_connection_list[-1](second_x,self.feed_forward)


class Decoder(nn.Module):
    def __init__(self,n_layers,decoder_layer):
        super(Decoder,self).__init__()
        self.decoder_layer_list = clones(decoder_layer,n_layers)
    def forward(self,x,memory,src_mask,trg_mask):
        for decoder_layer in self.decoder_layer_list:
            x = decoder_layer(x,memory,src_mask,trg_mask)
        return x

首先实现一个用来复制的函数,因为不管是decoder还是encoder都有两个add和Normalize。
encoder和decoder都先实现一层,再用一个类来多次创建实现多层叠加。
encoderlayer就是一层encoder,就是实现多头+add和Normalize+ffn+add和Normalize,其中传入的参数attn是创建好的多头自注意力模型,ffn同理
decoderlayer就是一层decoder,同理是实现多头+add和Normalize+ffn+add和Normalize,只不过接受的参数不同,x是输入,memory是encoder层的输出,后面两个是掩码,最后两个参数不用管,是反向解码。

拼凑Transformer


class WordProbGenerator(nn.Module):
    def __init__(self,d_model,vocab_size):
        super(WordProbGenerator,self).__init__()
        self.linear = nn.Linear(d_model,vocab_size)
    def forward(self,x):
        return F.log_softmax(self.linear(x),dim=-1)

class WordEmbedding(nn.Module):
    def __init__(self,vocab_size,d_model) -> None:
        super(WordEmbedding,self).__init__()
        self.embedding = nn.Embedding(vocab_size,d_model)
        self.embed = self.embedding
        self.d_model = d_model
    def forward(self,x):
        return self.embed(x)*math.sqrt(self.d_model)


class ABDTransformer(nn.Module):
    def __init__(self,vocab,d_model,d_ff,n_head,n_layer,dropout,device='cuda'):
        super(ABDTransformer,self).__init__()
        self.vocab = vocab
        self.device = device
        attn = MultiHeadattention(n_head,d_model,dropout)
        feed_forward = PositionWiseFeedForward(d_model,d_ff,dropout)
        self.src_embed = WordEmbedding(vocab,d_model)
        self.pos_embed = PositionalEncoding(d_model,dropout)
        self.encoder = Encoder(n_layer,EncoderLayer(d_model,deepcopy(attn),deepcopy(feed_forward),dropout=dropout))
        self.decoder = Decoder(n_layer,DecoderLayer(d_model,deepcopy(attn),deepcopy(feed_forward),sublayer_num=3,dropout=dropout))
        self.word_prob_generator = WordProbGenerator(d_model,vocab)
    def encode(self,src,src_mask):
        x = self.src_embed(src[0])
        x = self.pos_embed(x)
        x = self.encoder(x,src_mask)
        return x
    def decode(self,trg,memory,src_mask,trg_mask):
        x = self.src_embed(trg)
        x = self.pos_embed(x)
        return self.decoder(x,memory,src_mask,trg_mask)
        
    def forward(self,src,trg,mask):
        src_mask,trg_mask = mask
        encoder_output = self.encode(src,src_mask)
        decoder_output = self.decode(trg,encoder_output,src_mask,trg_mask)
        pred = self.word_prob_generator(decoder_output)
        return pred


第一个函数是得到各个词的概率
第二个函数是将输入词向量的维度,就是字典的维度改成d_model的维度。
组建transformer
第一步的init中将模型都初始化,包括encoder,decoder,ffn,多头自注意力机制,位置编码等。
第二步写decode和encode的输入输出,简单来说我们已经实现了内部的操作,现在写两个函数,将他需要的输入进去即可。
第三步调用函数,最后得到概率输出。

Transformer的Pytorch实现【1】 使用Pytorch手把手搭建一个Transformer网络结构并完成一个小型翻译任务。首先,对Transformer结构进行拆解,Transformer由编码器和解码器(Encoder-Decoder)组成,编码器由Multi-Head Attention + Feed-Forward Network组成的结构堆叠而成,解码器由Multi-Head Attention + Multi-Head Attention + Feed-Forward Network组成的结构堆叠而成。 阅读详情

相关推荐

PyTorch实现Transformer模型

所有数学公式都要用$...$或者$$...$$,比如自注意力的计算公式$Attention(Q, K, V) = softmax(\frac{QK^T}{\sqrt{d_k}})V$,这里要检查是否正确使用括号和符号。接下来,用户需要的是手把手的代码解读,所以必须详细,每一步都不能遗漏。还要考虑用户可能遇到的常见问题,比如维度不匹配,如何处理mask,训练时的损失函数选择,优化器的设置等。需要确保代码示例正确,比如在实现多头注意力时,是否正确地分割了张量,是否计算了注意力分数,并应用了mask。

liuhaoran___的博客 1380

Transformer结构

Transformer学习

m0_52537264的博客 599

Pytorch中 nn.Transformer的使用详解与Transformer的黑盒讲解

1. Transformer的训练过程讲解 2. Transformer的推理过程讲解 3. Transformer的入参和出参讲解 4. nn.Transformer的各个参数讲解 5. nn.Transformer的mask机制详解 6. 实战:使用nn.Transformer训练一个copy任务。

iioSnail的博客 9万+

Transformer详解:基于self-attention的大杀器

Transformer 话不多说,先上图,让大家对Transformer的结构有一个直观的认识,方便大家在看我后续的讲解中会更容易理解。 好,我们开始,先从encoder side开始。 Encoder Side 1.Self-Attention 我们已经知道在处理sequence数据时,我们最常用到的模型就是RNN,但是RNN有个非常大的问题,就是–Hard to parallel! 什么意思呢?也就是是说,我们使用RNN输出某个位置的ouput时,必须要make use of之前所有位置的输入,因此模

weixin_44607838的博客 1246

Intouch间接变量(扩展)

间接变量只是Intouch提供给开发者的便捷方式之一,并不是所有情况都一定要使用间接变量,有时候用条件语句或者内存变量的方式也能起到类似的作用。

weixin_41571357的博客 2178

搞定汽车座椅电机EMC超标:一个PCB滤波板的实战设计与避坑心得

本文详细介绍了汽车座椅电机EMC超标问题的解决方案,通过PCB滤波板的实战设计,解决了传导发射测试超标问题。文章分享了在空间受限条件下的滤波电路架构设计、接地系统优化及迭代验证过程,为汽车直流电机的EMC整改提供了实用方法论。

weixin_30336061的博客 383

读懂 transformer

Transformer是一种用于自然语言处理(NLP)和其他序列到序列(sequence-to-sequence)任务的深度学习模型架构,它在2017年由Vaswani等人首次提出。Transformer架构引入了自注意力机制(self-attention mechanism),这是一个关键的创新,使其在处理序列数据时表现出色。

wangziling123456的博客 1224

【ESP32 S3 开发】基于I2S协议驱动INMP441数字麦克风 实现语音采集

注意INMP441的 L/R接地之后才稳定输出数据 否则一直都是0WAV格式说明这里主要是想说wav文件重要的就是生成一个wavhead来标识它是一个wave文件,wave文件的data chunk 中的data部分还是PCM编码格式的数据,直接从I2S读进去就可以,不需要压缩。wav文件的头一般由4个chunk组成。 以16bit深度为例,代码如下。其他深度可以根据注释自行计算。 I2S -> DAC i2s_read()函数,向flash中划分的一个buff当中读入byte数组。以16bit深度为例,一

m0_43395703的博客 1万+

【NLP】手把手使用PyTorch实现Transformer以及Transformer-XL

Google 2017年的论文 Attention is all you need 提出了Transformer模型,完全基于Attention mechanism,抛弃了传统的RNN和CNN。本文根据论文的结构图,手把手带你使用 PyTorch 实现这个Transformer模型以及Transformer-XL模型。

小哲的博客 8331

提供一个微信投票刷票的js代码

最近几天,有个朋友找我去写一个脚本帮他 在微信上刷票、微信投票刷票,我大概看了一下,本次微信投票刷票其实就是根据微信的openid来限制,每个openid只能投三次票的限制。上图可以看出,其实只要openid,和toopenid即可,openid是自己的微信id,toopenid是投票对象的微信id,那我们定时修改openid即可给某一个人刷投票。把这段代码复制到浏览器F12之后的console里,直接回车即可开始微信投票刷票(刷新或关闭浏览器即可停止刷票)//生成随机的ip地址。

qq_858865388专业提供快速微信投票教程攻略和方法的博客 2万+

ARFoundation系列讲解-教程目录

一、教程目录 ARFoundation快速入门-01简介 ARFoundation快速入门-02环境搭建 ARFoundation快速入门-03环境配置之iOS ARFoundation快速入门-04环境配置之Android ARFoundation快速入门-05ARKit设备支持列表 ARFoundation快速入门-06ARCore设备支持列表 ARFoundation快速入门-07检查设备支持 ARFoundation快速入门-08平面检..........

a451319296的博客 3万+

Transformer的PyTorch实现

本文由罗周杨原创,转载请注明作者和出处。未经授权,不得用于商业用途 Google 2017年的论文 Attention is all you need 阐释了什么叫做大道至简!该论文提出了Transformer模型,完全基于Attention mechanism,抛弃了传统的RNN和CNN。 我们根据论文的结构图,一步一步使用 PyTorch 实现这个Transformer模型。 Transf...

stupid_3的博客 4万+

ABAP Cloud:面向云时代的 ABAP 开发范式与实践指南

摘要: 本文系统讲解SAP ABAP Cloud开发模型,涵盖其架构、工具链、规范及实践。ABAP Cloud作为统一开发模型,支持在SAP BTP和S/4HANA上构建云就绪应用,遵循clean core原则,通过RAP(RESTful应用编程模型)实现低耦合扩展。文章详细解析其核心构成(RAP、稳定API、clean core约束)、工具链(ADT、软件物流)及两种典型扩展场景(on-stack与side-by-side),并附可运行RAP示例代码(如销售笔记应用)。重点强调通过规范开发确保系统可升级性

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 424

Transformer 模型的 PyTorch 实现

Google 2017年的论文阐释了什么叫做大道至简!该论文提出了模型,完全基于,抛弃了传统的和。我们根据论文的结构图,一步一步使用实现这个模型。

weixin_42907150的博客 1157

管理类联考——逻辑——真题篇——按知识分类——综合推理

29、某部门抽检了肉制品、白酒、乳制品、干果、蔬菜、水产品、饮料等﹖类商品共521种样品,发现其中合格样品515种,不合格样品6种。已知: (1)蔬菜、白酒中有2种不合格样品。 (2)肉制品、白酒、蔬菜、水产品中有5种不合格样品。 (3)蔬菜、乳制品、干果中有3种不合格样品。 根据上述信息,可以得出以下哪项? A. 乳制品中没有不合格样品。 B. 肉制品中没有不合格样品。 C. 蔬菜中没有不合格样品。 D. 白酒中没有不合格样品。 E. 水产品中没有不合格样品。 31~32题基于以下题干: 某中学举行田径运

stqer的博客 2039

SMPLify-x-master | 复现记录

由于毕业设计中将会用到smpl模型,而smplify方法的各环境依赖版本比较老,复现不太容易,因此便进行了smplifyx方法使用smplx的方法。由于在过程中遇到较多坑,因此进行记录和分享。

qq_44916003的博客 5110

pytorch实现transformer

pytorch实现transfomer,详细。小白入门向。

m0_61688615的博客 4555

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

使用PyTorch从头实现Transformer

使用PyTorch从头实现Transformer

qq_20144897的博客 2335

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Transformer的Pytorch实现

使用Pytorch编程实现Transformer并进行训练和预测

ing100的博客 3170

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

Transformer模型的Pytorch实现

Transformer模型的Pytorch实现解读。

牧羊女 2682

Transformer的PyTorch实现(超详细)

文本主要介绍一下如何使用 PyTorch 复现 Transformer,实现简单的机器翻译任务。请先花上 15 分钟阅读我的这篇文章 Transformer详解,再来看文本,方能达到醍醐灌顶,事半功倍的效果 数据预处理 这里我并没有用什么大型的数据集,而是手动输入了两对德语→英语的句子,还有每个字的索引也是我手动硬编码上去的,主要是为了降低代码阅读难度,我希望读者能更关注模型实现的部分 # S: Symbol that shows starting of decoding input # E: Symbol

mathor的博客 6万+

Transformer详解及Pytorch实现

Attention Is All You Need——“目前主要的序列转导模型基于编码器-解码器中配置的复杂循环神经网络或卷积神经网络。但通过注意力机制连接编码器和解码器可以大幅改善模型性能。我们提出了一种新的简单网络架构,它叫 Transformer,它完全基于注意力机制,完全省去了循环和卷积。”(Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., … & Polosukhin, I. (2017).

weixin_45414514的博客 1246

Transformer的pytorch实现

Transformer架构 Transformer模型由encoder和decoder两部分组成,decoder输出的结果,经过一个线性层,然后计算softmax。 d_model = 512 # Embedding Size d_ff = 2048 # FeedForward dimension d_k = d_v = 64 # dimension of K(=Q), V n_layers...

lbw522的博客 2500

PyTorch从零开始实现Transformer

使用Pytorch实现Attention is all you need

阿正的梦工坊 4万+

Transformer的PyTorch实现 视频讲解

Transformer的PyTorch实现

m0_37347812的博客 216
上一篇: Transformer理论阶段
下一篇: GPT和BERT
我.佛.糍.粑
博客等级 码龄3年 201粉丝 36原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址