我无法找到一种有效的方法来给这个函数提供批量输入并返回批量输出。我希望在训练我的神经网络时能够做到这一点。
Inverse_Norm = transforms.Normalize( mean = [-m/s for m, s in zip(mean, std)], std = [1/s for s in std])inverse_norm_input = Inverse_Norm(input)
回答:
假设一个形状为(B, C, ...)
的张量,其中mean
和std
是长度为C
的可迭代对象,那么你可以使用广播语义来操作批量张量。例如
import torchdef batch_inverse_normalize(x, mean, std): # 将mean和std表示为1, C, 1, ...的张量以便广播 reshape_shape = [1, -1] + ([1] * (len(x.shape) - 2)) mean = torch.tensor(mean, device=x.device, dtype=x.dtype).reshape(*reshape_shape) std = torch.tensor(std, device=x.device, dtype=x.dtype).reshape(*reshape_shape) return x * std + mean