Automatic Differentiation
 
Loading...
Searching...
No Matches
categorical_logit_glm_lpmf.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_GLM_LPMF_HPP
2#define STAN_MATH_PRIM_PROB_CATEGORICAL_LOGIT_GLM_LPMF_HPP
3
20#include <cmath>
21
22namespace stan {
23namespace math {
24
45template <bool propto, typename T_y, typename T_x, typename T_alpha,
46 typename T_beta, require_matrix_t<T_x>* = nullptr,
47 require_col_vector_t<T_alpha>* = nullptr,
48 require_matrix_t<T_beta>* = nullptr>
50 const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta) {
51 using T_partials_return = partials_return_t<T_x, T_alpha, T_beta>;
52 using Eigen::Array;
53 using Eigen::Dynamic;
54 using Eigen::Matrix;
55 using std::exp;
56 using std::isfinite;
57 using std::log;
58 using T_y_ref = ref_type_t<T_y>;
59 using T_x_ref = ref_type_if_not_constant_t<T_x>;
60 using T_alpha_ref = ref_type_if_not_constant_t<T_alpha>;
61 using T_beta_ref = ref_type_if_not_constant_t<T_beta>;
62 using T_beta_partials = partials_type_t<scalar_type_t<T_beta>>;
63 constexpr int T_x_rows = T_x::RowsAtCompileTime;
64
65 const size_t N_instances = T_x_rows == 1 ? stan::math::size(y) : x.rows();
66 const size_t N_attributes = x.cols();
67 const size_t N_classes = beta.cols();
68
69 static constexpr const char* function = "categorical_logit_glm_lpmf";
70 check_consistent_size(function, "Vector of dependent variables", y,
71 N_instances);
72 check_consistent_size(function, "Intercept vector", alpha, N_classes);
73 check_size_match(function, "x.cols()", N_attributes, "beta.rows()",
74 beta.rows());
75 if (size_zero(y) || N_classes == 1) {
76 return 0;
77 }
78 T_y_ref y_ref = y;
79 check_bounded(function, "categorical outcome out of support", y_ref, 1,
80 N_classes);
81
83 return 0;
84 }
85
86 T_x_ref x_ref = x;
87 T_alpha_ref alpha_ref = alpha;
88 T_beta_ref beta_ref = beta;
89
90 const auto& x_val = to_ref_if<is_autodiff_v<T_beta>>(value_of(x_ref));
91 const auto& alpha_val = value_of(alpha_ref);
92 const auto& beta_val = to_ref_if<is_autodiff_v<T_x>>(value_of(beta_ref));
93
94 const auto& alpha_val_vec = as_column_vector_or_scalar(alpha_val).transpose();
95
96 Array<T_partials_return, T_x_rows, Dynamic> lin;
97 if constexpr (T_x_rows == 1 && T_beta::ColsAtCompileTime == 1) {
98 lin = dot_product(x_val, beta_val) + alpha_val_vec.array();
99 } else {
100 lin = multiply(x_val, beta_val).rowwise() + alpha_val_vec;
101 }
102 Array<T_partials_return, T_x_rows, 1> lin_max
103 = lin.rowwise().maxCoeff(); // This is used to prevent overflow when
104 // calculating softmax/log_sum_exp and
105 // similar expressions
106 Array<T_partials_return, T_x_rows, Dynamic> exp_lin
107 = exp(lin.colwise() - lin_max);
108 Array<T_partials_return, T_x_rows, 1> inv_sum_exp_lin
109 = 1 / exp_lin.rowwise().sum();
110
111 T_partials_return logp = log(inv_sum_exp_lin).sum() - lin_max.sum();
112 if constexpr (T_x_rows == 1) {
113 logp *= N_instances;
114 }
115 scalar_seq_view<T_y_ref> y_seq(y_ref);
116 for (int i = 0; i < N_instances; i++) {
117 if constexpr (T_x_rows == 1) {
118 logp += lin(0, y_seq[i] - 1);
119 } else {
120 logp += lin(i, y_seq[i] - 1);
121 }
122 }
123 // TODO(Tadej) maybe we can replace previous block with the following line
124 // when we have newer Eigen T_partials_return logp =
125 // lin(Eigen::all,y-1).sum() + log(inv_sum_exp_lin).sum() - lin_max.sum();
126
127 if (!isfinite(logp)) {
128 check_finite(function, "Weight vector", beta_ref);
129 check_finite(function, "Intercept", alpha_ref);
130 check_finite(function, "Matrix of independent variables", x_ref);
131 }
132
133 // Compute the derivatives.
134 auto ops_partials = make_partials_propagator(x_ref, alpha_ref, beta_ref);
135
136 if constexpr (is_autodiff_v<T_x>) {
137 if constexpr (T_x_rows == 1) {
138 Array<T_beta_partials, 1, Dynamic> beta_y = beta_val.col(y_seq[0] - 1);
139 for (int i = 1; i < N_instances; i++) {
140 beta_y += beta_val.col(y_seq[i] - 1).array();
141 }
142 if constexpr (T_beta::RowsAtCompileTime == 1) {
143 edge<0>(ops_partials).partials_
144 = beta_y
145 - dot_product(exp_lin.matrix(), beta_val) * inv_sum_exp_lin
146 * N_instances;
147 } else {
148 edge<0>(ops_partials).partials_
149 = beta_y
150 - multiply(exp_lin.matrix(), beta_val.transpose())
151 .array()
152 .colwise()
153 * inv_sum_exp_lin * N_instances;
154 }
155 } else {
156 Array<T_beta_partials, Dynamic, Dynamic> beta_y(N_instances,
157 N_attributes);
158 for (int i = 0; i < N_instances; i++) {
159 beta_y.row(i) = beta_val.col(y_seq[i] - 1);
160 }
161 edge<0>(ops_partials).partials_
162 = beta_y
163 - multiply(exp_lin.matrix(), beta_val.transpose()).array().colwise()
164 * inv_sum_exp_lin;
165 // TODO(Tadej) maybe we can replace previous block with the following
166 // line when we have newer Eigen partials<0>(ops_partials) = beta_val(y
167 // - 1, all) - (exp_lin.matrix() * beta.transpose()).colwise() *
168 // inv_sum_exp_lin;
169 }
170 }
171 if constexpr (is_any_autodiff_v<T_alpha, T_beta>) {
172 Array<T_partials_return, T_x_rows, Dynamic> neg_softmax_lin
173 = exp_lin.colwise() * -inv_sum_exp_lin;
174 if constexpr (is_autodiff_v<T_alpha>) {
175 if constexpr (T_x_rows == 1) {
176 edge<1>(ops_partials).partials_
177 = neg_softmax_lin.colwise().sum() * N_instances;
178 } else {
179 partials<1>(ops_partials) = neg_softmax_lin.colwise().sum();
180 }
181 for (int i = 0; i < N_instances; i++) {
182 partials<1>(ops_partials)[y_seq[i] - 1] += 1;
183 }
184 }
185 if constexpr (is_autodiff_v<T_beta>) {
186 Matrix<T_partials_return, Dynamic, Dynamic> beta_derivative
187 = multiply(x_val.transpose(), neg_softmax_lin.matrix());
188 if constexpr (T_x_rows == 1) {
189 beta_derivative *= N_instances;
190 }
191
192 for (int i = 0; i < N_instances; i++) {
193 if constexpr (T_x_rows == 1) {
194 beta_derivative.col(y_seq[i] - 1) += x_val;
195 } else {
196 beta_derivative.col(y_seq[i] - 1) += x_val.row(i);
197 }
198 }
199 // TODO(Tadej) maybe we can replace previous loop with the following
200 // line when we have newer Eigen partials<2>(ops_partials)(Eigen::all,
201 // y
202 // - 1) += x_val.colwise.sum().transpose();
203
204 partials<2>(ops_partials) = std::move(beta_derivative);
205 }
206 }
207 return ops_partials.build(logp);
208}
209
210template <typename T_y, typename T_x, typename T_alpha, typename T_beta>
212 const T_y& y, const T_x& x, const T_alpha& alpha, const T_beta& beta) {
213 return categorical_logit_glm_lpmf<false>(y, x, alpha, beta);
214}
215
216} // namespace math
217} // namespace stan
218
219#endif
scalar_seq_view provides a uniform sequence-like wrapper around either a scalar or a sequence of scal...
isfinite_< as_operation_cl_t< T > > isfinite(T &&a)
auto as_column_vector_or_scalar(T &&a)
as_column_vector_or_scalar of a kernel generator expression.
return_type_t< T_x, T_alpha, T_beta > categorical_logit_glm_lpmf(const T_y &y, const T_x &x, const T_alpha &alpha, const T_beta &beta)
Returns the log PMF of the Generalized Linear Model (GLM) with categorical distribution and logit (so...
typename partials_type< T >::type partials_type_t
Helper alias for accessing the partial type.
typename return_type< Ts... >::type return_type_t
Convenience type for the return type of the specified template parameters.
int64_t size(const T &m)
Returns the size (number of the elements) of a matrix_cl or var_value<matrix_cl<T>>.
Definition size.hpp:19
auto multiply(Mat1 &&m1, Mat2 &&m2)
Return the product of the specified matrices.
Definition multiply.hpp:20
bool size_zero(const T &x)
Returns 1 if input is of length 0, returns 0 otherwise.
Definition size_zero.hpp:19
void check_bounded(const char *function, const char *name, const T_y &y, const T_low &low, const T_high &high)
Check if the value is between the low and high values, inclusively.
void check_consistent_size(const char *function, const char *name, const T &x, size_t expected_size)
Check if x is consistent with size expected_size.
T value_of(const fvar< T > &v)
Return the value of the specified variable.
Definition value_of.hpp:18
fvar< T > log(const fvar< T > &x)
Definition log.hpp:18
void check_finite(const char *function, const char *name, const T_y &y)
Return true if all values in y are finite.
void check_size_match(const char *function, const char *name_i, T_size1 i, const char *name_j, T_size2 j)
Check if the provided sizes match.
auto dot_product(const T_a &a, const T_b &b)
Returns the dot product of the specified vectors.
fvar< T > beta(const fvar< T > &x1, const fvar< T > &x2)
Return fvar with the beta function applied to the specified arguments and its gradient.
Definition beta.hpp:51
auto make_partials_propagator(Ops &&... ops)
Construct an partials_propagator.
fvar< T > exp(const fvar< T > &x)
Definition exp.hpp:15
typename ref_type_if< is_autodiff_v< T >, T >::type ref_type_if_not_constant_t
Definition ref_type.hpp:63
typename ref_type_if< true, T >::type ref_type_t
Definition ref_type.hpp:56
typename partials_return_type< Args... >::type partials_return_t
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
Template metaprogram to calculate whether a summand needs to be included in a proportional (log) prob...