赞
踩
利用Pytorch框架实现用transformer通过输入sine预测cos,代码如下:
import math import torch from torch import nn class PositionalEncoding(nn.Module): def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): x = x + self.pe[:x.size(1), :].squeeze(1) return self.dropout(x) class TransformerTS(nn.Module): def __init__(self, input_dim, dec_seq_len, out_seq_len, d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。