99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀8個計算機(jī)視覺深度學(xué)習(xí)中常見的Bug
8個計算機(jī)視覺深度學(xué)習(xí)中常見的Bug
2019-12-11
收藏
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

作者 | Arseny Kravchenko

編譯 | ronghuaiyang

人是不完美的,我們經(jīng)常在軟件中犯錯誤。有時這些錯誤很容易發(fā)現(xiàn):你的代碼根本不能工作,你的應(yīng)用程序崩潰等等。但是有些bug是隱藏的,這使得它們更加危險。

在解決深度學(xué)習(xí)問題時,由于一些不確定性,很容易出現(xiàn)這種類型的bug:很容易看到web應(yīng)用程序路由請求是否正確,而不容易檢查你的梯度下降步驟是否正確。然而,有很多錯誤是可以避免的。

8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

我想分享一些我的經(jīng)驗(yàn),關(guān)于我在過去兩年的計算機(jī)視覺工作中看到或制造的錯誤。我之前有談到過這個話題,很多人告訴我:“是的,我也有很多這樣的bug?!蔽蚁M业奈恼驴梢詭椭阒辽俦苊馄渲械囊恍﹩栴}。

1. 翻轉(zhuǎn)圖片以及關(guān)鍵點(diǎn)

假設(shè)在關(guān)鍵點(diǎn)檢測的問題上。數(shù)據(jù)看起來像一對圖像和一系列的關(guān)鍵點(diǎn)元組。其中每個關(guān)鍵點(diǎn)是一對x和y坐標(biāo)。

讓我們對這個數(shù)據(jù)進(jìn)行基礎(chǔ)的增強(qiáng):

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

看起來是正確的,嗯?我們把它可視化。

  1. image = np.ones((10, 10), dtype=np.float32)
  2. kpts = [(0, 1), (2, 2)]
  3. image_flipped, kpts_flipped = flip_img_and_keypoints(image, kpts)
  4. img1 = image.copy()
  5. for y, x in kpts:
  6. img1[y, x] = 0
  7. img2 = image_flipped.copy()
  8. for y, x in kpts_flipped:
  9. img2[y, x] = 0

  10. _ = plt.imshow(np.hstack((img1, img2)))
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

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

  1. image = np.ones((10, 10), dtype=np.float32)
  2. kpts = [(0, 0), (1, 1)]
  3. image_flipped, kpts_flipped = flip_img_and_keypoints(image, kpts)
  4. img1 = image.copy()
  5. for y, x in kpts:
  6. img1[y, x] = 0
  7. img2 = image_flipped.copy()
  8. for y, x in kpts_flipped:
  9. img2[y, x] = 0
  10. ---------------------------------------------------------------------------
  11. IndexError Traceback (most recent call last)
  12. <ipython-input-5-997162463eae> in <module>
  13. 8 img2 = image_flipped.copy()
  14. 9 for y, x in kpts_flipped:
  15. ---> 10 img2[y, x] = 0
  16. IndexError: index 10 is out of bounds for axis 1 with size 10

不好!這是一個典型的off-by-one錯誤。正確的代碼是這樣的:

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

我們通過可視化發(fā)現(xiàn)了這個問題,但是,使用“x = 0”點(diǎn)進(jìn)行單元測試也會有所幫助。一個有趣的事實(shí)是:有一個團(tuán)隊(duì)中有三個人(包括我自己)獨(dú)立地犯了幾乎相同的錯誤。

2. 繼續(xù)是關(guān)鍵點(diǎn)相關(guān)的問題

即使在上面的函數(shù)被修復(fù)之后,仍然存在危險。現(xiàn)在更多的是語義,而不僅僅是一段代碼。

假設(shè)需要用兩只手掌來增強(qiáng)圖像。看起來很安全:手是左,右翻轉(zhuǎn)。

8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

但是等等!我們對關(guān)鍵點(diǎn)的語義并不很了解。如果這個關(guān)鍵點(diǎn)的意思是這樣的:

  1. kpts = [
  2. (20, 20), # left pinky
  3. (20, 200), # right pinky
  4. ...
  5. ]
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

這意味著增強(qiáng)實(shí)際上改變了語義:左變成右,右變成左,但我們不交換數(shù)組中的關(guān)鍵點(diǎn)索引。它會給訓(xùn)練帶來大量的噪音和更糟糕的度量。

我們應(yīng)該吸取一個教訓(xùn):

  • 在應(yīng)用增強(qiáng)或其他花哨的功能之前,了解并考慮數(shù)據(jù)結(jié)構(gòu)和語義
  • 保持你的實(shí)驗(yàn)原子性:添加一個小的變化(例如一個新的變換),檢查它如何進(jìn)行,如果分?jǐn)?shù)提高才加進(jìn)去。

3. 編寫自己的損失函數(shù)

熟悉語義分割問題的人可能知道IoU指標(biāo)。不幸的是,我們不能直接用SGD來優(yōu)化它,所以常用的方法是用可微損失函數(shù)來近似它。

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

看起來不錯,我們先做個小的檢查:

  1. In [3]: ones = np.ones((1, 3, 10, 10))
  2. ...: x1 = iou_continuous_loss(ones * 0.01, ones)
  3. ...: x2 = iou_continuous_loss(ones * 0.99, ones)
  4. In [4]: x1, x2
  5. Out[4]: (0.010099999897990103, 0.9998990001020204)

在 x1中,我們計算了一些與ground truth完全不同的東西的損失,而 x2則是非常接近ground truth的東西的結(jié)果。我們預(yù)計 x1會很大,因?yàn)轭A(yù)測是錯誤的, x2應(yīng)該接近于零。怎么了?

上面的函數(shù)是對metric的一個很好的近似。metric不是一種損失:它通常(包括這種情況)越高越好。當(dāng)我們使用SGD來最小化損失時,我們應(yīng)該使用一些相反的東西:

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

這些問題可以從兩個方面來確定:

  • 編寫一個單元測試,檢查損失的方向:形式化的期望,更接近ground truth應(yīng)該輸出更低的損失。
  • 運(yùn)行一個健全的檢查,讓你的模型在單個batch中過擬合
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

4. 當(dāng)我們使用Pytorch的時候

假設(shè)有一個預(yù)先訓(xùn)練好的模型,開始做infer。

  1. from ceevee.base import AbstractPredictor
  2. class MySuperPredictor(AbstractPredictor):
  3. def __init__(self,
  4. weights_path: str,
  5. ):
  6. super().__init__()
  7. self.model = self._load_model(weights_path=weights_path)
  8. def process(self, x, *kw):
  9. with torch.no_grad():
  10. res = self.model(x)
  11. return res
  12. @staticmethod
  13. def _load_model(weights_path):
  14. model = ModelClass()
  15. weights = torch.load(weights_path, map_location='cpu')
  16. model.load_state_dict(weights)
  17. return model

這個代碼正確嗎?也許!這確實(shí)適用于某些模型。例如,當(dāng)模型沒有dropout或norm層,如 torch.nn.BatchNorm2d?;蛘弋?dāng)模型需要為每個圖像使用實(shí)際的norm統(tǒng)計量時(例如,許多基于pix2pix的架構(gòu)需要它)。

但是對于大多數(shù)計算機(jī)視覺應(yīng)用程序來說,代碼忽略了一些重要的東西:切換到評估模式。

如果試圖將動態(tài)PyTorch圖轉(zhuǎn)換為靜態(tài)PyTorch圖,這個問題很容易識別。 torch.jit用于這種轉(zhuǎn)換。

  1. In [3]: model = nn.Sequential(
  2. ...: nn.Linear(10, 10),
  3. ...: nn.Dropout(.5)
  4. ...: )
  5. ...:
  6. ...: traced_model = torch.jit.trace(model, torch.rand(10))
  7. /Users/Arseny/.pyenv/versions/3.6.6/lib/python3.6/site-packages/torch/jit/__init__.py:914: TracerWarning: Trace had nondeterministic nodes. Did you forget call .eval() on your model? Nodes:
  8. %12 : Float(10) = aten::dropout(%input, %10, %11), scope: Sequential/Dropout[1] # /Users/Arseny/.pyenv/versions/3.6.6/lib/python3.6/site-packages/torch/nn/functional.py:806:0
  9. This may cause errors in trace checking. To disable trace checking, pass check_trace=False to torch.jit.trace()
  10. check_tolerance, _force_outplace, True, _module_class)
  11. /Users/Arseny/.pyenv/versions/3.6.6/lib/python3.6/site-packages/torch/jit/__init__.py:914: TracerWarning: Output nr 1. of the traced function does not match the corresponding output of the Python function. Detailed error:
  12. Not within tolerance rtol=1e-05 atol=1e-05 at input[5] (0.0 vs. 0.5454154014587402) and 5 other locations (60.00%)
  13. check_tolerance, _force_outplace, True, _module_class)
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

簡單的修復(fù)一下:

  1. In [4]: model = nn.Sequential(
  2. ...: nn.Linear(10, 10),
  3. ...: nn.Dropout(.5)
  4. ...: )
  5. ...:
  6. ...: traced_model = torch.jit.trace(model.eval(), torch.rand(10))
  7. # No more warnings!

在這種情況下, torch.jit.trace將模型運(yùn)行幾次并比較結(jié)果。這里的差別是可疑的。

然而 torch.jit.trace在這里不是萬能藥。這是一種應(yīng)該知道和記住的細(xì)微差別。

5. 復(fù)制粘貼的問題

