CoreML 中的潜在向量方差比 PyTorch 大得多

Latent vector variance much larger in CoreML than PyTorch

我有一个已转换为 CoreML 的 PyTorch 模型。在 PyTorch 中,推断的潜在向量的值范围限制在 ±1.6 左右,但转换后的 mlmodel 变化高达 ±55.0。是什么导致了这种巨大的差异?转换非常简单:

encoder = Encoder_CNN(latent_dim, n_c)
enc_fname = os.path.join(models_dir, encoder.name + '_153.pth.tar')
encoder.load_state_dict(torch.load(enc_fname, map_location={'cuda:0': 'cpu'}))
encoder.cpu()
encoder.eval()

img_in = torch.rand(1, 1, 28, 28).cpu()
traced_encoder_model = torch.jit.trace(encoder, img_in)
traced_encoder_model.save("{}_encoder_mobile_{}_{}.pt".format(model_type, latent_dim, n_c))

coreml_encoder = ct.convert(traced_encoder_model, inputs=[ct.ImageType(name=name, shape=img_in.shape)])
coreml_encoder.save("{}_encoder_{}_{}.mlmodel".format(model_type, latent_dim, n_c))

您可能正在为 PyTorch 和 Core ML 使用不同的输入规范化。您的 img_in 由 0 到 1 之间的值组成。我没有看到 Core ML 的推理代码,但您的输入像素可能在 0 到 255 之间。您可以通过在将 PyTorch 模型转换为 Core ML 时指定图像预处理设置来解决此问题。