深度學(xué)習(xí)/計算機視覺常見的8個錯誤總結(jié)及避坑指南
本文轉(zhuǎn)自雷鋒網(wǎng),如需轉(zhuǎn)載請至雷鋒網(wǎng)官網(wǎng)申請授權(quán)。
人類并不是完美的,我們經(jīng)常在編寫軟件的時候犯錯誤。有時這些錯誤很容易找到:你的代碼根本不工作,你的應(yīng)用程序會崩潰。但有些 bug 是隱藏的,很難發(fā)現(xiàn),這使它們更加危險。
在處理深度學(xué)習(xí)問題時,由于某些不確定性,很容易產(chǎn)生此類錯誤:很容易看到 web 應(yīng)用的端點路由請求是否正確,但卻不容易檢查梯度下降步驟是否正確。然而,在深度學(xué)習(xí)實踐例程中有很多 bug 是可以避免的。
我想和大家分享一下我在過去兩年的計算機視覺工作中所發(fā)現(xiàn)或產(chǎn)生的錯誤的一些經(jīng)驗。我在會議上談到過這個話題,很多人在會后告訴我:「是的,老兄,我也有很多這樣的 bug?!刮蚁M业奈恼履軒椭惚苊馄渲械囊恍﹩栴}。
1.翻轉(zhuǎn)圖像和關(guān)鍵點
假設(shè)有人在研究關(guān)鍵點檢測問題。它們的數(shù)據(jù)看起來像一對圖像和一系列關(guān)鍵點元組,例如 [(0,1),(2,2)],其中每個關(guān)鍵點是一對 x 和 y 坐標(biāo)。
讓我們對這些數(shù)據(jù)編進行基本的增強:
- def flip_img_and_keypoints(img: np.ndarray, kpts:
- Sequence[Sequence[int]]):
- img = np.fliplr(img)
- h, w, *_ = img.shape
- kpts = [(y, w - x) for y, x in kpts]
- return img, kpts
上面的代碼看起來很對,是不是?接下來,讓我們對它進行可視化。
- image = np.ones((10, 10), dtype=np.float32)
- kpts = [(0, 1), (2, 2)]
- image_flipped, kpts_flipped = flip_img_and_keypoints(image, kpts)
- img1 = image.copy()
- for y, x in kpts:
- img1[y, x] = 0
- img2 = image_flipped.copy()
- for y, x in kpts_flipped:
- img2[y, x] = 0
- _ = plt.imshow(np.hstack((img1, img2)))
這個圖是不對稱的,看起來很奇怪!如果我們檢查極值呢?
- image = np.ones((10, 10), dtype=np.float32)
- kpts = [(0, 0), (1, 1)]
- image_flipped, kpts_flipped = flip_img_and_keypoints(image, kpts)
- img1 = image.copy()
- for y, x in kpts:
- img1[y, x] = 0
- img2 = image_flipped.copy()
- for y, x in kpts_flipped:
- img2[y, x] = 0
- -------------------------------------------------------------------- -------
- IndexError
- Traceback (most recent call last)
- <ipython-input-5-997162463eae> in <module>
- 8 img2 = image_flipped.copy()
- 9 for y, x in kpts_flipped:
- ---> 10 img2[y, x] = 0
- IndexError: index 10 is out of bounds for axis 1 with size 10
不好!這是一個典型的錯誤。正確的代碼如下:
- def flip_img_and_keypoints(img: np.ndarray, kpts: Sequence[Sequence[int]]):
- img = np.fliplr(img)
- h, w, *_ = img.shape
- kpts = [(y, w - x - 1) for y, x in kpts]
- return img, kpts
我們已經(jīng)通過可視化檢測到這個問題,但是,使用 x=0 點的單元測試也會有幫助。一個有趣的事實是:我們團隊三個人(包括我自己)各自獨立地犯了幾乎相同的錯誤。
2.繼續(xù)談?wù)勱P(guān)鍵點
即使上述函數(shù)已修復(fù),也存在危險。接下來更多的是關(guān)于語義,而不僅僅是一段代碼。
假設(shè)一個人需要用兩只手掌來增強圖像??雌饋砗馨踩?mdash;—手在左右翻轉(zhuǎn)后會還是手。
但是等等!我們對關(guān)鍵點語義一無所知。如果關(guān)鍵點真的是這樣的意思呢:
- kpts = [
- (20, 20), # left pinky
- (20, 200), # right pinky
- ...
- ]
這意味著增強實際上改變了語義:left 變?yōu)?right,right 變?yōu)?left,但是我們不交換數(shù)組中的 keypoints 索引。它會給訓(xùn)練帶來巨大的噪音和更糟糕的指標(biāo)。
這里應(yīng)該吸取教訓(xùn):
-
在應(yīng)用增強或其他特性之前,了解并考慮數(shù)據(jù)結(jié)構(gòu)和語義;
-
保持你的實驗的獨立性:添加一個小的變化(例如,一個新的轉(zhuǎn)換),檢查它是如何進行的,如果分?jǐn)?shù)提高了再合并。
3.自定義損失函數(shù)
熟悉語義分割問題的人可能知道 IoU (intersection over union)度量。不幸的是,我們不能直接用 SGD 來優(yōu)化它,所以一個常見的技巧是用可微損失函數(shù)來逼近它。讓我們編寫相關(guān)代碼!
- def iou_continuous_loss(y_pred, y_true):
- eps = 1e-6
- def _sum(x):
- return x.sum(-1).sum(-1)
- numerator = (_sum(y_true * y_pred) + eps)
- denominator = (_sum(y_true ** 2) + _sum(y_pred ** 2) -
- _sum(y_true * y_pred) + eps)
- return (numerator / denominator).mean()
看起來很不錯,讓我們做一個小小的檢查:
- In [3]: ones = np.ones((1, 3, 10, 10))
- ...: x1 = iou_continuous_loss(ones * 0.01, ones)
- ...: x2 = iou_continuous_loss(ones * 0.99, ones)
- In [4]: x1, x2
- Out[4]: (0.010099999897990103, 0.9998990001020204)
在 x1 中,我們計算了與標(biāo)準(zhǔn)答案完全不同的損失,x2 是非常接近標(biāo)準(zhǔn)答案的函數(shù)的結(jié)果。我們預(yù)計 x1 會很大,因為預(yù)測結(jié)果并不好,x2 應(yīng)該接近于零。這其中發(fā)生了什么?
上面的函數(shù)是度量的一個很好的近似。度量不是損失:它通常越高越好。因為我們要用 SGD 把損失降到最低,我們真的應(yīng)該采用用相反的方法:
- v> def iou_continuous(y_pred, y_true):
- eps = 1e-6
- def _sum(x):
- return x.sum(-1).sum(-1)
- numerator = (_sum(y_true * y_pred) + eps)
- denominator = (_sum(y_true ** 2) + _sum(y_pred ** 2)
- - _sum(y_true * y_pred) + eps)
- return (numerator / denominator).mean()
- def iou_continuous_loss(y_pred, y_true):
- return 1 - iou_continuous(y_pred, y_true)
這些問題可以通過兩種方式確定:
-
編寫一個單元測試來檢查損失的方向:形式化地表示一個期望,即更接近實際的東西應(yīng)該輸出更低的損失;
-
做一個全面的檢查,嘗試過擬合你的模型的 batch。
4.使用 Pytorch
假設(shè)一個人有一個預(yù)先訓(xùn)練好的模型,并且是一個時序模型。我們基于 ceevee api 編寫預(yù)測類。
- from ceevee.base import AbstractPredictor
- class MySuperPredictor(AbstractPredictor):
- def __init__(self, weights_path: str, ):
- super().__init__()
- self.model = self._load_model(weights_path=weights_path)
- def process(self, x, *kw):
- with torch.no_grad():
- res = self.model(x)
- return res
- @staticmethod
- def _load_model(weights_path):
- model = ModelClass()
- weights = torch.load(weights_path, map_location='cpu')
- model.load_state_dict(weights)
- return model
這個密碼正確嗎?也許吧!對某些模型來說確實是正確的。例如,當(dāng)模型沒有規(guī)范層時,例如 torch.nn.BatchNorm2d;或者當(dāng)模型需要為每個圖像使用實際的 norm 統(tǒng)計信息時(例如,許多基于 pix2pix 的架構(gòu)需要它)。
但是對于大多數(shù)計算機視覺應(yīng)用程序來說,代碼遺漏了一些重要的東西:切換到評估模式。
如果試圖將動態(tài) pytorch 圖轉(zhuǎn)換為靜態(tài) pytorch 圖,則很容易識別此問題。有一個 torch.jit 模塊是用于這種轉(zhuǎn)換的。
一個簡單的修復(fù):
- In [4]: model = nn.Sequential(
- ...: nn.Linear(10, 10),
- ..: nn.Dropout(.5)
- ...: )
- ...:
- ...: traced_model = torch.jit.trace(model.eval(), torch.rand(10))
- # No more warnings!
此時,torch.jit.trace 多次運行模型并比較結(jié)果。這里看起來似乎沒有區(qū)別。
然而,這里的 torch.jit.trace 不是萬能的。這是一種應(yīng)該知道并記住的細(xì)微差別。
5.復(fù)制粘貼問題
很多東西都是成對存在的:訓(xùn)練和驗證、寬度和高度、緯度和經(jīng)度……如果仔細(xì)閱讀,你可以很容易地發(fā)現(xiàn)由一對成員之間的復(fù)制粘貼引起的錯誤:
- v> def make_dataloaders(train_cfg, val_cfg, batch_size):
- train = Dataset.from_config(train_cfg)
- val = Dataset.from_config(val_cfg)
- shared_params = {'batch_size': batch_size, 'shuffle': True,
- 'num_workers': cpu_count()}
- train = DataLoader(train, **shared_params)
- val = DataLoader(train, **shared_params)
- return train, val
不僅僅是我犯了愚蠢的錯誤。在流行庫中也有類似的錯誤。
- #
- https://github.com/albu/albumentations/blob/0.3.0/albumentations/aug mentations/transforms.py
- def apply_to_keypoint(self, keypoint, crop_height=0, crop_width=0, h_start=0, w_start= 0, rows=0, cols=0, **params):
- keypoint = F.keypoint_random_crop(keypoint, crop_height, crop_width, h_start, w_start, rows, cols)
- scale_x = self.width / crop_height
- scale_y = self.height / crop_height
- keypoint = F.keypoint_scale(keypoint, scale_x, scale_y) return keypoint
別擔(dān)心,這個錯誤已經(jīng)修復(fù)了。如何避免?不要復(fù)制粘貼代碼,盡量以不要以復(fù)制粘貼的方式進行編碼。
- datasets = []
- data_a = get_dataset(MyDataset(config['dataset_a']), config['shared_param'], param_a) datasets.append(data_a)
- data_b = get_dataset(MyDataset(config['dataset_b']), config['shared_param'], param_b) datasets.append(data_b)
- datasets = []
- for name, param in zip(('dataset_a', 'dataset_b'), (param_a, param_b), ):
- datasets.append(get_dataset(MyDataset(config[name]), config['shared_param'], param))
6.合適的數(shù)據(jù)類型
讓我們再做一個增強:
- def add_noise(img: np.ndarray) -> np.ndarray:
- mask = np.random.rand(*img.shape) + .5
- img = img.astype('float32') * mask
- return img.astype('uint8')
圖像已經(jīng)改變了。這是我們期望的嗎?嗯,也許改變太多了。
這里有一個危險的操作:將 float32 轉(zhuǎn)到 uint8。這可能導(dǎo)致溢出:
- def add_noise(img: np.ndarray) -> np.ndarray:
- mask = np.random.rand(*img.shape) + .5
- img = img.astype('float32') * mask
- return np.clip(img, 0, 255).astype('uint8')
- img = add_noise(cv2.imread('two_hands.jpg')[:, :, ::-1]) _ = plt.imshow(img)
看起來好多了,是吧?
順便說一句,還有一個方法可以避免這個問題:不要重新發(fā)明輪子,可以在前人的基礎(chǔ)上,修改代碼。例如:albumentations.augmentations.transforms.GaussNoise 。
我又產(chǎn)生了同樣來源的 bug。
這里出了什么問題?首先,使用三次插值調(diào)整 mask 的大小是個壞主意。將 float32 轉(zhuǎn)換為 uint8 也存在同樣的問題:三次插值可以輸出大于輸入的值,并導(dǎo)致溢出。
我發(fā)現(xiàn)了這個問題。在你的循環(huán)里面有斷言也是一個好主意。
7.打字錯誤
假設(shè)需要對全卷積網(wǎng)絡(luò)(如語義分割問題)和一幅巨大的圖像進行處理。圖像太大了,你沒有機會把它放進你的 gpu 中——例如,它可以是一個醫(yī)學(xué)或衛(wèi)星圖像。
在這種情況下,可以將圖像分割成一個網(wǎng)格,獨立地對每一塊進行推理,最后合并。另外,一些預(yù)測交集可以用來平滑邊界附近的偽影。
我們來編碼吧!
- from tqdm import tqdm
- class GridPredictor:
- """ This class can be used to predict a segmentation mask for the big image when you have GPU memory limitation """
- def __init__(self, predictor: AbstractPredictor, size: int, stride: Optional[int] = None): self.predictor = predictor
- self.size = size
- self.stride = stride if stride is not None else size // 2
- def __call__(self, x: np.ndarray):
- h, w, _ = x.shape
- mask = np.zeros((h, w, 1), dtype='float32')
- weights = mask.copy()
- for i in tqdm(range(0, h - 1, self.stride)):
- for j in range(0, w - 1, self.stride):
- a, b, c, d = i, min(h, i + self.size), j, min(w, j + self.size)
- patch = x[a:b, c:d, :]
- mask[a:b, c:d, :] += np.expand_dims(self.predictor(patch), -1) weights[a:b, c:d, :] = 1
- return mask / weights
有一個符號輸入錯誤,代碼片段足夠大,因此可以很容易地找到它。我懷疑僅僅通過代碼就可以快速識別它,很容易檢查代碼是否正確:
- class Model(nn.Module):
- def forward(self, x):
- return x.mean(axis=-1)
- model = Model()
- grid_predictor = GridPredictor(model, size=128, stride=64)
- simple_pred = np.expand_dims(model(img), -1)
- grid_pred = grid_predictor(img)
- np.testing.assert_allclose(simple_pred, grid_pred, atol=.001)
調(diào)用方法的正確版本如下:
- def __call__(self, x: np.ndarray):
- h, w, _ = x.shape
- mask = np.zeros((h, w, 1), dtype='float32')
- weights = mask.copy()
- for i in tqdm(range(0, h - 1, self.stride)):
- for j in range(0, w - 1, self.stride): a, b, c, d = i, min(h, i + self.size), j, min(w, j + self.size)
- patch = x[a:b, c:d, :]
- mask[a:b, c:d, :] += np.expand_dims(self.predictor(patch), -1)
- weights[a:b, c:d, :] += 1
- return mask / weights
如果你仍然沒有看出問題所在,請注意線寬 [a:b,c:d,:]+=1。
8.ImageNet 規(guī)范化
當(dāng)一個人需要進行遷移學(xué)習(xí)時,通常最好像訓(xùn)練 ImageNet 時那樣對圖像進行標(biāo)準(zhǔn)化。
讓我們使用我們已經(jīng)熟悉的 albumentations 庫。
- from albumentations import Normalize
- norm = Normalize()
- img = cv2.imread('img_small.jpg')
- mask = cv2.imread('mask_small.png', cv2.IMREAD_GRAYSCALE)
- mask = np.expand_dims(mask, -1) # shape (64, 64) -> shape (64, 64, 1)
- normed = norm(image=img, mask=mask)
- img, mask = [normed[x] for x in ['image', 'mask']]
- def img_to_batch(x):
- x = np.transpose(x, (2, 0, 1)).astype('float32')
- return torch.from_numpy(np.expand_dims(x, 0))
- img, mask = map(img_to_batch, (img, mask))
- criterion = F.binary_cross_entropy
現(xiàn)在是時候訓(xùn)練一個網(wǎng)絡(luò)并使其過擬合某一張圖像了——正如我所提到的,這是一種很好的調(diào)試技術(shù):
- model_a = UNet(3, 1)
- optimizer = torch.optim.Adam(model_a.parameters(), lr=1e-3)
- losses = []
- for t in tqdm(range(20)):
- loss = criterion(model_a(img), mask)
- losses.append(loss.item())
- optimizer.zero_grad()
- loss.backward()
- optimizer.step()
- _ = plt.plot(losses)
曲率看起來很好,但交叉熵的損失值預(yù)計不會是 -300。這是怎么了?
圖像的標(biāo)準(zhǔn)化效果很好,需要手動將其縮放到 [0,1]。
- model_b = UNet(3, 1)
- optimizer = torch.optim.Adam(model_b.parameters(), lr=1e-3)
- losses = []
- for t in tqdm(range(20)):
- loss = criterion(model_b(img), mask / 255.)
- losses.append(loss.item())
- optimizer.zero_grad()
- loss.backward()
- optimizer.step()
- _ = plt.plot(losses)
訓(xùn)練循環(huán)中一個簡單的斷言(例如 assert mask.max()<=1)會很快檢測到問題。同樣,單元測試也可以檢測到問題。
總而言之:
-
測試很重要;
-
運行斷言可以用于訓(xùn)練管道;
-
可視化是一種不錯的手段;
-
抄襲是一種詛咒;
-
沒有什么是靈丹妙藥,機器學(xué)習(xí)工程師必須時刻小心。