Stan  1.3
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Pages
softmax.hpp
Go to the documentation of this file.
1 #ifndef __STAN__MATH__FUNCTIONS__SOFTMAX_HPP__
2 #define __STAN__MATH__FUNCTIONS__SOFTMAX_HPP__
3 
4 #include <boost/math/tools/promotion.hpp>
5 #include <stdexcept>
6 #include <boost/throw_exception.hpp>
7 
8 namespace stan {
9  namespace math {
10 
11  // hide helper for now; could use Eigen here
12  namespace {
13  template <typename Vector, typename Scalar>
14  Scalar maximum(const Vector& x) {
15  if(x.size() == 0)
16  BOOST_THROW_EXCEPTION(std::invalid_argument ("x must have at least one element"));
17  Scalar max_x(x[0]);
18  for (typename Vector::size_type i = 1; i < x.size(); ++i)
19  if (x[i] < max_x)
20  max_x = x[i];
21  return max_x;
22  }
23  }
24 
74  template <typename Vector, typename Scalar>
75  void softmax(const Vector& x, Vector& simplex) {
76  using std::exp;
77  if (x.size() != simplex.size())
78  BOOST_THROW_EXCEPTION(std::invalid_argument ("x.size() != simplex.size()"));
79  Scalar sum(0.0);
80  Scalar max_x = maximum<Vector,Scalar>(x);
81  for (typename Vector::size_type i = 0; i < x.size(); ++i) {
82  simplex[i] = exp(x[i]-max_x);
83  sum += simplex[i];
84  }
85  for (typename Vector::size_type i = 0; i < x.size(); ++i)
86  simplex[i] /= sum;
87  }
88 
89  }
90 }
91 
92 #endif

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