【发布时间】:2018-07-22 09:33:04
【问题描述】:
我正在尝试为recall = (recall of class1 + recall of class2)/2 创建一个自定义宏。我想出了以下代码,但我不确定如何计算 0 类的真阳性。
def unweightedRecall():
def recall(y_true, y_pred):
# recall of class 1
true_positives1 = K.sum(K.round(K.clip(y_pred * y_true, 0, 1)))
possible_positives1 = K.sum(K.round(K.clip(y_true, 0, 1)))
recall1 = true_positives1 / (possible_positives1 + K.epsilon())
# --- get true positive of class 0 in true_positives0 here ---
# Also, is there a cleaner way to get possible_positives0
possible_positives0 = K.int_shape(y_true)[0] - possible_positives1
recall0 = true_positives0 / (possible_positives0 + K.epsilon())
return (recall0 + recall1)/2
return recall
看来我必须使用Keras.backend.equal(x, y),但是我如何创建一个形状为K.int_shape(y_true)[0] 和所有值的张量,比如x?
编辑 1
基于 Marcin 的 cmets,我想创建一个基于 keras 回调的自定义指标。在 browsing issues in Keras 时,我遇到了以下 f1 指标代码:
class Metrics(keras.callbacks.Callback):
def on_epoch_end(self, batch, logs={}):
predict = np.asarray(self.model.predict(self.validation_data[0]))
targ = self.validation_data[1]
self.f1s=f1(targ, predict)
return
metrics = Metrics()
model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_data=[X_test,y_test],
verbose=1, callbacks=[metrics])
但是回调如何返回准确性?我想实现unweighted recall = (recall class1 + recall class2)/2。我可以想到以下代码,但希望能帮助我完成它
from sklearn.metrics import recall_score
class Metrics(keras.callbacks.Callback):
def on_epoch_end(self, batch, logs={}):
predict = np.asarray(self.model.predict(self.validation_data[0]))
targ = self.validation_data[1]
# --- what to store the result in?? ---
self.XXXX=recall_score(targ, predict, average='macro')
# we really dont need to return anything ??
return
metrics = Metrics()
model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_data=[X_test,y_test],
verbose=1, callbacks=[metrics])
编辑 2:型号:
def createModelHelper(numNeurons=40, optimizer='adam'):
inputLayer = Input(shape=(data.shape[1],))
denseLayer1 = Dense(numNeurons)(inputLayer)
outputLayer = Dense(1, activation='sigmoid')(denseLayer1)
model = Model(input=inputLayer, output=outputLayer)
model.compile(loss=unweightedRecall, optimizer=optimizer)
return model
【问题讨论】:
-
使用
keras.metrics和keras.lossesAPI. Remember - that the final value of loss or metric is a mean across every batch - but forprecision` 和recall计算precision和recall时出现问题 - 批次间的平均值不等于最终值度量值。我建议您使用keras.callbacks来计算适当的值。 -
感谢您提供的信息! (自定义)回调的任何指针将不胜感激!如果为 (recall class1 + recall class2)/2 实现回调很容易,我将非常感谢您的回答:)
标签: tensorflow machine-learning keras backpropagation precision-recall