训练一个模型之前首先要准备就是数据和预训练模型,通常作者都会提供预训练模型,即一些模型的原始参数,训练数据可以先用官方提供的数据先跑通。
用官方数据跑代码时通常会遇到的错误:
1、Module Error:某个代码包未下载完全,这时直接打开终端输入:
解决方法:
pip install numpy -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
numpy替换成缺失的包就可以
2、FileNotFoundError: [Errno 2] No such file or directory:路径问题
解决方法:出现这种问题首先要去该路径下查看是否存在这个文件,或者是路径字母打错;其次路径是中文的要注意,图片名存在中文和其他符号的,最好用cv.imdecode函数读取
cv_img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)
除此之外在参数设置上要注意,用自己电脑跑的话,batch_size要设的小一点,还有num_work=0
3、OSError: [WinError 1455] 页面文件太小,无法完成操作。
解决方法:先检查代码的num_work是否等于0;解决不了再调大页面文件的大小 + 更改一下batch_size
想用别的数据训练模型就一定要注意了,对于新手来说,出错会像海浪一样,一波又一波朝你涌来。
1、RuntimeError: CUDA out of memory. Tried to allocate 38.00 MiB
GPU运行错误,显存不够用,最直接的解决方式就是减少batch_size;
或者终端运行torch.cuda.empty_cache(),清理缓存
2、ValueError: too many values to unpack (expected 2)
通常是for循环语句出错,中文意思:太多值需要解包(目标值为2)
例如,报错原句为:
for batch_idx, (data, target) in enumerate(train_loader):
改为:
for batch_idx, sampled_batch in enumerate(train_loader):
以及下面这种改法(在遍历时加上字典):
原句:
for a,b in dict:
改为:
for a,b in dict.items():
3、RuntimeError: Sizes of tensors must match except in dimension 2. Got 448 and 352 (The offending index is 0)
数据不匹配问题,原语句为
4、IndexError: list index out of range
对Python中有序序列进行按索引取值的时候,对于有序序列,总体范围为 -len(有序序列) ~ len(有序序列)-1,如果输入的取值结果不在这个范围内,则报这个错。
解决方法:检查索引是否在 -len(有序序列) ~ len(有序序列)-1 范围内,修改正确
5、TypeError: Got inappropriate interpolation arg
数据插值错误,把函数中interpolation参数调整一下,interpolation是对图像进行插值,了解其不同模式对读取数据的作用,或者删去这个参数(通常会报错)
6、TypeError: Input image tensor should 3 channels, but found 4
RuntimeError: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0
类型错误:输入图像张量应该有3个通道,但找到了4个
解决方法:数据格式不对, 把image转成tensor,参数transform进行如下设置就可以了:transform=transform.ToTensor()。注意检测一下transform
或者使用函数torch.from_numpy(x),x的type将会从
7、TypeError: Input image tensor should 3 channels, but found 4
类型错误:输入图形张量应该是3维,而不是4维
可能遇到的问题:数据是png图像的时候,如果用PIL读取图像,获得的是单通道的,不是多通道的。
可以采用expand()函数将3维数据拓展到4维(只能在0维拓展)
例如:a–【1,2,3】,b = a.expand(2,1,2,3) ,b.shape=(2,1,2,3)
8、ValueError: test_size=0 should be either positive and smaller than the number of samples 0 or a float in the (0, 1) range
读取数据时pytorch报错
解决方法:test的数据读取错误,查看读取数据代码,跟上面错误通常扎推出现