| Stan Math Library 2.12.0 reverse mode automatic differentiation

- Main Page
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

log_softmax.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_FWD_MAT_FUN_LOG_SOFTMAX_HPP
2 #define STAN_MATH_FWD_MAT_FUN_LOG_SOFTMAX_HPP
3
4 #include <stan/math/fwd/core.hpp>
5 #include <stan/math/fwd/mat/fun/softmax.hpp>
6 #include <stan/math/prim/mat/fun/Eigen.hpp>
7 #include <stan/math/prim/mat/fun/log_softmax.hpp>
8 #include <stan/math/prim/mat/fun/softmax.hpp>
9
10 namespace stan {
11 namespace math {
12
13 template <typename T>
14 inline
15 Eigen::Matrix<fvar<T>, Eigen::Dynamic, 1>
16 log_softmax(const Eigen::Matrix<fvar<T>, Eigen::Dynamic, 1>& alpha) {
17 using Eigen::Matrix;
18 using Eigen::Dynamic;
19
20 Matrix<T, Dynamic, 1> alpha_t(alpha.size());
21 for (int k = 0; k < alpha.size(); ++k)
22 alpha_t(k) = alpha(k).val_;
23
24 Matrix<T, Dynamic, 1> softmax_alpha_t = softmax(alpha_t);
25 Matrix<T, Dynamic, 1> log_softmax_alpha_t = log_softmax(alpha_t);
26
27 Matrix<fvar<T>, Dynamic, 1> log_softmax_alpha(alpha.size());
28 for (int k = 0; k < alpha.size(); ++k) {
29 log_softmax_alpha(k).val_ = log_softmax_alpha_t(k);
30 log_softmax_alpha(k).d_ = 0;
31 }
32
33 for (int m = 0; m < alpha.size(); ++m) {
34 T negative_alpha_m_d_times_softmax_alpha_t_m
35 = - alpha(m).d_ * softmax_alpha_t(m);
36 for (int k = 0; k < alpha.size(); ++k) {
37 if (m == k)
38 log_softmax_alpha(k).d_
39 += alpha(m).d_
40 + negative_alpha_m_d_times_softmax_alpha_t_m;
41 else
42 log_softmax_alpha(k).d_
43 += negative_alpha_m_d_times_softmax_alpha_t_m;
44 }
45 }
46
47 return log_softmax_alpha;
48 }
49
50 }
51 }
52 #endif
core.hpp
stan::math::softmax
Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > softmax(const Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > &alpha)
Definition: softmax.hpp:14
stan
Definition: log_sum_exp.hpp:8
softmax.hpp
stan::math::log_softmax
Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > log_softmax(const Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > &alpha)
Definition: log_softmax.hpp:16
softmax.hpp
Eigen.hpp
log_softmax.hpp
stan::math::fvar
Definition: fvar.hpp:12

[ Stan Home Page ] © 2011–2016, Stan Development Team.