原因:
在网络本身有随机变量的情况下,随机变量很可能是在定义网络时按照预设的batchSzie确定的维度。这样,如果总的训练集的Size不能被batchSize整除,就会出现网络输入数据的Size和生成的随机变量的size在Batchsize那个维度上不匹配的问题,从而报错。
解决:
调整BatchSize使其能够整除Size;
或
调整数据集大小使其能够被BatchSize整除。
或
检查输入数据的batchsize,当它和预设的batchsize不匹配时强行补齐;
总结
之前一直以为在使用dataLoader的时候不会出现这种问题,而且也没有跑过额外产生随机变量的网络。今天首次遇到这个问题。在训练有自生成随机变量的网络时要特别注意该问题。
===============2020年10月16日 21:23:23更新==============================================
上述问题应该(没有去试但根据文档应该没问题)可以通过设置dataloader的drop_last 参数去解决,这才应该是标准解法。
drop_last (bool, optional) – set to True
to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If False
and the size of dataset is not divisible by the batch size, then the last batch will be smaller. (default: False)
参考:https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader