All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Groups
softmax.hpp
Go to the documentation of this file.
#ifndef STAN_MATH_PRIM_MAT_FUN_SOFTMAX_HPP
#define STAN_MATH_PRIM_MAT_FUN_SOFTMAX_HPP
#include <stan/math/prim/scal/err/check_nonzero_size.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <cmath>
namespace stan {
namespace math {
template <typename T>
inline Eigen::Matrix<T, Eigen::Dynamic, 1>
softmax(const Eigen::Matrix<T, Eigen::Dynamic, 1>& v) {
using std::exp;
stan::math::check_nonzero_size("softmax", "v", v);
Eigen::Matrix<T, Eigen::Dynamic, 1> theta(v.size());
T sum(0.0);
T max_v = v.maxCoeff();
for (int i = 0; i < v.size(); ++i) {
theta(i) = exp(v(i) - max_v); // extra work for (v[i] == max_v)
sum += theta(i); // extra work vs. sum() w. auto-diff
}
for (int i = 0; i < v.size(); ++i)
theta(i) /= sum;
return theta;
}
}
}
#endif
stan::math::sum
fvar< T > sum(const std::vector< fvar< T > > &m)
Return the sum of the entries of the specified standard vector.
Definition: sum.hpp:20
stan::math::softmax
Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > softmax(const Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > &alpha)
Definition: softmax.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:31
stan::math::exp
fvar< T > exp(const fvar< T > &x)
Definition: exp.hpp:10
Eigen.hpp
check_nonzero_size.hpp

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