偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

深度學(xué)習(xí)/計算機視覺常見的8個錯誤總結(jié)及避坑指南

新聞 深度學(xué)習(xí)
人類并不是完美的,我們經(jīng)常在編寫軟件的時候犯錯誤。有時這些錯誤很容易找到:你的代碼根本不工作,你的應(yīng)用程序會崩潰。但有些 bug 是隱藏的,很難發(fā)現(xiàn),這使它們更加危險。

 本文轉(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ù)編進行基本的增強:

  1. def flip_img_and_keypoints(img: np.ndarray, kpts:  
  2.  
  3. Sequence[Sequence[int]]):  
  4.  
  5.         img = np.fliplr(img)  
  6.  
  7.         h, w, *_ = img.shape  
  8.  
  9.         kpts = [(y, w - x) for y, x in kpts]  
  10.  
  11.         return img, kpts 

上面的代碼看起來很對,是不是?接下來,讓我們對它進行可視化。

  1. image = np.ones((1010), dtype=np.float32)  
  2.  
  3. kpts = [(01), (22)]  
  4.  
  5. image_flipped, kpts_flipped = flip_img_and_keypoints(image, kpts)  
  6.  
  7. img1 = image.copy()  
  8.  
  9. for y, x in kpts:  
  10.  
  11.         img1[y, x] = 0  
  12.  
  13. img2 = image_flipped.copy()  
  14.  
  15. for y, x in kpts_flipped:  
  16.  
  17.         img2[y, x] = 0  
  18.  
  19. _ = plt.imshow(np.hstack((img1, img2))) 

這個圖是不對稱的,看起來很奇怪!如果我們檢查極值呢?

  1. image = np.ones((1010), dtype=np.float32)  
  2.  
  3. kpts = [(00), (11)]  
  4.  
  5. image_flipped, kpts_flipped = flip_img_and_keypoints(image, kpts)  
  6.  
  7. img1 = image.copy()  
  8.  
  9. for y, x in kpts:  
  10.  
  11.        img1[y, x] = 0  
  12.  
  13. img2 = image_flipped.copy()  
  14.  
  15. for y, x in kpts_flipped: 
  16.  
  17.        img2[y, x] = 0  
  18.  
  19. -------------------------------------------------------------------- -------  
  20.  
  21. IndexError  
  22.  
  23. Traceback (most recent call last)  
  24.  
  25. <ipython-input-5-997162463eae> in <module>  
  26.  
  27. 8 img2 = image_flipped.copy()  
  28.  
  29. 9 for y, x in kpts_flipped: 
  30.  
  31. ---> 10 img2[y, x] = 0  
  32.  
  33. IndexError: index 10 is out of bounds for axis 1 with size 10 

不好!這是一個典型的錯誤。正確的代碼如下:

  1. def flip_img_and_keypoints(img: np.ndarray, kpts: Sequence[Sequence[int]]):  
  2.  
  3.        img = np.fliplr(img)  
  4.  
  5.        h, w, *_ = img.shape  
  6.  
  7.        kpts = [(y, w - x - 1for y, x in kpts]  
  8.  
  9.        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)鍵點真的是這樣的意思呢:

  1. kpts = [  
  2.  
  3. (2020), # left pinky  
  4.  
  5. (20200), # right pinky 
  6.  
  7. ... 
  8.  

這意味著增強實際上改變了語義: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)代碼!

  1. def iou_continuous_loss(y_pred, y_true):  
  2.  
  3.         eps = 1e-6  
  4.  
  5.        def _sum(x):  
  6.  
  7.               return x.sum(-1).sum(-1)  
  8.  
  9.        numerator = (_sum(y_true * y_pred) + eps)  
  10.  
  11.        denominator = (_sum(y_true ** 2) + _sum(y_pred ** 2) -  
  12.  
  13.               _sum(y_true * y_pred) + eps)  
  14.  
  15.        return (numerator / denominator).mean() 

看起來很不錯,讓我們做一個小小的檢查:

  1. In [3]: ones = np.ones((131010))  
  2.  
  3.        ...: x1 = iou_continuous_loss(ones * 0.01, ones)  
  4.  
  5.        ...: x2 = iou_continuous_loss(ones * 0.99, ones)  
  6.  
  7. In [4]: x1, x2  
  8.  
  9. Out[4]: (0.0100999998979901030.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)該采用用相反的方法: 

  1. v> def iou_continuous(y_pred, y_true):  
  2.  
  3.         eps = 1e-6  
  4.  
  5.        def _sum(x):  
  6.  
  7.               return x.sum(-1).sum(-1)  
  8.  
  9.        numerator = (_sum(y_true * y_pred) + eps)  
  10.  
  11.        denominator = (_sum(y_true ** 2) + _sum(y_pred ** 2)  
  12.  
  13.                                    - _sum(y_true * y_pred) + eps)  
  14.  
  15.        return (numerator / denominator).mean()  
  16.  
  17. def iou_continuous_loss(y_pred, y_true):  
  18.  
  19.        return 1 - iou_continuous(y_pred, y_true) 

這些問題可以通過兩種方式確定:

  • 編寫一個單元測試來檢查損失的方向:形式化地表示一個期望,即更接近實際的東西應(yīng)該輸出更低的損失;

  • 做一個全面的檢查,嘗試過擬合你的模型的 batch。

4.使用 Pytorch

假設(shè)一個人有一個預(yù)先訓(xùn)練好的模型,并且是一個時序模型。我們基于 ceevee api 編寫預(yù)測類。

  1. from ceevee.base import AbstractPredictor  
  2.  
  3. class MySuperPredictor(AbstractPredictor):  
  4.  
  5.         def __init__(self, weights_path: str, ):  
  6.  
  7.               super().__init__()  
  8.  
  9.               self.model = self._load_model(weights_path=weights_path) 
  10.  
  11.        def process(self, x, *kw):  
  12.  
  13.               with torch.no_grad():  
  14.  
  15.                      res = self.model(x)  
  16.  
  17.               return res  
  18.  
  19.        @staticmethod  
  20.  
  21.        def _load_model(weights_path):  
  22.  
  23.               model = ModelClass()  
  24.  
  25.               weights = torch.load(weights_path, map_location='cpu')  
  26.  
  27.               model.load_state_dict(weights)  
  28.  
  29.               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ù):

  1. In [4]: model = nn.Sequential(  
  2.  
  3.         ...: nn.Linear(1010),  
  4.  
  5.        ..: nn.Dropout(.5)  
  6.  
  7.        ...: ) 
  8.  
  9.        ...: 
  10.  
  11.         ...: traced_model = torch.jit.trace(model.eval(), torch.rand(10))  
  12.  
  13.        # 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ù)制粘貼引起的錯誤:

  1. v> def make_dataloaders(train_cfg, val_cfg, batch_size):  
  2.  
  3.        train = Dataset.from_config(train_cfg)  
  4.  
  5.        val = Dataset.from_config(val_cfg)  
  6.  
  7.        shared_params = {'batch_size': batch_size, 'shuffle': True,  
  8.  
  9. 'num_workers': cpu_count()}  
  10.  
  11.        train = DataLoader(train, **shared_params)  
  12.  
  13.        val = DataLoader(train, **shared_params)  
  14.  
  15.        return train, val 

不僅僅是我犯了愚蠢的錯誤。在流行庫中也有類似的錯誤。 

  1.  
  2. https://github.com/albu/albumentations/blob/0.3.0/albumentations/aug mentations/transforms.py  
  3.  
  4. def apply_to_keypoint(self, keypoint, crop_height=0, crop_width=0, h_start=0, w_start=  0, rows=0, cols=0, **params):  
  5.  
  6.         keypoint = F.keypoint_random_crop(keypoint, crop_height, crop_width, h_start, w_start, rows, cols)  
  7.  
  8.         scale_x = self.width / crop_height 
  9.  
  10.         scale_y = self.height / crop_height  
  11.  
  12.         keypoint = F.keypoint_scale(keypoint, scale_x, scale_y) return keypoint 

別擔(dān)心,這個錯誤已經(jīng)修復(fù)了。如何避免?不要復(fù)制粘貼代碼,盡量以不要以復(fù)制粘貼的方式進行編碼。

  1. datasets = []  
  2.  
  3. data_a = get_dataset(MyDataset(config['dataset_a']), config['shared_param'], param_a) datasets.append(data_a)  
  4.  
  5. data_b = get_dataset(MyDataset(config['dataset_b']), config['shared_param'], param_b) datasets.append(data_b) 
  6.  
  7. datasets = []  
  8.  
  9. for name, param in zip(('dataset_a''dataset_b'), (param_a, param_b), ):  
  10.  
  11.         datasets.append(get_dataset(MyDataset(config[name]), config['shared_param'], param)) 

6.合適的數(shù)據(jù)類型

讓我們再做一個增強:

  1. def add_noise(img: np.ndarray) -> np.ndarray:  
  2.  
  3.         mask = np.random.rand(*img.shape) + .5  
  4.  
  5.         img = img.astype('float32') * mask  
  6.  
  7.         return img.astype('uint8'

圖像已經(jīng)改變了。這是我們期望的嗎?嗯,也許改變太多了。

這里有一個危險的操作:將 float32 轉(zhuǎn)到 uint8。這可能導(dǎo)致溢出:

  1. def add_noise(img: np.ndarray) -> np.ndarray:  
  2.  
  3.         mask = np.random.rand(*img.shape) + .5  
  4.  
  5.        img = img.astype('float32') * mask  
  6.  
  7.        return np.clip(img, 0255).astype('uint8')  
  8.  
  9. 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ù)測交集可以用來平滑邊界附近的偽影。

我們來編碼吧!

  1. from tqdm import tqdm  
  2.  
  3. class GridPredictor:  
  4.  
  5. """ This class can be used to predict a segmentation mask for the big image when you have GPU memory limitation """  
  6.  
  7.         def __init__(self, predictor: AbstractPredictor, size: int, stride: Optional[int] = None):               self.predictor = predictor  
  8.  
  9.               self.size = size  
  10.  
  11.               self.stride = stride if stride is not None else size // 2  
  12.  
  13.        def __call__(self, x: np.ndarray):  
  14.  
  15.               h, w, _ = x.shape  
  16.  
  17.               mask = np.zeros((h, w, 1), dtype='float32')  
  18.  
  19.               weights = mask.copy()  
  20.  
  21.               for i in tqdm(range(0, h - 1, self.stride)):  
  22.  
  23.                      for j in range(0, w - 1, self.stride):  
  24.  
  25.                             a, b, c, d = i, min(h, i + self.size), j, min(w, j + self.size)  
  26.  
  27.                             patch = x[a:b, c:d, :]  
  28.  
  29.                             mask[a:b, c:d, :] += np.expand_dims(self.predictor(patch), -1) weights[a:b, c:d, :] = 1  
  30.  
  31.               return mask / weights 

