Keras自定义损失错误:未知损失函数

时间:2018-10-05 02:10:04

标签: python tensorflow keras loss-function

我试图在Keras中自定义损失函数。

我尝试了两种方法:

import keras.backend as K
from keras.losses import mean_absolute_error

def mae_in_minute(y_true, y_pred):
    temp = K.mean(K.abs(y_pred - y_true), axis=-1)/60
    return temp

import keras.backend as K
from keras.losses import mean_absolute_error

def mae_in_minute(y_true, y_pred):
    return mean_absolute_error(y_true, y_pred)/60

我的模型结构是:

input_layer = Input(shape=training.shape[1:len(training.shape)])
added = Conv2D(128, (3, training.shape[2]),activation="relu")(input_layer)
added = Flatten()(added)
added = Dense(600, activation='relu')(added)
added = Dense(400, activation='relu')(added)
added = Dense(256, activation='relu')(added)
added = Dense(256, activation='relu')(added)
added = Dense(256, activation='relu')(added)
added = Dense(200, activation='relu')(added)
added = Dense(100, activation='relu')(added)
added = Dense(50, activation='relu')(added)
output_temp = Dense(2,activation='softmax', name="temp_output")(added)
output_time = Dense(1,activation='relu', name="time_output")(added)
model = Model(input=input_layer, output=[output_temp,output_time])
losses = {
    "temp_output": "categorical_crossentropy",
    "time_output": "mae_in_minute",
}
lossWeights = {"temp_output": 1.0, "time_output": 1.0}
model.compile(optimizer='adam',loss=losses, loss_weights=lossWeights)
model.summary()

但是我收到了两种自定义丢失方法的错误消息:

  
    

未知损失函数:mae_in_minute

  

如何解决此问题?

我找到了一种解决方法here

但这是使用自定义损失的唯一方法吗?要预先保存并加载模型?

谢谢。

1 个答案:

答案 0 :(得分:2)

只需删除自定义损失的形式,它就可以完美运行。

我的损失

import keras.backend as K
from keras.losses import mean_absolute_error

def mae_in_minute(y_true, y_pred):
    return mean_absolute_error(y_true, y_pred)/60

之前

losses = {
    "temp_output": "categorical_crossentropy",
    "time_output": "mae_in_minute",
}
lossWeights = {"temp_output": 1.0, "time_output": 1.0}
model.compile(optimizer='adam',loss=losses, loss_weights=lossWeights)
model.summary()

之后

losses = {
    "temp_output": "categorical_crossentropy",
    "time_output": mae_in_minute,
}
lossWeights = {"temp_output": 1.0, "time_output": 1.0}
model.compile(optimizer='adam',loss=losses, loss_weights=lossWeights)
model.summary()