很多東西都是成對存在的:訓(xùn)練和驗(yàn)證、寬度和高度、緯度和經(jīng)度……

  1. def make_dataloaders(train_cfg, val_cfg, batch_size):
  2. train = Dataset.from_config(train_cfg)
  3. val = Dataset.from_config(val_cfg)
  4. shared_params = {'batch_size': batch_size, 'shuffle': True, 'num_workers': cpu_count()}
  5. train = DataLoader(train, **shared_params)
  6. val = DataLoader(train, **shared_params)
  7. return train, val

不僅僅是我犯了愚蠢的錯誤。例如,在非常流行的albumentations庫也有一個類似的版本。

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

別擔(dān)心,已經(jīng)修改好了。

如何避免?不要復(fù)制和粘貼代碼,盡量以不需要復(fù)制和粘貼的方式編寫代碼。

【NO】

  1. datasets = []
  2. data_a = get_dataset(MyDataset(config['dataset_a']), config['shared_param'], param_a)
  3. datasets.append(data_a)
  4. data_b = get_dataset(MyDataset(config['dataset_b']), config['shared_param'], param_b)
  5. datasets.append(data_b)

【YES】

  1. datasets = []
  2. for name, param in zip(('dataset_a', 'dataset_b'),
  3. (param_a, param_b),
  4. ):
  5. datasets.append(get_dataset(MyDataset(config[name]), config['shared_param'], param))

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

讓我們編寫一個新的增強(qiáng)

  1. def add_noise(img: np.ndarray) -> np.ndarray:
  2. mask = np.random.rand(*img.shape) + .5
  3. img = img.astype('float32') * mask
  4. return img.astype('uint8')
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

圖像已被更改。這是我們所期望的嗎?嗯,也許它改變得太多了。

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

  1. def add_noise(img: np.ndarray) -> np.ndarray:
  2. mask = np.random.rand(*img.shape) + .5
  3. img = img.astype('float32') * mask
  4. return np.clip(img, 0, 255).astype('uint8')
  5. img = add_noise(cv2.imread('two_hands.jpg')[:, :, ::-1])
  6. _ = plt.imshow(img)
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

看起來好多了,是吧?

順便說一句,還有一種方法可以避免這個問題:不要重新發(fā)明輪子,不要從頭開始編寫增強(qiáng)代碼并使用現(xiàn)有的擴(kuò)展: albumentations.augmentations.transforms.GaussNoise。

我曾經(jīng)做過另一個同樣起源的bug。

  1. raw_mask = cv2.imread('mask_small.png')
  2. mask = raw_mask.astype('float32') / 255
  3. mask = cv2.resize(mask, (64, 64), interpolation=cv2.INTER_LINEAR)
  4. mask = cv2.resize(mask, (128, 128), interpolation=cv2.INTER_CUBIC)
  5. mask = (mask * 255).astype('uint8')
  6. _ = plt.imshow(np.hstack((raw_mask, mask)))

這里出了什么問題?首先,用三次插值調(diào)整掩模的大小是一個壞主意。同樣的問題 float32到 uint8:三次插值可以輸出值大于輸入,這會導(dǎo)致溢出。

8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

我在做可視化的時候發(fā)現(xiàn)了這個問題。在你的訓(xùn)練循環(huán)中到處放置斷言也是一個好主意。

7. 拼寫錯誤

假設(shè)需要對全卷積網(wǎng)絡(luò)(如語義分割問題)和一個巨大的圖像進(jìn)行推理。該圖像是如此巨大,沒有機(jī)會把它放在你的GPU中,它可以是一個醫(yī)療或衛(wèi)星圖像。

