ValueError:expected sequence of length 10 at dim 1 (got 1)

错误现象:

数据预处理创建mini batch时,因为以下代码导致出错:ValueError:expected sequence of length 10 at dim 1 (got 1)

    inout_seq.append((train_seq, train_label))
    return torch.FloatTensor(inout_seq)

原因分析:

train_seq和 train_label 长度一不一样,一个有10个元素,另一个只有一个。

解决方案:

修改好的办法是, 在划分trainset, testset的时候, 就把数据转换成torch的tensor:

    train_data = df[:samples]   
    test_data = df[samples:]
    
    train_data = torch.FloatTensor(train_data).to(device)
    test_data = torch.FloatTensor(test_data).to(device)

这样就可以直接

return inout_seq

顺利解决error

附:

x = [[1,2,3,4], [2]]
x = torch.FloatTensor(x)
print(x)

输出ValueError: expected sequence of length 4 at dim 1 (got 1)

改为:

x = [[1,2,3,4], [2,3,4,5]]
x = torch.FloatTensor(x)
print(x)

就可以正常输出:

tensor([[1., 2., 3., 4.],
        [2., 3., 4., 5.]])

总结:

内部机制要求两个列表维度一样。

是否有自动补全不确定,没有深入研究。

猜你喜欢

转载自blog.csdn.net/l641208111/article/details/129820042