All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Groups
log_softmax.hpp
Go to the documentation of this file.
#ifndef STAN_MATH_PRIM_MAT_FUN_LOG_SOFTMAX_HPP
#define STAN_MATH_PRIM_MAT_FUN_LOG_SOFTMAX_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/log_sum_exp.hpp>
#include <stan/math/prim/scal/err/check_nonzero_size.hpp>
#include <cmath>
#include <sstream>
#include <stdexcept>
namespace stan {
namespace math {
template <typename T>
inline Eigen::Matrix<T, Eigen::Dynamic, 1>
log_softmax(const Eigen::Matrix<T, Eigen::Dynamic, 1>& v) {
using std::exp;
using std::log;
using stan::math::log_sum_exp;
stan::math::check_nonzero_size("log_softmax", "v", v);
Eigen::Matrix<T, Eigen::Dynamic, 1> theta(v.size());
T z = log_sum_exp(v);
for (int i = 0; i < v.size(); ++i)
theta(i) = v(i) - z;
return theta;
// T sum(0.0);
// T max_v = v.maxCoeff();
// for (int i = 0; i < v.size(); ++i)
// sum += exp(v(i) - max_v); // log_sum_exp trick
// T log_sum = log(sum);
// for (int i = 0; i < v.size(); ++i)
// theta(i) = (v(i) - max_v) - log_sum;
// return theta;
}
}
}
#endif
stan::math::log
fvar< T > log(const fvar< T > &x)
Definition: log.hpp:15
stan::math::log_softmax
Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > log_softmax(const Eigen::Matrix< fvar< T >, Eigen::Dynamic, 1 > &alpha)
Definition: log_softmax.hpp:16
stan::math::log_sum_exp
fvar< T > log_sum_exp(const std::vector< fvar< T > > &v)
Definition: log_sum_exp.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
log_sum_exp.hpp
check_nonzero_size.hpp

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