Stan  2.5.0
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
log_softmax.hpp
Go to the documentation of this file.
1 #ifndef STAN__AGRAD__FWD__MATRIX__LOG_SOFTMAX_HPP
2 #define STAN__AGRAD__FWD__MATRIX__LOG_SOFTMAX_HPP
3 
9 
10 namespace stan {
11  namespace agrad {
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 stan::math::softmax;
19  using Eigen::Matrix;
20  using Eigen::Dynamic;
21 
22  Matrix<T,Dynamic,1> alpha_t(alpha.size());
23  for (int k = 0; k < alpha.size(); ++k)
24  alpha_t(k) = alpha(k).val_;
25 
26  Matrix<T,Dynamic,1> softmax_alpha_t = softmax(alpha_t);
27  Matrix<T,Dynamic,1> log_softmax_alpha_t = log_softmax(alpha_t);
28 
29  Matrix<fvar<T>,Dynamic,1> log_softmax_alpha(alpha.size());
30  for (int k = 0; k < alpha.size(); ++k) {
31  log_softmax_alpha(k).val_ = log_softmax_alpha_t(k);
32  log_softmax_alpha(k).d_ = 0;
33  }
34 
35  // for each input position
36  for (int m = 0; m < alpha.size(); ++m) {
37  T negative_alpha_m_d_times_softmax_alpha_t_m
38  = - alpha(m).d_ * softmax_alpha_t(m);
39  // for each output position
40  for (int k = 0; k < alpha.size(); ++k) {
41  // chain from input to output
42  if (m == k)
43  log_softmax_alpha(k).d_
44  += alpha(m).d_
45  + negative_alpha_m_d_times_softmax_alpha_t_m;
46  else
47  log_softmax_alpha(k).d_
48  += negative_alpha_m_d_times_softmax_alpha_t_m;
49  }
50  }
51 
52  return log_softmax_alpha;
53  }
54 
55 
56  }
57 }
58 
59 #endif
Eigen::Matrix< T, Eigen::Dynamic, 1 > softmax(const Eigen::Matrix< T, Eigen::Dynamic, 1 > &v)
Return the softmax of the specified vector.
Definition: softmax.hpp:46
Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > log_softmax(const Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > &alpha)
Definition: log_softmax.hpp:16
Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > softmax(const Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > &alpha)
Definition: softmax.hpp:14
Eigen::Matrix< T, Eigen::Dynamic, 1 > log_softmax(const Eigen::Matrix< T, Eigen::Dynamic, 1 > &v)
Return the natural logarithm of the softmax of the specified vector.
Definition: log_softmax.hpp:44

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