在 Keras 中为模型编译指定多个损失函数

Ahm*_*ael 3 python deep-learning keras tensorflow

我想为交叉熵的对象类指定 2 个损失函数,另一个为均方误差的边界框。如何在 model.compile 每个输出中指定相应的损失函数?

model = Sequential()

model.add(Dense(128, activation='relu'))
out_last_dense = model.add(Dense(128, activation='relu'))
object_type = model.add(Dense(1, activation='softmax'))(out_last_dense)
object_coordinates = model.add(Dense(4, activation='softmax'))(out_last_dense)

/// here is the problem i want to specify loss function for object type and coordinates
model.compile(loss= keras.losses.categorical_crossentropy,
   optimizer= 'sgd', metrics=['accuracy'])
Run Code Online (Sandbox Code Playgroud)

tod*_*day 7

首先,你不能在这里使用 Sequential API,因为你的模型有两个输出层(即你写的都是错误的,会引发错误)。相反,您必须使用Keras Functional API

inp = Input(shape=...)
x = Dense(128, activation='relu')(inp)
x = Dense(128, activation='relu')(x)
object_type = Dense(1, activation='sigmoid', name='type')(x)
object_coordinates = Dense(4, activation='linear', name='coord')(x)
Run Code Online (Sandbox Code Playgroud)

现在,您可以根据上面给出的名称并使用字典为每个输出层指定一个损失函数(以及度量):

model.compile(loss={'type': 'binary_crossentropy', 'coord': 'mse'}, 
              optimizer='sgd', metrics={'type': 'accuracy', 'coord': 'mae'})
Run Code Online (Sandbox Code Playgroud)

此外,请注意您使用的是 softmax 作为激活函数,我已将其更改为sigomidlinear以上。这是因为:1)在一个单元的层上使用 softmax 没有意义(如果有 2 个以上的类,那么你应该使用 softmax),并且 2)另一层预测坐标,因此使用 softmax 根本不适合(除非问题表述让你这样做)。