我想在 Keras 中训练一个神经网络(使用 theano 作为后端),每个正样本使用一个负样本,并使用最大边际损失函数:
max(0,1 -pos_score +neg_score)
我有一个神经网络,它接受两个参数i
并j
返回 score base(i,j)
。对于给定i
的,我有一个正样本j
和负样本k
。所以,我想计算以下内容:
max(0, 1 - base(i, j) + base(i, k))
在抽象级别,我的代码如下所示:
i = Input(...) # d=100
j = Input(...) # d=300
k = Input(...) # d=300
i_vec = Sequential()
i_vec.add(Dense(20, input_dim=100))
j_vec = Sequential()
j_vec.add(Dense(30, input_dim=300))
base = Sequential()
base.add(Merge([i_vec, j_vec], mode='concat')
# Here goes definition of the base network
base.add(Dense(output_dim=1, bias=False))
pos = base([i, j])
neg = base([i, k])
def custom_loss(y_true, y_pred):
return K.maximum(0, 1 - y_pred[0] + y_pred[1])
model = Model(input=[i,j,k], output=[pos, neg])
# Shape of I=(1000,100), J and K=(1000,300), XX=(1000,)
model.fit([I, J, K], [XX,XX], nb_epoch=10)
请注意,XX
在训练期间是无用的。
运行代码时,出现以下错误:
ValueError: GpuElemwise. Output dimension mismatch. Output 0 (indices start at 0), working inplace on input 0, has shape[0] == 1, but the output's size on that axis is 32.
Apply node that caused the error: GpuElemwise{Composite{(i0 * (i1 * i2))}}[(0, 0)](GpuElemwise{Composite{Cast{float32}(EQ(i0, i1))}}[(0, 0)].0, GpuElemwise{Composite{(i0 / (i1 * i2))}}[(0, 0)].0, GpuFromHost.0)
Toposort index: 83
Inputs types: [CudaNdarrayType(float32, vector), CudaNdarrayType(float32, (True,)), CudaNdarrayType(float32, vector)]
Inputs shapes: [(1,), (1,), (32,)]
Inputs strides: [(0,), (0,), (1,)]
Inputs values: [CudaNdarray([ 1.]), CudaNdarray([ 1.]), 'not shown']
Outputs clients: [[GpuIncSubtensor{InplaceInc;int64}(GpuIncSubtensor{Inc;int64}.0, GpuElemwise{Composite{(i0 * (i1 * i2))}}[(0, 0)].0, Constant{1}), GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{(i0 * (i1 * i2))}}[(0, 0)].0)]]
我认为问题在于损失函数的计算。
注意:我尝试过使用XX
原始向量和列向量。但是,错误仍然相同。
可以在此处和此处找到使用 TensorFlow 作为后端的相同问题的解决方案。
编辑1:
如下更改损失函数是可行的(我的意思是它可以正常工作)。但是,我既不知道为什么,也不知道新代码的正确性。
def custom_loss(y_true, y_pred):
return K.sum(K.maximum(0, 1 - y_pred[0] + y_pred[1]))