2022-07-08 深度學(xué)習(xí)Python筆記

torchvision.transforms.Compose():?

torchvision是torch中處理計算機(jī)視覺的工具包,主要包含torchvision.transforms:圖形變換如剪裁,旋轉(zhuǎn)等;torchvision.datasets:加載數(shù)據(jù)集的接口 ;torchvision.models:提供ResNet, AlexNet, VGG等模型。

torchvision.transforms.Compose():將多種變換組合在一起:

-----

from torchvision.transforms import transforms

train_transforms = transforms.Compose([

? ? transforms.Resize([224, 224]),? ? ? ? ? ? ? ? ? # 將輸入圖片resize成統(tǒng)一尺寸

? ? transforms.RandomRotation(degrees=(-10, 10)),? # 隨機(jī)旋轉(zhuǎn),-10到10度之間隨機(jī)選

? ? transforms.RandomHorizontalFlip(p=0.5),? ? ? ? # 隨機(jī)水平翻轉(zhuǎn) 選擇一個概率概率

? ? transforms.RandomVerticalFlip(p=0.5),? ? ? ? ? # 隨機(jī)垂直翻轉(zhuǎn)

? ? transforms.RandomPerspective(distortion_scale=0.6, p=1.0),? ? # 隨機(jī)視角

? ? transforms.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 5)),? # 隨機(jī)選擇的高斯模糊模糊圖像

? ? transforms.ToTensor(),? ? ? ? ? # 將PIL Image或numpy.ndarray轉(zhuǎn)換為tensor,并歸一化到[0,1]之間

? ? transforms.Normalize(? ? ? ? ? # 正則化處理-->轉(zhuǎn)換為標(biāo)準(zhǔn)正太分布(高斯分布),使模型更容易收斂

? ? ? ? mean=[0.485, 0.456, 0.406],

? ? ? ? std = [0.229, 0.224, 0.225])? # 其中 mean=[0.485,0.456,0.406]與std=[0.229,0.224,0.225] 從數(shù)據(jù)集中隨機(jī)抽樣計算得到的。

])

transforms.Normalize(mean,std)的計算公式是:

公式

大家可以看到, 為什么在一些深度學(xué)習(xí)圖像預(yù)處理的時候,都是使用mean=[0.485, 0.456, 0.406],?std = [0.229, 0.224, 0.225]呢?pytorch官網(wǎng)之前曾解釋過(All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded in to a range of [0, 1] and then normalized using?mean = [0.485, 0.456, 0.406]?and?std = [0.229, 0.224, 0.225]"),不過這段文字已經(jīng)不在了:所有預(yù)訓(xùn)練模型都期望輸入的圖像已相同的方式進(jìn)行歸一化,所以采用mean = [0.485, 0.456, 0.406] ,std = [0.229, 0.224, 0.225],將圖像轉(zhuǎn)換為標(biāo)準(zhǔn)正太分布(高斯分布),使得模型更容易收斂。

在stackoverflow上的解釋是ImageNet對輸入圖像處理都是采用上述mean和std,他們是基于上百萬張圖像計算而得到的。https://stackoverflow.com/questions/58151507/why-pytorch-officially-use-mean-0-485-0-456-0-406-and-std-0-229-0-224-0-2。

是否使用ImageNet的mean和std,取決于你的圖像數(shù)據(jù),如果是一些自然風(fēng)光、人文、動植物等可以使用,若是一些醫(yī)療影像、宇宙天文、手寫體之類就不太適合,或是經(jīng)過對比度經(jīng)過調(diào)整、顏色經(jīng)過過濾、非正常光照等也不適合。

因為在我的數(shù)據(jù)集是三維建模圖像如長方體,圓柱體的RGB圖像且是使用ResNet18模型,根據(jù)pytorch官網(wǎng):https://pytorch.org/vision/stable/models/generated/torchvision.models.quantization.resnet18.html#torchvision.models.quantization.resnet18

進(jìn)行normalize的時候需要使用mean = [0.485, 0.456, 0.406]?and?std = [0.229, 0.224, 0.225]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容