本专栏为深度学习的一些技巧,方法和实验测试,偏向于实际应用,后续不断更新,感兴趣童鞋可关,方便后续推送
现象
在训练深度学习模型时,保错如下:
line 2404, in _verify_batch_size
raise ValueError("Expected more than 1 value per channel when training, got input size {}".format(size))
分析
网上一般解释为batch中恰好只含一个sample
显然这个解释不合理:
- 有过模型训练经验的人,都知道batch_size为1的bn层肯定是可以训练,不然这个设计也太愚蠢了
- 报错明明说的是每一个通道要求超过1个值
关于bn的简介可以参考我的另外一篇
接下来,我来查一下问题根源.通过PYCharm的Debug可以定位到
def _verify_batch_size(size: List[int]) -> None:
# XXX: JIT script does not support the reduce from functools, and mul op is a
# builtin, which cannot be used as a value to a func yet, so rewrite this size
# check to a simple equivalent for loop
#
# TODO: make use of reduce like below when JIT is ready with the missing features:
# from operator import mul
# from functools import reduce
#
# if reduce(mul, size[2:], size[0]) == 1
size_prods = size[0]
for i in range(len(size) - 2):
size_prods *= size[i + 2]
if size_prods == 1:
raise ValueError("Expected more than 1 value per channel when training, got input size {}".format(size))
上面的size是Size([1, xxx, 1, 1])
当size=Size([1, xxx]), size_prods是size[0]
当size=Size([1, xxx, 1, 1]), size_prods是size[0] * size[2] * size[3]
因此,为了避免这个错误,我们把batch_size改成大于1就可以,这就是为什么网上通用解释都是这个.
但是显然,我调整输入尺寸或者网络结构使得 size[2]和size[3]不为1也是可以的.
解决方法
1.优先建议,调整输入尺寸或者网络结构使得 size[2]和size[3]不为1
2.方法1如果不能用,则batch_size改成大于1