I want to save the name of the loss function I used in my keras model. I looked into the documentation but haven't found a way to get this name. If possible I also want to save this name in case I use a custom loss function. Or at least extract the information from the model that I've used a custom loss function. This is what my model is looking like:
model = Sequential()
model.add(Dense(5, input_dim=4, activation='tanh'))
model.add(Dense(5, activation='tanh'))
model.add(Dense(5, activation='tanh'))
model.add(Dense(3))
model.compile(loss='mean_squared_error', optimizer='nadam', metrics=['accuracy'])
And for custom loss:
model.compile(loss=custom_loss, optimizer='nadam', metrics=['accuracy'])
The loss is saved as an attribute inside the model
object. I was not able to find it in the docs, I found it using dir(model)
. You can retrieve from the attribute the name of the loss function, a tf.keras.losses.Loss
instance or a custom callable.
model.compile(loss='mean_squared_error', optimizer='nadam', metrics=['accuracy'])
model.loss
>>> 'mean_squared_error'
model.compile(loss=tf.keras.losses.MeanSquaredError(), optimizer='nadam', metrics=['accuracy'])
model.loss
>>> <keras.losses.MeanSquaredError at 0x7f5d47ee4710>
def my_loss_fn(y_true, y_pred):
squared_difference = tf.square(y_true - y_pred)
return tf.reduce_mean(squared_difference, axis=-1)
model.compile(loss=my_loss_fn, optimizer='nadam', metrics=['accuracy'])
model.loss
>>> <function __main__.my_loss_fn>
you can still access the loss name as string in the last two cases of Santiago's answer:
for tf.keras.losses
objects: model.loss.name
for custom loss functions: model.loss.__name__
(this will return the variable name used to define the function)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.