20 MLogit::MLogit(
const arma::uvec &choice,
21 const arma::uvec &alt,
22 const arma::uvec &id_idx,
31 if (weights.is_empty()) {
32 weights = arma::vec(n);
35 updateData(choice, alt, id_idx, z1, z2, x, weights);
38 arma::uvec ualt = arma::unique(alt);
41 idx_z1 = arma::uvec(z1.n_cols);
43 for (
unsigned i=0; i < idx_z1.n_elem; i++) {
47 idx_z2 = arma::uvec(J*z2.n_cols);
48 for (
unsigned i=0; i < idx_z2.n_elem; i++) {
52 idx_x = arma::uvec((J-1)*x.n_cols);
53 for (
unsigned i=0; i < idx_x.n_elem; i++) {
57 alt_idx = arma::uvec(J);
59 theta_z1 = arma::vec(z1.n_cols);
60 theta_x = arma::mat(J, x.n_cols);
61 theta_z2 = arma::mat(J, z2.n_cols);
62 theta = arma::vec(idx_z1.n_elem + idx_z2.n_elem + idx_x.n_elem);
66 zx = arma::sp_mat(n, theta.n_elem);
69 double MLogit::loglik() {
70 return arma::as_scalar(sum(logpr%(*Choice())%(*Weights())));
73 mat MLogit::score(
bool update,
bool indiv) {
74 if (update) MLogit::updateZX();
78 xp = target::groupsum(xp, *cluster(),
true);
79 uvec chosen = find((*Choice()));
80 mat score = zx.rows(chosen) - xp;
81 score.each_col() %= (*Weights()).elem(chosen);
82 if (!indiv) score = sum(score, 0);
86 mat MLogit::hessian(
bool update) {
87 if (update) MLogit::updateZX();
92 xp = zx - target::groupsum(xp, *cluster(),
false);
93 tmp.each_col() %= target::groupsum((*Weights()) %
94 (*Choice()), *cluster(),
false);
95 mat hess = -xp.t()*tmp;
99 void MLogit::updateRef(
unsigned basealt) {
101 this->basealt = basealt;
104 for (
unsigned j=0; j < J; j++) {
106 this->alt_idx[j] = pos;
112 void MLogit::updatePar(vec theta) {
115 for (
unsigned i=0; i < p_z1; i++) {
116 theta_z1(i) = theta(idx_z1[i]);
122 for (
unsigned j=0; j < J; j++)
124 for (
unsigned i=0; i < p_x; i++) {
125 theta_x(j, i) = theta(idx_x[pos]);
132 for (
unsigned j=0; j < J; j++)
133 for (
unsigned i=0; i < p_z2; i++) {
134 theta_z2(j, i) = theta(idx_z2[pos]);
140 void MLogit::updateZX() {
141 for (
unsigned i=0; i < n; i++) {
144 for (
unsigned j=0; j < p_z1; j++)
145 zx(i, j) = (*Z1())(i, j);
149 for (
unsigned j=0; j < p_z2; j++)
150 zx(i, j + pos + p_z2*Alt(i)) = (*Z2())(i, j);
154 if (Alt(i) != basealt) {
155 pos += p_x*(alt_idx(Alt(i))-1);
156 for (
unsigned j=0; j < p_x; j++)
157 zx(i, j+pos) = (*X())(i, j);
163 void MLogit::updateProb() {
166 lp = (*Z1())*theta_z1;
169 for (
unsigned i=0; i < n; i++) {
171 lp[i] += as_scalar((*Z2()).row(i)*trans(theta_z2.row(Alt(i))));
175 for (
unsigned i=0; i < n; i++) {
176 if (Alt(i) != basealt) {
177 lp[i] += as_scalar((*X()).row(i)*trans(theta_x.row(Alt(i))));
184 for (
unsigned i=0; i < ncl; i++) {
185 unsigned start = this->cluster(i);
189 stop = this->cluster(i+1)-1;
191 vec a = target::softmax(lp.subvec(start, stop));
192 for (
unsigned j=0; j < a.n_elem; j++) {
Multinomial logit models.