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__MATRIX__SOFTMAX_HPP__
2 #define __STAN__MATH__MATRIX__SOFTMAX_HPP__
3 
6 
7 namespace stan {
8  namespace math {
9 
16  template <typename T>
17  inline Eigen::Matrix<T,Eigen::Dynamic,1>
18  softmax(const Eigen::Matrix<T,Eigen::Dynamic,1>& v) {
19  using std::exp;
20  stan::math::validate_nonzero_size(v,"vector softmax");
21  Eigen::Matrix<T,Eigen::Dynamic,1> theta(v.size());
22  T sum(0.0);
23  T max_v = v.maxCoeff();
24  for (int i = 0; i < v.size(); ++i) {
25  theta[i] = exp(v[i] - max_v);
26  sum += theta[i];
27  }
28  for (int i = 0; i < v.size(); ++i)
29  theta[i] /= sum;
30  return theta;
31  }
32 
33  }
34 }
35 #endif

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