我有一个用于计算两个数组(y_pred和y_actual)比较的负预测值的代码:
def npv(y_pred, y_actual): tn = 0 fn = 0 negative_value = 1 for i in range(0,len(y_actual)): if(y_pred[i] == negative_value): if(y_pred[i] == y_actual[i]): tn += 1 else: fn += 1 result = tn / (tn + fn) return result
但我想用张量实现它,以便在Python中使用Keras深度学习循环神经网络时用作自定义指标。
我该怎么做呢?
回答:
我尝试使用简单的Tensorflow编写指标。它设计用于二分类任务
def npv(y_actual, y_pred): negative_value = 1. if y_pred.shape[-1]==2: # 最后一层激活函数:二分类时的softmax y_actual = tf.cast(tf.argmax(y_actual, -1), tf.float32) # 获取真实类别 y_pred = tf.cast(tf.argmax(y_pred, -1), tf.float32) # 获取预测类别 else: # 最后一层激活函数:二分类时的sigmoid y_pred = tf.round(y_pred) # 四舍五入概率 # 如果(y_pred == negative_value)并且(y_pred == negative_value) tn = tf.reduce_sum(tf.cast(tf.logical_and(tf.equal(y_pred, negative_value), tf.equal(y_pred, y_actual)), tf.float32)) # 如果(y_pred == negative_value)并且(y_pred != negative_value) fn = tf.reduce_sum(tf.cast(tf.logical_and(tf.equal(y_pred, negative_value), tf.not_equal(y_pred, y_actual)), tf.float32)) result = tn / ((tn + fn) + K.epsilon()) # 添加epsilon以避免NaN return result
这是一个二分类任务的示例
X = np.random.uniform(0,1, (100,3))y = np.random.randint(0,2, 100)inp = Input((3))x = Dense(10, activation='relu')(inp)x = Dense(1, activation='sigmoid')(x)model = Model(inp, x)model.compile('adam', 'binary_crossentropy', metrics=npv)model.fit(X,y, epochs=10)