Stan  2.5.0
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
softmax.hpp
Go to the documentation of this file.
1 #ifndef STAN__MATH__MATRIX__SOFTMAX_HPP
2 #define STAN__MATH__MATRIX__SOFTMAX_HPP
3 
5 #include <cmath>
7 
8 namespace stan {
9  namespace math {
10 
44  template <typename T>
45  inline Eigen::Matrix<T,Eigen::Dynamic,1>
46  softmax(const Eigen::Matrix<T,Eigen::Dynamic,1>& v) {
47  using std::exp;
48  stan::math::check_nonzero_size("softmax(%1%)",v,"v",(double*)0);
49  Eigen::Matrix<T,Eigen::Dynamic,1> theta(v.size());
50  T sum(0.0);
51  T max_v = v.maxCoeff();
52  for (int i = 0; i < v.size(); ++i) {
53  theta(i) = exp(v(i) - max_v); // extra work for (v[i] == max_v)
54  sum += theta(i); // extra work vs. sum() w. auto-diff
55  }
56  for (int i = 0; i < v.size(); ++i)
57  theta(i) /= sum;
58  return theta;
59  }
60 
61  }
62 }
63 #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< T, Rows, Cols > exp(const Eigen::Matrix< T, Rows, Cols > &m)
Return the element-wise exponentiation of the matrix or vector.
Definition: exp.hpp:18
double sum(std::vector< double > &x)
Definition: sum.hpp:10
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.