BinaryCrossentropy在词性标注和情感分析中经常出现。它的具体函数形式是:
具体的Python实现代码如下:
def binary_ce(a_v, p_v, logit): if logit: p_v = np.exp(p_v) / (1 + np.exp(p_v)) return -(a_v * np.log(p_v) + (1-a_v) * np.log(1 - p_v)) def binary_crossentropy(A, P, logit=False): return np.mean([binary_ce(a_i, p_i, logit) for a_i, p_i in zip(A, P)])
具体例子及对比,从tensorflow官网上我们获取以下信息:
# Example 1: (batch_size = 1, number of samples = 4) y_true = [0, 1, 0, 0] y_pred = [-18.6, 0.51, 2.94, -12.8] bce = tf.keras.losses.BinaryCrossentropy(from_logits=True) bce(y_true, y_pred).numpy() # 0.865
将上述例子带入自定义函数中得:
binary_crossentropy(y_true, y_pred, logit=True) # 0.8654579497810972,保留三位小数后得:0.865
可见自定义函数无误。
注释:
1. np为numpy的简写:import numpy as np
2. tf为tensorflow的简写:import tensorflow as tf
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)