以一定概率執行某段代碼(Python實現)

簡介

在數據擴增中,我們希望程序以一定概率執行某個擴增的行爲,比如圖像翻轉; 在deep-medic中提到使用一定概率做某件事(忘了幹啥了)。

因此這種以一定概率做某件事在生活中還是很常用的,發現這種做法其實很簡單,這裏參考 Augmentor中使用的方法,將此類問題記錄下來。

內容

這裏粘貼了自己寫的一個類,主要參考第22行即可。

 15 class ElasticTransform(object):
 16     def __init__(self, mode='train', probability=0.6): 
 17         self.mode = mode
 18         self.probability = probability  
 19 
 20     def __call__(self, sample):
 21         if self.mode == 'train':        
 22             if round(np.random.uniform(0, 1), 1) <= self.probability:
 23                 image, target = sample['image'], sample['label']
 24                 sigma = 0.1 * np.random.randint(2, 5) # sigma and points are experience parameter via experiment
 25                 points = np.random.randint(3, 8)
 26                 img_aug = deform_grid(image, target, sigma=sigma, points=points)
 27 
 28                 sample['image'] = img_aug[0]    
 29                 sample['label'] = img_aug[1]    
 30                 return sample
 31             else:
 32                 return sample
 33 
 34         if self.mode == 'test' or self.mode == 'infer': 
 35             return sample
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章