在這種情況下,可以將圖像分割成網(wǎng)格,獨(dú)立地對每一塊進(jìn)行推理,最后合并。此外,一些預(yù)測交叉可能有助于平滑邊界附近的artifacts。

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

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

  1. class Model(nn.Module):
  2. def forward(self, x):
  3. return x.mean(axis=-1)
  4. model = Model()
  5. grid_predictor = GridPredictor(model, size=128, stride=64)
  6. simple_pred = np.expand_dims(model(img), -1)
  7. grid_pred = grid_predictor(img)
  8. np.testing.assert_allclose(simple_pred, grid_pred, atol=.001)
  9. ---------------------------------------------------------------------------
  10. AssertionError Traceback (most recent call last)
  11. <ipython-input-24-a72034c717e9> in <module>
  12. 9 grid_pred = grid_predictor(img)
  13. 10
  14. ---> 11 np.testing.assert_allclose(simple_pred, grid_pred, atol=.001)
  15. ~/.pyenv/versions/3.6.6/lib/python3.6/site-packages/numpy/testing/_private/utils.py in assert_allclose(actual, desired, rtol, atol, equal_nan, err_msg, verbose)
  16. 1513 header = 'Not equal to tolerance rtol=%g, atol=%g' % (rtol, atol)
  17. 1514 assert_array_compare(compare, actual, desired, err_msg=str(err_msg),
  18. -> 1515 verbose=verbose, header=header, equal_nan=equal_nan)
  19. 1516
  20. 1517
  21. ~/.pyenv/versions/3.6.6/lib/python3.6/site-packages/numpy/testing/_private/utils.py in assert_array_compare(comparison, x, y, err_msg, verbose, header, precision, equal_nan, equal_inf)
  22. 839 verbose=verbose, header=header,
  23. 840 names=('x', 'y'), precision=precision)
  24. --> 841 raise AssertionError(msg)
  25. 842 except ValueError:
  26. 843 import traceback
  27. AssertionError:
  28. Not equal to tolerance rtol=1e-07, atol=0.001
  29. Mismatch: 99.6%
  30. Max absolute difference: 765.
  31. Max relative difference: 0.75000001
  32. x: array([[[215.333333],
  33. [192.666667],
  34. [250. ],...
  35. y: array([[[ 215.33333],
  36. [ 192.66667],
  37. [ 250. ],...
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

下面是 __call__方法的正確版本:

  1. def __call__(self, x: np.ndarray):
  2. h, w, _ = x.shape
  3. mask = np.zeros((h, w, 1), dtype='float32')
  4. weights = mask.copy()
  5. for i in tqdm(range(0, h - 1, self.stride)):
  6. for j in range(0, w - 1, self.stride):
  7. a, b, c, d = i, min(h, i + self.size), j, min(w, j + self.size)
  8. patch = x[a:b, c:d, :]
  9. mask[a:b, c:d, :] += np.expand_dims(self.predictor(patch), -1)
  10. weights[a:b, c:d, :] += 1
  11. return mask / weights

如果你仍然不知道問題出在哪里,請注意 weights[a:b,c:d,:]+=1這一行。

8. Imagenet歸一化

當(dāng)一個人需要進(jìn)行轉(zhuǎn)移學(xué)習(xí)時,用訓(xùn)練Imagenet時的方法將圖像歸一化通常是一個好主意。

讓我們使用我們已經(jīng)熟悉的albumentations庫。

  1. from albumentations import Normalize
  2. norm = Normalize()
  3. img = cv2.imread('img_small.jpg')
  4. mask = cv2.imread('mask_small.png', cv2.IMREAD_GRAYSCALE)
  5. mask = np.expand_dims(mask, -1) # shape (64, 64) -> shape (64, 64, 1)
  6. normed = norm(image=img, mask=mask)
  7. img, mask = [normed[x] for x in ['image', 'mask']]
  8. def img_to_batch(x):
  9. x = np.transpose(x, (2, 0, 1)).astype('float32')
  10. return torch.from_numpy(np.expand_dims(x, 0))
  11. img, mask = map(img_to_batch, (img, mask))
  12. criterion = F.binary_cross_entropy

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

  1. model_a = UNet(3, 1)
  2. optimizer = torch.optim.Adam(model_a.parameters(), lr=1e-3)
  3. losses = []
  4. for t in tqdm(range(20)):
  5. loss = criterion(model_a(img), mask)
  6. losses.append(loss.item())
  7. optimizer.zero_grad()
  8. loss.backward()
  9. optimizer.step()

  10. _ = plt.plot(losses)
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

曲率看起來很好,但是交叉熵的損失值-300是不可預(yù)料的。是什么問題?

歸一化處理圖像效果很好,但是mask沒有:需要手動縮放到 [0,1]。

  1. model_b = UNet(3, 1)
  2. optimizer = torch.optim.Adam(model_b.parameters(), lr=1e-3)
  3. losses = []
  4. for t in tqdm(range(20)):
  5. loss = criterion(model_b(img), mask / 255.)
  6. losses.append(loss.item())
  7. optimizer.zero_grad()
  8. loss.backward()
  9. optimizer.step()

  10. _ = plt.plot(losses)
8個<a href='/map/jisuanjishijue/' style='color:#000;font-size:inherit;'>計算機(jī)視覺</a><a href='/map/shenduxuexi/' style='color:#000;font-size:inherit;'>深度學(xué)習(xí)</a>中常見的Bug

訓(xùn)練循環(huán)的簡單運(yùn)行時斷言(例如 assertmask.max()<=1會很快檢測到問題。同樣,也可以是單元測試。

總結(jié)

  • 測試很有必要
  • 運(yùn)行時斷言可以用于訓(xùn)練的pipeline;
  • 可視化是一種幸福
  • 復(fù)制粘貼是一種詛咒
  • 沒有什么是靈丹妙藥,一個機(jī)器學(xué)習(xí)工程師必須總是小心(或只是受苦)。

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }