Stan Math Library  2.9.0
reverse mode automatic differentiation
log_softmax.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_LOG_SOFTMAX_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_LOG_SOFTMAX_HPP
3 
7 #include <cmath>
8 #include <sstream>
9 #include <stdexcept>
10 
11 namespace stan {
12  namespace math {
13 
42  template <typename T>
43  inline Eigen::Matrix<T, Eigen::Dynamic, 1>
44  log_softmax(const Eigen::Matrix<T, Eigen::Dynamic, 1>& v) {
45  using std::exp;
46  using std::log;
48  stan::math::check_nonzero_size("log_softmax", "v", v);
49  Eigen::Matrix<T, Eigen::Dynamic, 1> theta(v.size());
50  T z = log_sum_exp(v);
51  for (int i = 0; i < v.size(); ++i)
52  theta(i) = v(i) - z;
53  return theta;
54  // T sum(0.0);
55  // T max_v = v.maxCoeff();
56  // for (int i = 0; i < v.size(); ++i)
57  // sum += exp(v(i) - max_v); // log_sum_exp trick
58  // T log_sum = log(sum);
59  // for (int i = 0; i < v.size(); ++i)
60  // theta(i) = (v(i) - max_v) - log_sum;
61  // return theta;
62  }
63 
64  }
65 }
66 #endif
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:15
Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > log_softmax(const Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > &alpha)
Definition: log_softmax.hpp:16
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.hpp:14
bool check_nonzero_size(const char *function, const char *name, const T_y &y)
Return true if the specified matrix/vector is of non-zero size.
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:10

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