RNN-运行错误:输入必须有3个维度,得到2

发布时间:2022-08-23 / 作者:清心寡欲
本文介绍了RNN-运行错误:输入必须有3个维度,得到2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

运行错误:输入必须有3个维度,得到%2

我有一个功能栏,我正尝试将其输入GRU神经网络。

下面是我的数据加载器和神经网络。在检索一批数据时,我还包含了数据加载器的输出。

我做错了什么?

def batch_data(feature1, sequence_length, batch_size):
"""
Batch the neural network data using Dataloader
:param feature1: the single feature column
: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(feature1)//batch_size

    # Keep only enough characters to make full batches
    feature1= feature1[:n_batches * batch_size]

    y_len = len(feature1) - sequence_length

    x, y = [], []
    for idx in range(0, y_len):
        idx_end = sequence_length + idx
        x_batch = feature1[idx:idx_end]
        x.append(x_batch)
        # only making predictions after the last item in the batch
        batch_y = feature1[idx_end]    
        y.append(batch_y)    

    # create tensor datasets
    data = TensorDataset(torch.from_numpy(np.asarray(x)), torch.from_numpy(np.asarray(y)))

    data_loader = DataLoader(data, shuffle=False, batch_size=batch_size)

    # return a dataloader
    return data_loader



# test dataloader on subset of actual data

test_text = data_subset_b
t_loader = batch_data(test_text, sequence_length=5, batch_size=10)
 
data_iter = iter(t_loader)
sample_x, sample_y = data_iter.next()
 
print(sample_x.shape)
print(sample_x)
print()
print(sample_y.shape)
print(sample_y)
当我传入数据时,将生成以下批处理…
torch.Size([10, 5])
tensor([[ 0.0045, 0.0040, -0.0008, 0.0005, -0.0012],
[ 0.0040, -0.0008, 0.0005, -0.0012, 0.0000],
[-0.0008, 0.0005, -0.0012, 0.0000, -0.0015],
[ 0.0005, -0.0012, 0.0000, -0.0015, 0.0008],
[-0.0012, 0.0000, -0.0015, 0.0008, 0.0000],
[ 0.0000, -0.0015, 0.0008, 0.0000, 0.0000],
[-0.0015, 0.0008, 0.0000, 0.0000, -0.0008],
[ 0.0008, 0.0000, 0.0000, -0.0008, -0.0039],
[ 0.0000, 0.0000, -0.0008, -0.0039, -0.0026],
[ 0.0000, -0.0008, -0.0039, -0.0026, -0.0082]], dtype=torch.float64)

torch.Size([10])
tensor([ 0.0000, -0.0015, 0.0008, 0.0000, 0.0000, -0.0008, -0.0039, -0.0026,
-0.0082, 0.0078], dtype=torch.float64)

推荐答案

如您收到的错误所示,GRU期望的输入张量形状是三维的,形状(batch_size, seq_len, input_size)1

但您正在提供形状的张量(10,5)。您说您的输入有一个要素值,所以您应该为大小为1的INPUT_SIZE添加一个维度。可以这样做

sample_x.unsqueeze(-1)

这篇关于RNN-运行错误:输入必须有3个维度,得到2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!



[英文标题]RNN - RuntimeError: input must have 3 dimensions, got 2


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。