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__MATH__MATRIX__LOG_SOFTMAX_HPP
2 #define STAN__MATH__MATRIX__LOG_SOFTMAX_HPP
3 
4 #include <cmath>
5 #include <sstream>
6 #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(%1%)",v,"v", (double*)0);
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
boost::math::tools::promote_args< T1, T2 >::type log_sum_exp(const T2 &a, const T1 &b)
Calculates the log sum of exponetials without overflow.
Definition: log_sum_exp.hpp:49
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
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:15
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:16
bool check_nonzero_size(const char *function, const T_y &y, const char *name, T_result *result)
Return true if the specified matrix/vector is of non-zero size.

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