我想为交叉熵的对象类指定 2 个损失函数 1,为均方误差的边界框指定另一个。如何在 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'])
最佳答案
首先,你不能在这里使用 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)
现在,您可以根据上面给出的名称并使用字典为每个输出层指定一个损失函数(以及度量):
model.compile(loss={'type': 'binary_crossentropy', 'coord': 'mse'},
optimizer='sgd', metrics={'type': 'accuracy', 'coord': 'mae'})
此外,请注意您使用的是 softmax 作为激活函数,我已将其更改为
sigomid
和 linear
以上。这是因为:1)在一个单元的层上使用 softmax 没有意义(如果有 2 个以上的类,那么你应该使用 softmax),并且 2)另一层预测坐标,因此使用 softmax 根本不适合(除非问题表述让你这样做)。
关于python - 在 Keras 中为模型编译指定多个损失函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53802846/