| Stan Math Library 2.11.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_PRIM_MAT_FUN_LOG_SOFTMAX_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_LOG_SOFTMAX_HPP
3
4 #include <stan/math/prim/arr/err/check_nonzero_size.hpp>
5 #include <stan/math/prim/mat/fun/Eigen.hpp>
6 #include <stan/math/prim/mat/fun/log_sum_exp.hpp>
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;
47 using stan::math::log_sum_exp;
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
stan
Definition: log_sum_exp.hpp:8
stan::math::log
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:15
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
stan::math::log_sum_exp
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.hpp:14
stan::math::check_nonzero_size
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.
Definition: check_nonzero_size.hpp:30
stan::math::exp
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:10
Eigen.hpp
log_sum_exp.hpp
check_nonzero_size.hpp

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