有一個符號輸入錯誤,代碼片段足夠大,因此可以很容易地找到它。我懷疑僅僅通過代碼就可以快速識別它,很容易檢查代碼是否正確:

  1. class Model(nn.Module):  
  2.  
  3.         def forward(self, x):  
  4.  
  5.               return x.mean(axis=-1)  
  6.  
  7. model = Model()  
  8.  
  9. grid_predictor = GridPredictor(model, size=128, stride=64)  
  10.  
  11. simple_pred = np.expand_dims(model(img), -1)  
  12.  
  13. grid_pred = grid_predictor(img)  
  14.  
  15. np.testing.assert_allclose(simple_pred, grid_pred, atol=.001

調(diào)用方法的正確版本如下:

  1. def __call__(self, x: np.ndarray):  
  2.  
  3.        h, w, _ = x.shape  
  4.  
  5.        mask = np.zeros((h, w, 1), dtype='float32')  
  6.  
  7.        weights = mask.copy()  
  8.  
  9.        for i in tqdm(range(0, h - 1, self.stride)):  
  10.  
  11.               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)  
  12.  
  13.                      patch = x[a:b, c:d, :]  
  14.  
  15.                      mask[a:b, c:d, :] += np.expand_dims(self.predictor(patch), -1)  
  16.  
  17.                      weights[a:b, c:d, :] += 1  
  18.  
  19.        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 庫。

  1. from albumentations import Normalize  
  2.  
  3. norm = Normalize()  
  4.  
  5. img = cv2.imread('img_small.jpg')  
  6.  
  7. mask = cv2.imread('mask_small.png', cv2.IMREAD_GRAYSCALE)  
  8.  
  9. mask = np.expand_dims(mask, -1) # shape (6464) -> shape (64641
  10.  
  11. normed = norm(image=img, mask=mask)  
  12.  
  13. img, mask = [normed[x] for x in ['image''mask']]  
  14.  
  15. def img_to_batch(x):  
  16.  
  17.         x = np.transpose(x, (201)).astype('float32'
  18.  
  19.        return torch.from_numpy(np.expand_dims(x, 0))  
  20.  
  21. img, mask = map(img_to_batch, (img, mask))  
  22.  
  23. criterion = F.binary_cross_entropy 

現(xiàn)在是時候訓(xùn)練一個網(wǎng)絡(luò)并使其過擬合某一張圖像了——正如我所提到的,這是一種很好的調(diào)試技術(shù):

  1. model_a = UNet(31)  
  2.  
  3. optimizer = torch.optim.Adam(model_a.parameters(), lr=1e-3)  
  4.  
  5. losses = []  
  6.  
  7. for t in tqdm(range(20)):  
  8.  
  9.         loss = criterion(model_a(img), mask)  
  10.  
  11.        losses.append(loss.item())  
  12.  
  13.        optimizer.zero_grad()  
  14.  
  15.        loss.backward()  
  16.  
  17.        optimizer.step()  
  18.  
  19. _ = plt.plot(losses) 

曲率看起來很好,但交叉熵的損失值預(yù)計不會是 -300。這是怎么了?

圖像的標(biāo)準(zhǔn)化效果很好,需要手動將其縮放到 [0,1]。

  1. model_b = UNet(31)  
  2.  
  3. optimizer = torch.optim.Adam(model_b.parameters(), lr=1e-3)  
  4.  
  5. losses = []  
  6.  
  7. for t in tqdm(range(20)):  
  8.  
  9.         loss = criterion(model_b(img), mask / 255.)  
  10.  
  11.        losses.append(loss.item())  
  12.  
  13.        optimizer.zero_grad()  
  14.  
  15.        loss.backward()  
  16.  
  17.        optimizer.step()  
  18.  
  19. _ = plt.plot(losses) 

訓(xùn)練循環(huán)中一個簡單的斷言(例如 assert mask.max()<=1)會很快檢測到問題。同樣,單元測試也可以檢測到問題。

總而言之:

  • 測試很重要;

  • 運行斷言可以用于訓(xùn)練管道;

  • 可視化是一種不錯的手段;

  • 抄襲是一種詛咒;

  • 沒有什么是靈丹妙藥,機器學(xué)習(xí)工程師必須時刻小心。 

 

責(zé)任編輯:張燕妮 來源: 雷鋒網(wǎng)
相關(guān)推薦

2019-12-11 13:24:57

深度學(xué)習(xí)數(shù)據(jù)結(jié)構(gòu)軟件

2023-11-01 15:32:58

2024-04-03 12:30:00

C++開發(fā)

2023-03-28 15:21:54

深度學(xué)習(xí)計算機視覺

2023-11-20 22:14:16

計算機視覺人工智能

2020-12-16 19:28:07

深度學(xué)習(xí)計算機視覺Python庫

2020-12-15 15:40:18

深度學(xué)習(xí)Python人工智能

2022-01-23 14:29:25

C語言編程語言

2017-11-30 12:53:21

深度學(xué)習(xí)原理視覺

2020-10-15 14:33:07

機器學(xué)習(xí)人工智能計算機

2020-04-26 17:20:53

深度學(xué)習(xí)人工智能計算機視覺

2021-03-29 11:52:08

人工智能深度學(xué)習(xí)

2018-01-20 20:46:33

2025-03-26 02:00:00

API工具開發(fā)

2024-12-31 15:52:43

2020-06-12 11:03:22

Python開發(fā)工具

2020-09-13 09:19:10

LinuxPython3.6

2024-03-28 12:51:00

Spring異步多線程

2021-07-15 08:00:00

人工智能深度學(xué)習(xí)技術(shù)

2024-04-24 13:45:00

點贊
收藏

51CTO技術(shù)棧公眾號