Creating custom metrics
As simple callables (stateless)
Much like loss functions, any callable with signature metric_fn(y_true, y_pred) that returns an array of losses (one of sample in the input batch) can be passed to compile() as a metric. Note that sample weighting is automatically supported for any such metric.
Here's a simple example:
def my_metric_fn(y_true, y_pred):
squared_difference = tf.square(y_true - y_pred)
return tf.reduce_mean(squared_difference, axis=-1) # Note the axis=-1
model.compile(optimizer='adam', loss='mean_squared_error', metrics=[my_metric_fn])
In this case, the scalar metric value you are tracking during training and evaluation is the average of the per-batch metric values for all batches see during a given epoch (or during a given call to model.evaluate()).
出自keras官方文档的原话,看得我欲仙欲死,麻烦懂的前辈简单翻译一下,然后
我有2个问题想请教各位前辈:
1.keras自定义评价指标函数(y_true,y_pred)中的y_true和y_pred是所有样本放进模型后得到的值吗?还是只是说一个样本的值
2..keras自定义评价指标函数,要求retun的是一个标量还是一个向量
由于这几天在做一个多标签分类的项目,老板又催得急,看了官方文档,英语水平不好,又看不懂,特来请教
有时候训练模型,现有的评估函数并不足以科学的评估模型的好坏,这时候就需要自定义一些评估函数,比如样本分布不均衡是准确率accuracy评估无法判定一个模型的好坏,这时候需要引入精确度和召回率作为评估标准,不幸的是keras没有这些评估函数。以下是参考别的文章摘取的两个自定义评估函数
召回率:
def recall(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
精确度:
def precision(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
自定义了评估函数,一般在编译模型阶段加入即可:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy', precision, recall])
自定义了损失函数focal_loss一般也在编译阶段加入:
model.compile(optimizer=Adam(lr=0.0001), loss=[focal_loss],
metrics=['accuracy',fbeta_score], )
其他的没有特别要注意的点,直接按照原来的思路训练一版模型出来就好了,关键的地方在于加载模型这里,自定义的函数需要特殊的加载方式,不然会出现加载没有自定义函数的问题:ValueError: Unknown loss function:focal_loss
解决方案:
model_name = 'test_calssification_model.h5'
model_dfcw = load_model(model_name,
custom_objects={'focal_loss': focal_loss,'fbeta_score':fbeta_score})
注意点:将自定义的损失函数和评估函数都加入到custom_objects里,以上就是在自定义一个损失函数从编译模型阶段到加载模型阶段出现的所有的问题。