1 #ifndef STAN_MATH_PRIM_FUN_BINARY_LOG_LOSS_HPP
2 #define STAN_MATH_PRIM_FUN_BINARY_LOG_LOSS_HPP
3 
4 #include <stan/math/prim/meta.hpp>
5 #include <stan/math/prim/fun/log.hpp>
6 #include <stan/math/prim/fun/log1m.hpp>
7 #include <stan/math/prim/functor/apply_scalar_binary.hpp>
8 #include <cmath>
9 
10 namespace stan {
11 namespace math {
12 
13 /**
14  * Returns the log loss function for binary classification
15  * with specified reference and response values.
16  *
17  * The log loss function for prediction \f$\hat{y} \in [0, 1]\f$
18  * given outcome \f$y \in \{ 0, 1 \}\f$ is
19  *
20  * \f$\mbox{logloss}(1, \hat{y}) = -\log \hat{y} \f$, and
21  *
22  * \f$\mbox{logloss}(0, \hat{y}) = -\log (1 - \hat{y}) \f$.
23  *
24  * @tparam T value type
25  * @param[in] y reference value, either 0 or 1
26  * @param[in] y_hat response value in [0, 1]
27  * @return Log loss for response given reference value
28  */
29 template <typename T, require_arithmetic_t<T>* = nullptr>
binary_log_loss(int y,const T & y_hat)30 inline T binary_log_loss(int y, const T& y_hat) {
31   using std::log;
32   return y ? -log(y_hat) : -log1m(y_hat);
33 }
34 
35 /**
36  * Enables the vectorised application of the binary log loss function, when
37  * the first and/or second arguments are containers.
38  *
39  * @tparam T1 type of first input
40  * @tparam T2 type of second input
41  * @param a First input
42  * @param b Second input
43  * @return Binary log loss function applied to the two inputs.
44  */
45 template <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr,
46           require_not_var_matrix_t<T2>* = nullptr>
binary_log_loss(const T1 & a,const T2 & b)47 inline auto binary_log_loss(const T1& a, const T2& b) {
48   return apply_scalar_binary(a, b, [&](const auto& c, const auto& d) {
49     return binary_log_loss(c, d);
50   });
51 }
52 
53 }  // namespace math
54 }  // namespace stan
55 
56 #endif
57