Градиент функции потерь шарнира относительно входное предсказание

Для задания мне нужно реализовать как функцию расчета потерь на шарнире, так и ее частную производную. У меня есть сама функция потерь шарнира, но мне трудно понять, как вычислить ее частную производную по весу. вход для прогнозов. Я пробовал разные подходы, но ни один из них не работал.

Любая помощь, подсказки, предложения будут очень благодарны!

Вот аналитическое выражение для самой функции потерь шарнира:

Функция потери шарнира

А вот моя реализация функции потери шарнира:

def hinge_forward(target_pred, target_true):
    """Compute the value of Hinge loss 
        for a given prediction and the ground truth
    # Arguments
        target_pred: predictions - np.array of size `(n_objects,)`
        target_true: ground truth - np.array of size `(n_objects,)`
    # Output
        the value of Hinge loss 
        for a given prediction and the ground truth
        scalar
    """
    output = np.sum((np.maximum(0, 1 - target_pred * target_true)) / target_pred.size)

    return output

Теперь мне нужно рассчитать этот градиент:

Градиент потери шарнира относительно входных данных прогноза

Это то, что я пробовал для расчета градиента потерь в шарнире:

def hinge_grad_input(target_pred, target_true):
    """Compute the partial derivative 
        of Hinge loss with respect to its input
    # Arguments
        target_pred: predictions - np.array of size `(n_objects,)`
        target_true: ground truth - np.array of size `(n_objects,)`
    # Output
        the partial derivative 
        of Hinge loss with respect to its input
        np.array of size `(n_objects,)`
    """
# ----------------
#     try 1
# ----------------
#     hinge_result = hinge_forward(target_pred, target_true)

#     if hinge_result == 0:
#         grad_input = 0
#     else:
#         hinge = np.maximum(0, 1 - target_pred * target_true)
#         grad_input = np.zeros_like(hinge)
#         grad_input[hinge > 0] = 1
#         grad_input = np.sum(np.where(hinge > 0))
# ----------------
#     try 2
# ----------------
#     hinge = np.maximum(0, 1 - target_pred * target_true)
#     grad_input = np.zeros_like(hinge)

#     grad_input[hinge > 0] = 1
# ----------------
#     try 3
# ----------------
    hinge_result = hinge_forward(target_pred, target_true)

    if hinge_result == 0:
        grad_input = 0
    else:
        loss = np.maximum(0, 1 - target_pred * target_true)
        grad_input = np.zeros_like(loss)
        grad_input[loss > 0] = 1
        grad_input = np.sum(grad_input) * target_pred

    return grad_input

person Andrei    schedule 10.11.2018    source источник


Ответы (1)


Мне удалось решить эту проблему с помощью функции np.where (). Вот код:

def hinge_grad_input(target_pred, target_true):
    """Compute the partial derivative 
        of Hinge loss with respect to its input
    # Arguments
        target_pred: predictions - np.array of size `(n_objects,)`
        target_true: ground truth - np.array of size `(n_objects,)`
    # Output
        the partial derivative 
        of Hinge loss with respect to its input
        np.array of size `(n_objects,)`
    """
    grad_input = np.where(target_pred * target_true < 1, -target_true / target_pred.size, 0)

    return grad_input

Обычно градиент равен -y / N для всех случаев, когда y * y ‹1, в противном случае - 0.

person Andrei    schedule 11.11.2018