keras 自定义 metrics

本文详细介绍如何在Keras中自定义评估指标,包括精度、召回率、F1分数等,通过具体函数实现并整合到模型编译过程,提升模型评估的灵活性与准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义 Metrics

keras 中操作的均为 Tensor 对象,因此,需要定义操作 Tensor 的函数来操作所有输出结果,定义好函数之后,直接将其放在 model.compile 函数 metrics 中即可生效:

def precision(y_true, y_pred):
    # Calculates the precision
    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


def recall(y_true, y_pred):
    # Calculates the recall
    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 fbeta_score(y_true, y_pred, beta=1):
    # Calculates the F score, the weighted harmonic mean of precision and recall.

    if beta < 0:
        raise ValueError('The lowest choosable beta is zero (only precision).')
        
    # If there are no true positives, fix the F score at 0 like sklearn.
    if K.sum(K.round(K.clip(y_true, 0, 1))) == 0:
        return 0

    p = precision(y_true, y_pred)
    r = recall(y_true, y_pred)
    bb = beta ** 2
    fbeta_score = (1 + bb) * (p * r) / (bb * p + r + K.epsilon())
    return fbeta_score

def fmeasure(y_true, y_pred):
    # Calculates the f-measure, the harmonic mean of precision and recall.
    return fbeta_score(y_true, y_pred, beta=1)

使用方法如下:

model.compile( 
    optimizer=Adam(), 
    loss='binary_crossentropy',
    metrics = ['accuracy',  fmeasure, recall, precision])

参考

custom metrics for binary classification in Keras

### 如何在 Keras 模型编译过程中设置评估指标 在 Keras 中,`compile` 方法允许开发者指定模型的优化器、损失函数以及评估指标。这些参数共同定义了模型的学习目标及其性能衡量标准。当调用 `model.compile()` 时,可以通过传递一个字符串列表或自定义函数来配置评估指标。 #### 使用内置评估指标 Keras 提供了许多常用的内置评估指标,可以直接通过名称作为字符串传入到 `metrics` 参数中。例如: ```python from tensorflow import keras model = keras.Sequential([ keras.layers.Dense(64, activation='relu', input_shape=(784,)), keras.layers.Dense(10, activation='softmax') ]) model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'] # 设置评估指标为 accuracy ) ``` 上述代码片段展示了如何将 `accuracy` 设定为模型的评估指标[^5]。 #### 自定义评估指标 如果内置的评估指标无法满足需求,还可以创建自定义评估指标并将其应用于模型。以下是实现方法的一个例子: ```python import tensorflow as tf def custom_metric(y_true, y_pred): correct_predictions = tf.equal(tf.argmax(y_true, axis=-1), tf.argmax(y_pred, axis=-1)) return tf.reduce_mean(tf.cast(correct_predictions, tf.float32)) model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=[custom_metric] # 将自定义评估指标应用到模型中 ) ``` 此示例说明了如何编写和集成自定义评估逻辑。 #### 多输出模型中的评估指标 对于多输出模型,可以分别为每个输出设定不同的评估指标。这使得复杂任务(如联合分类与回归)更加灵活可控。 ```python input_layer = keras.Input(shape=(784,)) output_classification = keras.layers.Dense(10, activation='softmax')(input_layer) output_regression = keras.layers.Dense(1)(input_layer) model = keras.Model(inputs=input_layer, outputs=[output_classification, output_regression]) model.compile( optimizer=keras.optimizers.Adam(), loss={'dense': 'categorical_crossentropy', 'dense_1': 'mse'}, metrics={ 'dense': ['accuracy'], # 针对第一个输出设置 accuracy 'dense_1': ['mae'] # 针对第二个输出设置 mean absolute error (MAE) } ) ``` 这段代码演示了针对不同输出层分别指定适合它们特性的评价方式。 #### 错误处理机制 需要注意的是,在配置 `optimizer`, `loss`, 或者 `metrics` 过程中如果有错误发生,则会抛出异常提示具体问题所在位置。比如输入非法参数将会引发 `ValueError` 异常[^2]。 --- ###
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值