我希望建立一个具有自定义损失函数的模型,并遇到这篇文章Make a custom loss function in keras
def dice_coef(y_true, y_pred, smooth,thresh):
y_pred = y_pred>thresh #line with question
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(tf.cast(y_pred,tf.float32))
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection +smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def dice_loss(smooth,thresh):
def dice(y_true, y_pred):
return dice_coef(y_true, y_pred, smooth,thresh)
return dice
model = Sequential()
model.add(Dense(1, activation='sigmoid', input_dim=X_train_vectorized.shape[1]))
model.compile(optimizer='adam', loss=dice_loss(smooth=1e-5,thresh=0.5),
metrics=[metrics.mae, metrics.categorical_accuracy])
model.fit(X_train_vectorized, y_train, nb_epoch=5, validation_data=(X_test_vectorized, y_test))
当我在行上方运行时,y_pred = y_pred>thresh
将抛出错误,因为未定义渐变。我没有足够的声誉对原始帖子发表评论。
如何将预测的概率转换为二进制输出?谢谢。
答案 0 :(得分:1)
您可以收集满足您条件的预测:
y_pred = tf.gather(y_pred, tf.where(y_pred>thresh))
由于tf.gather是微分运算(它的行为就像是稀疏矩阵的乘法),因此您应该能够计算出损失,并且在反向传播错误时仅影响满足条件的值。