从张量中减去标量在 pytorch 中产生 'inconsistent tensor size'

subtraction of scalar from tensor yields 'inconsistent tensor size' in pytorch

我正在使用 pytorch,我的变量是

x = [torch.FloatTensor of size 1x3x32x32]
mean = Variable containing:
1.00000e-02 *
  2.0518
[torch.FloatTensor of size 1]

我想做的是通过

从 x 中减去标量均值
x = x - mean

但是,我收到了这个错误:

RuntimeError: inconsistent tensor size at /py/conda-
bld/pytorch_1493670682084/work/torch/lib/TH/generic/THTensorMath.c:831

我做错了什么? 非常感谢

只有当 mean 确实是标量时,您尝试的方法才有效,即 float()(在本例中)而不是 torch.FloatTensor of size 1。您可以从 mean 中提取一个真正的标量,或者将 mean 扩展到 x 的大小以执行减法。

要从 mean 中提取 float,请执行:

x = x - mean[0]

要将 mean 扩展到 x 的大小,请执行:

x = x - mean.expand_as(x)

请注意,这两种方法都从张量中的每个元素中减去平均值。