【发布时间】:2017-11-24 06:17:36
【问题描述】:
我已经看到可以像这样在 caffe 中定义一个自定义损失层,例如 EuclideanLoss:
import caffe
import numpy as np
class EuclideanLossLayer(caffe.Layer):
"""
Compute the Euclidean Loss in the same manner as the C++
EuclideanLossLayer
to demonstrate the class interface for developing layers in Python.
"""
def setup(self, bottom, top):
# check input pair
if len(bottom) != 2:
raise Exception("Need two inputs to compute distance.")
def reshape(self, bottom, top):
# check input dimensions match
if bottom[0].count != bottom[1].count:
raise Exception("Inputs must have the same dimension.")
# difference is shape of inputs
self.diff = np.zeros_like(bottom[0].data, dtype=np.float32)
# loss output is scalar
top[0].reshape(1)
def forward(self, bottom, top):
self.diff[...] = bottom[0].data - bottom[1].data
top[0].data[...] = np.sum(self.diff**2) / bottom[0].num / 2.
def backward(self, top, propagate_down, bottom):
for i in range(2):
if not propagate_down[i]:
continue
if i == 0:
sign = 1
else:
sign = -1
bottom[i].diff[...] = sign * self.diff / bottom[i].num
但是,我对该代码有几个问题:
如果我想自定义这一层并改变这一行中损失的计算:
top[0].data[...] = np.sum(self.diff**2) / bottom[0].num / 2.
让我们说:
channelsAxis = bottom[0].data.shape[1]
self.diff[...] = np.sum(bottom[0].data, axis=channelAxis) - np.sum(bottom[1].data, axis=channelAxis)
top[0].data[...] = np.sum(self.diff**2) / bottom[0].num / 2.
如何更改后退功能?对于 EuclideanLoss 它是:
bottom[i].diff[...] = sign * self.diff / bottom[i].num
它必须如何查找我描述的损失?
标志是什么?
【问题讨论】:
-
欧几里得损失有什么权重和偏差??
-
对不起,我也有点糊涂了。我已经更新了问题! @Shai
-
top[0].data[...] = euclidean_weight * euclidean + other_weight * other不是这样做的正确方法。您可以使用loss_weight: euclidean_weight使用常规欧几里得损失层,使用loss_weight: other_weight使用您自己的"OtherLoss"层。 -
bottom[i].data是shape(num, channel, height, width)的np.array。bottom[i].data.shape[0] == bottom[i].num
标签: python neural-network deep-learning caffe pycaffe