Caffe:使用 Scale 层添加 Softmax 温度

Caffe: Adding Softmax temperature using Scale layer

我正在尝试使用 "temperature" 参数实现 Caffe Softmax 层。我正在使用概述的蒸馏技术实现网络 here

本质上,我希望我的 Softmax 层使用 Softmax w/ temperature 函数,如下所示:

F(X) = exp(zi(X)/T) / sum(exp(zl(X)/T))

使用它,我希望能够在训练前调整温度 T。我发现了一个类似的 question,但是这个问题试图在部署网络上实现带有温度的 Softmax。我正在努力实现第一个答案中描述为 "option 4" 的附加 Scale 层。

我正在使用 Caffe 示例目录中的 cifar10_full_train_test prototxt 文件。我已尝试进行以下更改:

原创

...
...
...
layer {
  name: "accuracy"
  type: "Accuracy"
  bottom: "ip1"
  bottom: "label"
  top: "accuracy"
  include {
    phase: TEST
  }
}
layer {
  name: "loss"
  type: "SoftmaxWithLoss"
  bottom: "ip1"
  bottom: "label"
  top: "loss"
}

已修改

...
...
...
layer {
  name: "accuracy"
  type: "Accuracy"
  bottom: "ip1"
  bottom: "label"
  top: "accuracy"
  include {
    phase: TEST
  }
}
layer {
  type: "Scale"
  name: "temperature"
  top: "zi/T"
  bottom: "ip1"
  scale_param {
    filler: { type: 'constant' value: 0.025 } ### I wanted T = 40, so 1/40=.025
  }
  param { lr_mult: 0 decay_mult: 0 }
}
layer {
  name: "loss"
  type: "SoftmaxWithLoss"
  bottom: "ip1"
  bottom: "label"
  top: "loss"
}

经过快速训练(5,000 次迭代)后,我检查了我的分类概率是否看起来更均匀,但实际上它们似乎分布不均匀。

示例:

高温 T: F(X) = [0.2, 0.5, 0.1, 0.2]

低温 T: F(X) = [0.02, 0.95, 0.01, 0.02]

~我的尝试:F(X) = [0, 1.0, 0, 0]


这个实施看起来是否正确?不管怎样,我错过了什么?

您没有使用 "cooled" 预测 "zi/T" 您的 "Scale" 层生成。

layer {
  name: "loss"
  type: "SoftmaxWithLoss"
  bottom: "zi/T"  # Use the "cooled" predictions instead of the originals.
  bottom: "label"
  top: "loss"
}

接受的答案帮助我理解了我对 Softmax 温度实现的误解。

正如@Shai 指出的那样,为了观察到我预期的 "cooled" 概率输出,必须只将 Scale 层添加到 "deploy" prototxt 文件中。根本没有必要在 train/val prototxt 中包含 Scale 层。换句话说,温度必须应用于 Softmax 层,而不是 SoftmaxWithLoss 层。

如果您想将 "cooled" 效果应用于您的概率向量,只需确保您的最后两层是这样的:

deploy.prototxt

layer {
  type: "Scale"
  name: "temperature"
  top: "zi/T"
  bottom: "ip1"
  scale_param {
    filler: { type: 'constant' value: 1/T } ## Replace "1/T" with actual 1/T value
  }
  param { lr_mult: 0 decay_mult: 0 }
}
layer {
  name: "prob"
  type: "Softmax"
  bottom: "zi/T"
  top: "prob"
}

我的困惑主要是因为我误解了 SoftmaxWithLoss 和 Softmax 之间的区别。