Pytorch:プリトレーニングモデルに入力されたデータプリプロセッシング

1763 ワード

よく見られます.
transform = transforms.Compose([
        transforms.RandomResizedCrop(100),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])

ここで用いるmean=[0.485,0.456,0.406]およびstd=[0.229,0.224,0.225]を正規化する.
ここでの数字は,予備訓練モデルの訓練時に採用されるフォーマットであり,予備訓練モデルと同じフォーマットを維持する必要がある.
同時にpytorch公式紹介では,予備訓練モデルはいずれも【0,1】標準分布を用いた画像訓練であることを説明した.
以下はpytorchのサンプルで使用されるmeanとstdです.
https://github.com/pytorch/examples/tree/42e5b996718797e45c46a25c55b031e6768f8440
計算meanとstdのコードを添付します.
transform = transforms.Compose([
    transforms.ToPILImage(),
    transforms.ToTensor()
])

dataloader = torch.utils.data.DataLoader(*torch_dataset*, batch_size=4096, shuffle=False, num_workers=4)

pop_mean = []
pop_std0 = []
pop_std1 = []
for i, data in enumerate(dataloader, 0):
    # shape (batch_size, 3, height, width)
    numpy_image = data['image'].numpy()
    
    # shape (3,)
    batch_mean = np.mean(numpy_image, axis=(0,2,3))
    batch_std0 = np.std(numpy_image, axis=(0,2,3))      ##    
    batch_std1 = np.std(numpy_image, axis=(0,2,3), ddof=1) ##    
    
    pop_mean.append(batch_mean)
    pop_std0.append(batch_std0)
    pop_std1.append(batch_std1)

# shape (num_iterations, 3) -> (mean across 0th axis) -> shape (3,)
pop_mean = np.array(pop_mean).mean(axis=0)
pop_std0 = np.array(pop_std0).mean(axis=0)
pop_std1 = np.array(pop_std1).mean(axis=0)

追加するだけで計算されます.
transform = transforms.Compose([
    transforms.ToPILImage(),
    transforms.ToTensor(),
    transforms.Normalize(mean=*your_calculated_mean*, std=*your_calculated_std*)
])

batchに分けてmeanを計算し、平均をとる.