1

更新:回顾这个问题后,大部分代码都是不必要的。长话短说,Pytorch RNN 的隐藏层需要是一个火炬张量。当我发布问题时,隐藏层是一个元组。

下面是我的数据加载器。

from torch.utils.data import TensorDataset, DataLoader

def batch_data(log_returns, sequence_length, batch_size):
    """
    Batch the neural network data using DataLoader
    :param log_returns: asset's daily log returns
    :param sequence_length: The sequence length of each batch
    :param batch_size: The size of each batch; the number of sequences in a batch
    :return: DataLoader with batched data
    """
    
    # total number of batches we can make
    n_batches = len(log_returns)//batch_size
    
    # Keep only enough characters to make full batches
    log_returns = log_returns[:n_batches * batch_size]
    
    y_len = len(log_returns) - sequence_length
    
    x, y = [], []
    for idx in range(0, y_len):
        idx_end = sequence_length + idx
        x_batch = log_returns[idx:idx_end]
        x.append(x_batch)
        # only making predictions after the last word in the batch
        batch_y = log_returns[idx_end]    
        y.append(batch_y)    
    
    # create tensor datasets
    x_tensor = torch.from_numpy(np.asarray(x))
    y_tensor = torch.from_numpy(np.asarray(y))
    
    # make x_tensor 3-d instead of 2-d
    x_tensor = x_tensor.unsqueeze(-1)
    
    data = TensorDataset(x_tensor, y_tensor)
    
    data_loader = DataLoader(data, shuffle=False, batch_size=batch_size)
    
    # return a dataloader
    return data_loader
    def init_hidden(self, batch_size):
        ''' Initializes hidden state '''
        # Create two new tensors with sizes n_layers x batch_size x n_hidden,
        # initialized to zero, for hidden state and cell state of LSTM
        weight = next(self.parameters()).data
        
        if (train_on_gpu):
            hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda(),
                      weight.new(self.n_layers, batch_size, self.n_hidden).zero_().cuda())
        else:
            hidden = (weight.new(self.n_layers, batch_size, self.n_hidden).zero_(),
                      weight.new(self.n_layers, batch_size, self.n_hidden).zero_())
        
        return hidden

我不知道出了什么问题。当我尝试开始训练模型时,我收到错误消息:

AttributeError: 'tuple' object has no attribute 'size'
4

2 回答 2

4

问题来自于hidden(在forward定义中)不是Torch.Tensor. 因此,r_output, hidden = self.gru(nn_input, hidden)引发了一个相当混乱的错误,而没有明确说明参数中有什么问题。尽管你可以看到它是在一个nn.RNN名为check_hidden_size()...

起初我很困惑,认为 : 的第二个参数nn.RNNh0一个包含(hidden_state, cell_state). 该调用返回的第二个元素也是如此:hn. 事实并非如此h0hn两者都是Torch.Tensors。不过有趣的是,您可以解压缩堆叠的张量:

>>> z = torch.stack([torch.Tensor([1,2,3]), torch.Tensor([4,5,6])])
>>> a, b = z
>>> a, b
(tensor([1., 2., 3.]), tensor([4., 5., 6.]))

您应该提供一个张量作为 a 的第二个参数。nn.GRU __call__


编辑- 在进一步检查您的代码后,我发现您hidden再次转换回元组......在单元格 [14] 中,您有hidden = tuple([each.data for each in hidden]). 这基本上会覆盖您init_hidden使用torch.stack.

退后一步,查看RNNBase 的源代码,这是 RNN 模块的基类。如果隐藏状态没有给予转发,它将默认为:

if hx is None:
    num_directions = 2 if self.bidirectional else 1
    hx = torch.zeros(self.num_layers * num_directions,
                     max_batch_size, self.hidden_size,
                     dtype=input.dtype, device=input.device)

这本质上与您尝试实现的 init 完全相同。当然,您只想在每个时代重置隐藏状态,(我不明白为什么......)。无论如何,一个基本的替代方法是在一个纪元开始时设置hidden为,然后None按原样传递self.forward_back_proprnn,然后self.rnn默认为你初始化它。hidden然后用该 RNN 前向调用返回的隐藏状态覆盖。

总而言之,我只保留了代码的相关部分。从中删除该init_hidden功能AssetGRU并进行这些修改:

def forward_back_prop(rnn, optimizer, criterion, inp, target, hidden):
    ...
    if hidden is not None:
        hidden = hidden.detach()
    ...
    output, hidden = rnn(inp, hidden)  
    ...
    return loss.item(), hidden


def train_rnn(rnn, batch_size, optimizer, criterion, n_epochs, show_every_n_batches):
    ...
    for epoch_i in range(1, n_epochs + 1):
        
        hidden = None
        
        for batch_i, (inputs, labels) in enumerate(train_loader, 1):
            loss, hidden = forward_back_prop(rnn, optimizer, criterion, 
                                             inputs, labels, hidden)
            ...

    ...
于 2021-01-03T16:17:45.637 回答
0

在 0 附近应该有 [] 括号而不是 ()。

def forward(self, nn_input, hidden):
    ''' Forward pass through the network. 
        These inputs are x, and the hidden/cell state `hidden`. '''
    
    # batch_size equals the input's first dimension
    batch_size = nn_input.size(0)
于 2021-01-02T20:05:22.433 回答