| Stan Math Library 2.11.0 reverse mode automatic differentiation

- Main Page
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

softmax.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_FWD_MAT_FUN_SOFTMAX_HPP
2 #define STAN_MATH_FWD_MAT_FUN_SOFTMAX_HPP
3
4 #include <stan/math/fwd/core.hpp>
5 #include <stan/math/prim/mat/fun/Eigen.hpp>
6 #include <stan/math/prim/mat/fun/softmax.hpp>
7
8 namespace stan {
9 namespace math {
10
11 template <typename T>
12 inline
13 Eigen::Matrix<fvar<T>, Eigen::Dynamic, 1>
14 softmax(const Eigen::Matrix<fvar<T>, Eigen::Dynamic, 1>& alpha) {
15 using stan::math::softmax;
16 using Eigen::Matrix;
17 using Eigen::Dynamic;
18
19 Matrix<T, Dynamic, 1> alpha_t(alpha.size());
20 for (int k = 0; k < alpha.size(); ++k)
21 alpha_t(k) = alpha(k).val_;
22
23 Matrix<T, Dynamic, 1> softmax_alpha_t = softmax(alpha_t);
24
25 Matrix<fvar<T>, Dynamic, 1> softmax_alpha(alpha.size());
26 for (int k = 0; k < alpha.size(); ++k) {
27 softmax_alpha(k).val_ = softmax_alpha_t(k);
28 softmax_alpha(k).d_ = 0;
29 }
30
31 // for each input position
32 for (int m = 0; m < alpha.size(); ++m) {
33 // for each output position
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 // chain from input to output
38 if (m == k) {
39 softmax_alpha(k).d_
40 += softmax_alpha_t(k)
41 * (alpha(m).d_
42 + negative_alpha_m_d_times_softmax_alpha_t_m);
43 } else {
44 softmax_alpha(k).d_
45 += negative_alpha_m_d_times_softmax_alpha_t_m
46 * softmax_alpha_t(k);
47 }
48 }
49 }
50
51 return softmax_alpha;
52 }
53
54
55 }
56 }
57
58 #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
Eigen.hpp
stan::math::fvar
Definition: fvar.hpp:13

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