Automatic Differentiation
 
Loading...
Searching...
No Matches
softmax.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_FWD_FUN_SOFTMAX_HPP
2#define STAN_MATH_FWD_FUN_SOFTMAX_HPP
3
9
10namespace stan {
11namespace math {
12
13template <typename ColVec,
14 require_eigen_col_vector_vt<is_fvar, ColVec>* = nullptr>
15inline auto softmax(const ColVec& alpha) {
16 using Eigen::Dynamic;
17 using Eigen::Matrix;
18 using T = typename value_type_t<ColVec>::Scalar;
19 if (alpha.size() == 0) {
20 return Matrix<fvar<T>, Dynamic, 1>();
21 }
22 const auto& alpha_ref = to_ref(alpha);
23
24 Matrix<T, Dynamic, 1> softmax_alpha_t = softmax(value_of(alpha_ref));
25
26 Matrix<fvar<T>, Dynamic, 1> softmax_alpha(alpha.size());
27 for (int k = 0; k < alpha.size(); ++k) {
28 softmax_alpha.coeffRef(k).val_ = softmax_alpha_t.coeff(k);
29 softmax_alpha.coeffRef(k).d_ = 0;
30 }
31
32 for (int m = 0; m < alpha.size(); ++m) {
33 T negative_alpha_m_d_times_softmax_alpha_t_m
34 = -alpha_ref.coeff(m).d_ * softmax_alpha_t.coeff(m);
35 for (int k = 0; k < alpha.size(); ++k) {
36 if (m == k) {
37 softmax_alpha.coeffRef(k).d_
38 += softmax_alpha_t.coeff(k)
39 * (alpha_ref.coeff(m).d_
40 + negative_alpha_m_d_times_softmax_alpha_t_m);
41 } else {
42 softmax_alpha.coeffRef(k).d_
43 += softmax_alpha_t.coeff(k)
44 * negative_alpha_m_d_times_softmax_alpha_t_m;
45 }
46 }
47 }
48
49 return softmax_alpha;
50}
51
52} // namespace math
53} // namespace stan
54#endif
typename value_type< T >::type value_type_t
Helper function for accessing underlying type.
auto softmax(const ColVec &alpha)
Definition softmax.hpp:15
T value_of(const fvar< T > &v)
Return the value of the specified variable.
Definition value_of.hpp:18
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...