1 | ////////////////////////////////////////////////////////////////////////////// |
---|
2 | // FILE: def_strategy_logit.tol |
---|
3 | // PURPOSE: Define la estrategia de estimación asociada al método |
---|
4 | // Logit de TOL que está basado en un método de estimación |
---|
5 | // puntual máximo verosímil. |
---|
6 | ////////////////////////////////////////////////////////////////////////////// |
---|
7 | |
---|
8 | ////////////////////////////////////////////////////////////////////////////// |
---|
9 | Class @MMS.StrategyVLogit : @MMS.Strategy |
---|
10 | ////////////////////////////////////////////////////////////////////////////// |
---|
11 | { |
---|
12 | // Especificaciones propias: |
---|
13 | // (susceptibles de convertirse en clases) |
---|
14 | // * NameBlock de comunicación entre _BuildMatrices y _DoEstimation |
---|
15 | // [[ Text name, Matrix outData, Matrix inpData ]] |
---|
16 | |
---|
17 | //////////////////////////////////////////////////////////////////////////// |
---|
18 | // Métodos no triviales: |
---|
19 | // * Execute() |
---|
20 | // ¿? Real SetEstimationIntervalMinMax() |
---|
21 | // |
---|
22 | // * Real _AfterSetModel() |
---|
23 | // * Set _BuildMatrices() |
---|
24 | // * Set _DoEstimation(Set AllModelDef) |
---|
25 | |
---|
26 | //////////////////////////////////////////////////////////////////////////// |
---|
27 | Real SetEstimationIntervalMinMax(Real void) |
---|
28 | //////////////////////////////////////////////////////////////////////////// |
---|
29 | { |
---|
30 | Real 0 |
---|
31 | }; |
---|
32 | |
---|
33 | //////////////////////////////////////////////////////////////////////////// |
---|
34 | // Prepara los parametros configurables para cada output a partir del |
---|
35 | // modelo establecido en SetModel. Este metodo es invocado |
---|
36 | // automaticamente desde el metodo SetModel implementado en la clase |
---|
37 | // base. |
---|
38 | Real _AfterSetModel(Real void) |
---|
39 | //////////////////////////////////////////////////////////////////////////// |
---|
40 | { |
---|
41 | // (pgea) Considero interesante obviar el uso de esta función... |
---|
42 | Real void |
---|
43 | }; |
---|
44 | |
---|
45 | //////////////////////////////////////////////////////////////////////////// |
---|
46 | // recorre todos los outputs en model y construye su ModelDef |
---|
47 | // correspondiente. Advierte de posible informacion contenida en |
---|
48 | // @MMS.Model que no es usada, por ejemplo informacion de jerarquia. |
---|
49 | |
---|
50 | //////////////////////////////////////////////////////////////////////////// |
---|
51 | Set _BuildMatrices(Real void) |
---|
52 | //////////////////////////////////////////////////////////////////////////// |
---|
53 | { |
---|
54 | @MMS.ModelAdapter model = @MMS.ModelAdapter::Default(_.model[1]); |
---|
55 | Set submodels_ = model::GetSubmodels(?); // active |
---|
56 | |
---|
57 | // Comprueba que son VLogit |
---|
58 | Set submodels = Select(submodels_, Real (@MMS.SubmodelAdapter submodel) { |
---|
59 | If(submodel::GetModelType(?)=="Logit", 1, { |
---|
60 | WriteLn("El submodelo '"<<submodel::GetIndex(?) |
---|
61 | <<"' no es del tipo Logit.","E"); |
---|
62 | 0}) |
---|
63 | }); |
---|
64 | |
---|
65 | Set all_modeldef = EvalSet(submodels, NameBlock (@MMS.SubmodelAdapter submodel) { |
---|
66 | |
---|
67 | @MMS.OutputAdapter output = submodel::GetOutput(?); |
---|
68 | |
---|
69 | Text outputName = output::GetIndex(0); |
---|
70 | Matrix outputData = output::GetData(?); |
---|
71 | |
---|
72 | Set expTerms = submodel::GetExpTermsLinear(?); // active |
---|
73 | |
---|
74 | Set matrices = EvalSet(expTerms, Matrix (@MMS.ExpTermLinearAdapter expTerm) { |
---|
75 | expTerm::GetData(?) |
---|
76 | }); |
---|
77 | Matrix inputData = BinGroup("|", matrices); |
---|
78 | |
---|
79 | //! Apaño para mantener el nombre de los parámetros... |
---|
80 | Set parameterNames = EvalSet(expTerms, Text(@MMS.ExpTermLinearAdapter expTerm) { |
---|
81 | expTerm::GetParameter(?)::GetIndex(?) |
---|
82 | }); |
---|
83 | Set parameterIndices = For(1, Card(parameterNames), Real (Real i) { |
---|
84 | Eval("Real "<<parameterNames[i]<<" = Copy(i)") |
---|
85 | }); |
---|
86 | |
---|
87 | NameBlock [[ |
---|
88 | outputName, |
---|
89 | parameterIndices, |
---|
90 | outputData, |
---|
91 | inputData |
---|
92 | ]] |
---|
93 | }) |
---|
94 | }; |
---|
95 | |
---|
96 | //_.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-. |
---|
97 | NameBlock Logit = |
---|
98 | //_.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-. |
---|
99 | [[ |
---|
100 | Real _.ctInfo = 0; |
---|
101 | Real _.dEpsilon = DiffDist; |
---|
102 | Real _.maxIter = MaxIter; |
---|
103 | Real _.tolerance = 10^(-8); |
---|
104 | Real _.tolerance.Rec = 10^(-4); |
---|
105 | Real _.probability.Init = 1/2; |
---|
106 | Real _.num.Step = 8; |
---|
107 | |
---|
108 | Matrix _Error(Matrix y, Matrix p) |
---|
109 | { |
---|
110 | y-p //p = Probability(X, B) |
---|
111 | }; |
---|
112 | |
---|
113 | Matrix _Gradient(Matrix X, Matrix error) |
---|
114 | { |
---|
115 | Tra(Tra(error)*X) //error = y - Probability(X, B) |
---|
116 | }; |
---|
117 | |
---|
118 | Matrix _Hessian(VMatrix vX, Matrix p) |
---|
119 | { |
---|
120 | VMatrix W = Mat2VMat(p$*RSum(-p,1)); |
---|
121 | VMatrix V = Eye(Rows(p), Rows(p), 0, W); |
---|
122 | VMat2Mat(-Tra(V*vX)*vX) |
---|
123 | }; |
---|
124 | |
---|
125 | Matrix _Probability(Matrix X, Matrix B, Matrix LogitGroupProb) |
---|
126 | { |
---|
127 | Matrix p = RPow(RSum(Exp(-X*B-LogitGroupProb), 1), -1); |
---|
128 | p |
---|
129 | }; |
---|
130 | |
---|
131 | Matrix _MLnLikelyhood(Matrix y, Matrix p) |
---|
132 | { |
---|
133 | y$*Log(p)+RSum(-y,1)$*Log(RSum(-p,1)) |
---|
134 | }; |
---|
135 | |
---|
136 | Matrix _MLikelyhood(Matrix mLnLikelyhood) |
---|
137 | { |
---|
138 | Exp(mLnLikelyhood) |
---|
139 | }; |
---|
140 | |
---|
141 | Set Estimate.MaxLikelyhood |
---|
142 | ( |
---|
143 | Matrix y, // Matriz y de variable salida binaria |
---|
144 | Matrix XIni, // Matriz x de variables entrada |
---|
145 | Matrix B0Ini, // Matriz de parametros iniciales |
---|
146 | Anything ctInfo, // Un real 0 sin constante, |
---|
147 | // Un real 1 estima constante, |
---|
148 | // Una matriz |
---|
149 | Real dEpsilon, // Diferencia de paso |
---|
150 | Real maxIter, // Numero maximo de iteraciones |
---|
151 | Real tolerance // Tolerancia al error |
---|
152 | ) |
---|
153 | { |
---|
154 | Text grCtInfo = Grammar(ctInfo); |
---|
155 | |
---|
156 | Matrix X = Case |
---|
157 | ( |
---|
158 | /* |
---|
159 | And(grCtInfo=="Real", EQ(ctInfo, 0)), XIni, |
---|
160 | And(grCtInfo=="Real", EQ(ctInfo, 1)), |
---|
161 | { |
---|
162 | XIni|Rand(Rows(XIni), 1, 1, 1) |
---|
163 | }, |
---|
164 | */ |
---|
165 | grCtInfo=="Matrix", XIni, |
---|
166 | 1, XIni |
---|
167 | ); |
---|
168 | |
---|
169 | Matrix IdCt = Case |
---|
170 | ( |
---|
171 | // And(grCtInfo=="Real", EQ(ctInfo, 0)), Rand(Rows(XIni), 1, 0, 0), |
---|
172 | // And(grCtInfo=="Real", EQ(ctInfo, 1)), Rand(Rows(XIni), 1, 0, 0), |
---|
173 | grCtInfo=="Matrix", ctInfo, |
---|
174 | 1, Rand(Rows(XIni), 1, 0, 0) |
---|
175 | ); |
---|
176 | |
---|
177 | Matrix B0 = Case |
---|
178 | ( |
---|
179 | grCtInfo=="Matrix", B0Ini, |
---|
180 | 1, B0Ini |
---|
181 | ); |
---|
182 | |
---|
183 | Real n = Columns(X); // Number of variables |
---|
184 | Real N = Rows(X); // Number of data |
---|
185 | |
---|
186 | Text iniMsg = |
---|
187 | "Model Logit Init ("+IntText(N)+"x"+IntText(n)+")"+Time; |
---|
188 | Real WriteLn(iniMsg); |
---|
189 | |
---|
190 | VMatrix vX = Mat2VMat(X); |
---|
191 | |
---|
192 | Matrix zeroMat = Rand(N, 1, 0, 0); |
---|
193 | Matrix oneMat = Rand(N, 1, 1, 1); |
---|
194 | Matrix negInfMat = Rand(N, 1, -1/0, -1/0); |
---|
195 | Matrix tolMat = Rand(N, 1, tolerance, tolerance); |
---|
196 | |
---|
197 | Real completeTime = 0; |
---|
198 | Real difTimeMin = 0; |
---|
199 | Real exit = 0; |
---|
200 | Matrix B = Copy(B0); |
---|
201 | Real iter = 0; |
---|
202 | Real oldLnLikelyhood = 0; |
---|
203 | |
---|
204 | Set cycle = Empty; |
---|
205 | |
---|
206 | Real While(Not(exit), |
---|
207 | { |
---|
208 | Real time0 = Copy(Time); |
---|
209 | |
---|
210 | //Real CMsg::Trace::show(1, "Printing oldLnLikelyhood="<<oldLnLikelyhood); |
---|
211 | Matrix p = _Probability(X, B, IdCt); |
---|
212 | |
---|
213 | //Real CMsg::Trace::show(1, "Printing p="<<p); |
---|
214 | Matrix error = _Error(y, p); |
---|
215 | |
---|
216 | Matrix G = _Gradient(X, error); |
---|
217 | Real time0.1 = Copy(Time); |
---|
218 | Matrix H = _Hessian(vX, p); |
---|
219 | Real time0.2 = Copy(Time); |
---|
220 | Matrix dif = MinimumResidualsSolve(H, G); |
---|
221 | |
---|
222 | Real norm = MatFrobeniusNorm(G); |
---|
223 | Real advance = MatFrobeniusNorm(dif); |
---|
224 | Real maxAbsDif = MatMax(Abs(dif)); |
---|
225 | |
---|
226 | |
---|
227 | Matrix mLnLikelyhood = _MLnLikelyhood(y, p); |
---|
228 | Matrix mLLCorrect = IfMat(EQ(Abs(error), oneMat), negInfMat, |
---|
229 | IfMat(LT(Abs(error), tolMat), zeroMat, mLnLikelyhood)); |
---|
230 | |
---|
231 | Real lnLikelyhood = MatSum(mLLCorrect); |
---|
232 | //Real CMsg::Trace::show(1, "Printing dif"<<dif); |
---|
233 | //Real CMsg::Trace::show(1, "Printing mLnLikelyhood"<<mLnLikelyhood); |
---|
234 | //Real CMsg::Trace::show(1, "Printing mLLCorrect"<<mLLCorrect); |
---|
235 | //Real CMsg::Trace::show(1, "Printing error"<<error); |
---|
236 | |
---|
237 | //Real CMsg::Trace::show(1, "Printing lnLikelyhood="<<lnLikelyhood); |
---|
238 | |
---|
239 | Real difTimeMin := (time0.2-time0.1)+difTimeMin; |
---|
240 | |
---|
241 | Real difTime = Copy(Time)-time0; |
---|
242 | Real completeTime := completeTime+difTime; |
---|
243 | Real exitTreatment = Case |
---|
244 | ( |
---|
245 | IsUnknown(advance), |
---|
246 | { |
---|
247 | Real CMsg::Trace::show(1, "Advance is unknown"); |
---|
248 | Real exit:=1 |
---|
249 | }, |
---|
250 | GE(iter, maxIter), |
---|
251 | { |
---|
252 | Real CMsg::Trace::show(1, "MaxIter reached"); |
---|
253 | Real exit:=1 |
---|
254 | }, |
---|
255 | LT(norm, dEpsilon), |
---|
256 | { |
---|
257 | Real CMsg::Trace::show(1, "Norm lower than "<<dEpsilon); |
---|
258 | Real exit:=1 |
---|
259 | }, |
---|
260 | LT(maxAbsDif, tolerance), |
---|
261 | { |
---|
262 | Real CMsg::Trace::show(1, "MaxAbsDif lower than "<<tolerance); |
---|
263 | Real exit:=1 |
---|
264 | }, |
---|
265 | LT(Abs(oldLnLikelyhood - lnLikelyhood), dEpsilon), |
---|
266 | { |
---|
267 | Real CMsg::Trace::show(1, |
---|
268 | "LnLikelihood is stable: lnLikelyhood ="<<lnLikelyhood+ |
---|
269 | " oldLnLikelyhood ="<<oldLnLikelyhood); |
---|
270 | Real exit:=1 |
---|
271 | }, |
---|
272 | 1, |
---|
273 | { |
---|
274 | Text exitMsg = " Logit model iteration("+ |
---|
275 | FormatReal(iter, "%0"+IntText(Floor(Log10(maxIter)+1))+".lf")+ |
---|
276 | ")"+" "+ |
---|
277 | " LogLikelyhood = "+FormatReal(lnLikelyhood, "%.4E")+" "+ |
---|
278 | " MaxAbsDif = "+FormatReal(maxAbsDif, "%.4E")+" "+ |
---|
279 | " Gradient Norm = "+FormatReal(norm, "%.4E")+" "+ |
---|
280 | " Time = "+FormatReal(difTime, "%.4lf"); |
---|
281 | Real CMsg::Trace::show(1, exitMsg); |
---|
282 | Real iter := iter+1; |
---|
283 | Real oldLnLikelyhood := Copy(lnLikelyhood); |
---|
284 | Matrix B:=(Matrix B-dif); |
---|
285 | Real 0 |
---|
286 | } |
---|
287 | ); |
---|
288 | Real exitCycle = If(EQ(exitTreatment, 1), |
---|
289 | { |
---|
290 | Set cycle := SetOfAnything |
---|
291 | (B, p, G, H, dif, norm, advance, |
---|
292 | maxAbsDif, error, lnLikelyhood, oldLnLikelyhood, ctInfo, X, XIni, y, |
---|
293 | mLLCorrect); |
---|
294 | 1 |
---|
295 | }, 0) |
---|
296 | }); |
---|
297 | Real time2 = Copy(Time); |
---|
298 | /* |
---|
299 | Matrix p = _Probability(X, B); |
---|
300 | |
---|
301 | Matrix error = _Error(y, p); |
---|
302 | |
---|
303 | Matrix G = _Gradient(X, error); |
---|
304 | Matrix H = _Hessian(vX, p); |
---|
305 | Matrix dif = MinimumResidualsSolve(H, G); |
---|
306 | |
---|
307 | Real norm = MatFrobeniusNorm(G); |
---|
308 | Real advance = MatFrobeniusNorm(dif); |
---|
309 | Real maxAbsDif = MatMax(Abs(dif)); |
---|
310 | Matrix mLnLikelyhood = _MLnLikelyhood(y, p); |
---|
311 | Real lnLikelyhood = MatSum(mLnLikelyhood); |
---|
312 | */ |
---|
313 | Real difTime2 = Copy(Time)-time2; |
---|
314 | Real totalTime = completeTime+difTime2; |
---|
315 | Text endMsg = |
---|
316 | "Model Logit Ended. Time:"<<totalTime+" SplitTime:"<<difTimeMin+NL+NL; |
---|
317 | Real WriteLn(endMsg); |
---|
318 | |
---|
319 | /* |
---|
320 | SetOfAnything |
---|
321 | (B, p, G, H, dif, norm, advance, |
---|
322 | maxAbsDif, error, lnLikelyhood, oldLnLikelyhood) |
---|
323 | */ |
---|
324 | cycle |
---|
325 | }; |
---|
326 | |
---|
327 | Set Estimate.MaxLikelyhood.Default(Matrix y, Matrix X) |
---|
328 | { |
---|
329 | Matrix B0Ini = Rand(Columns(X), 1, 0, 0); |
---|
330 | Estimate.MaxLikelyhood |
---|
331 | ( |
---|
332 | y, // Matriz y de variable salida binaria |
---|
333 | X, // Matriz x de variables entrada |
---|
334 | B0Ini, |
---|
335 | _.ctInfo, |
---|
336 | _.dEpsilon, // Diferencia de paso |
---|
337 | _.maxIter, // Numero maximo de iteraciones |
---|
338 | _.tolerance // Tolerancia al error |
---|
339 | ) |
---|
340 | }; |
---|
341 | Set Estimate.MaxLikelyhood.Constant(Matrix y, Matrix X, Matrix constant) |
---|
342 | { |
---|
343 | Matrix B0Ini = Rand(Columns(X), 1, 0, 0); |
---|
344 | Estimate.MaxLikelyhood |
---|
345 | ( |
---|
346 | y, // Matriz y de variable salida binaria |
---|
347 | X, // Matriz x de variables entrada |
---|
348 | B0Ini, |
---|
349 | constant, |
---|
350 | _.dEpsilon, // Diferencia de paso |
---|
351 | _.maxIter, // Numero maximo de iteraciones |
---|
352 | _.tolerance // Tolerancia al error |
---|
353 | ) |
---|
354 | }; |
---|
355 | Set Estimate.MaxLikelyhood.ProbB0 |
---|
356 | ( |
---|
357 | Matrix y, |
---|
358 | Matrix X, |
---|
359 | Matrix B0Ini, |
---|
360 | Real prob |
---|
361 | ) |
---|
362 | { |
---|
363 | Matrix probMat = Rand(Rows(y), 1, prob, prob); |
---|
364 | Matrix constant = Log(probMat$/RSum(-probMat, 1)); |
---|
365 | |
---|
366 | Estimate.MaxLikelyhood |
---|
367 | ( |
---|
368 | y, // Matriz y de variable salida binaria |
---|
369 | X, // Matriz x de variables entrada |
---|
370 | B0Ini, |
---|
371 | constant, |
---|
372 | _.dEpsilon, // Diferencia de paso |
---|
373 | _.maxIter, // Numero maximo de iteraciones |
---|
374 | _.tolerance // Tolerancia al error |
---|
375 | ) |
---|
376 | }; |
---|
377 | |
---|
378 | Set Estimate.MaxLikelyhood.ProbRec |
---|
379 | ( |
---|
380 | Matrix y, |
---|
381 | Matrix X, |
---|
382 | Matrix B0Cur, |
---|
383 | Real step, |
---|
384 | Real tolerance, |
---|
385 | Real probCur, |
---|
386 | Real probEnd |
---|
387 | ) |
---|
388 | { |
---|
389 | Text iniMsg = NL+NL+"Model Logit (p="<<probCur+") "+Time; |
---|
390 | Real WriteLn(iniMsg); |
---|
391 | |
---|
392 | Set logitResult = Estimate.MaxLikelyhood.ProbB0(y, X, B0Cur, probCur); |
---|
393 | If(LT(Abs(probCur - probEnd), tolerance), logitResult, |
---|
394 | { |
---|
395 | Real prob = probCur*step; |
---|
396 | Matrix B0 = logitResult::B; |
---|
397 | Estimate.MaxLikelyhood.ProbRec |
---|
398 | (y, X, B0, step, tolerance, prob, probEnd) |
---|
399 | }) |
---|
400 | }; |
---|
401 | |
---|
402 | Set Estimate.MaxLikelyhood.Prob |
---|
403 | ( |
---|
404 | Matrix y, |
---|
405 | Matrix X, |
---|
406 | Real prob |
---|
407 | ) |
---|
408 | { |
---|
409 | Real step = (prob/_.probability.Init)^(1/_.num.Step); |
---|
410 | Matrix B0Ini = Rand(Columns(X), 1, 0, 0); |
---|
411 | Estimate.MaxLikelyhood.ProbRec |
---|
412 | (y, X, B0Ini, step, _.tolerance.Rec, _.probability.Init, prob) |
---|
413 | }; |
---|
414 | |
---|
415 | Set Diagnosis |
---|
416 | ( |
---|
417 | Matrix y, |
---|
418 | Matrix X, |
---|
419 | Matrix B, |
---|
420 | Matrix error, |
---|
421 | Real lnLikelyhood, |
---|
422 | Set names, |
---|
423 | Matrix H //Hessian |
---|
424 | ) |
---|
425 | { |
---|
426 | Text iniMsg = |
---|
427 | "Model Logit Diagnosis. Init Time:"+Time; |
---|
428 | Real WriteLn(iniMsg); |
---|
429 | |
---|
430 | Real N = Rows(X); // |
---|
431 | Real n = Columns(X); // Parameter number |
---|
432 | |
---|
433 | Matrix FIM = -H; // Fisher Information Matrix |
---|
434 | Matrix COV = SVDInverse(FIM); // Varianze Covarianza Parameter Matrix |
---|
435 | |
---|
436 | Set Parameters = For(1, Columns(X), Set(Real k) |
---|
437 | { |
---|
438 | Text name = names[k]; |
---|
439 | Real value = MatDat(B, k, 1); |
---|
440 | Real var = MatDat(COV, k, k); |
---|
441 | Real std = SqRt(var); |
---|
442 | Real tStudent = value/std; |
---|
443 | Real refProb = 2*(1-DistT(Abs(tStudent), N-n-1)); |
---|
444 | ParameterInf |
---|
445 | ( |
---|
446 | name, //Name |
---|
447 | 0, //Factor |
---|
448 | 0, //Order |
---|
449 | value, //Value |
---|
450 | std, //StDs |
---|
451 | tStudent, //TStudent |
---|
452 | refProb //RefuseProb |
---|
453 | ) |
---|
454 | }); |
---|
455 | |
---|
456 | Real VarTot = MatVar(y); |
---|
457 | Real VarError = MatVar(error); |
---|
458 | Real R2 = 1-VarError/VarTot; |
---|
459 | |
---|
460 | Real MaxProb = MatSum(y)/N; |
---|
461 | Real lnLikelyhoodIntercep = |
---|
462 | MatSum(_MLnLikelyhood(y, Rand(N, 1, MaxProb, MaxProb))); |
---|
463 | |
---|
464 | Real Nagelkerke.R2 = 1-(Exp((2/N)*(lnLikelyhoodIntercep-lnLikelyhood))); |
---|
465 | Real Nagelkerke.R2Max = 1-Exp((2/N)*lnLikelyhoodIntercep); |
---|
466 | Real Nagelkerke.R2MaxRescaled = Nagelkerke.R2/Nagelkerke.R2Max; |
---|
467 | Text endMsg = |
---|
468 | "Model Logit Diagnosis. End Time:"+Time+NL; |
---|
469 | Real WriteLn(endMsg); |
---|
470 | |
---|
471 | SetOfAnything |
---|
472 | ( |
---|
473 | Parameters, |
---|
474 | FIM, |
---|
475 | COV, |
---|
476 | MaxProb, |
---|
477 | R2, |
---|
478 | Nagelkerke.R2, |
---|
479 | Nagelkerke.R2Max, |
---|
480 | Nagelkerke.R2MaxRescaled, |
---|
481 | lnLikelyhood, |
---|
482 | lnLikelyhoodIntercep |
---|
483 | ) |
---|
484 | }; |
---|
485 | |
---|
486 | Set PreTesting(Matrix Y, Matrix X, Set varNames) |
---|
487 | { |
---|
488 | Text iniMsg = |
---|
489 | "Model Logit PreTesting. Init Time:"+Time; |
---|
490 | Real WriteLn(iniMsg); |
---|
491 | |
---|
492 | Real WriteLn(" Checking column stability..."+Time); |
---|
493 | Matrix unkX = IsUnknown(X); |
---|
494 | Matrix posInfX = IsPosInf(X); |
---|
495 | Matrix negInfX = IsNegInf(X); |
---|
496 | |
---|
497 | Matrix unkY = IsUnknown(Y); |
---|
498 | Matrix posInfY = IsPosInf(Y); |
---|
499 | Matrix negInfY = IsNegInf(Y); |
---|
500 | |
---|
501 | Real isUnkX = MatSum(unkX); |
---|
502 | Real isPosInfX = MatSum(posInfX); |
---|
503 | Real isNegInfX = MatSum(negInfX); |
---|
504 | |
---|
505 | Real isUnkY = MatSum(unkY); |
---|
506 | Real isPosInfY = MatSum(posInfY); |
---|
507 | Real isNegInfY = MatSum(negInfY); |
---|
508 | |
---|
509 | Real n = Rows(Y); |
---|
510 | Real balanced = MatSum(Y)/n; |
---|
511 | |
---|
512 | Real valid = |
---|
513 | Not(Or(isUnkX, isPosInfX, isNegInfX, isUnkY, isPosInfY, isNegInfY)); |
---|
514 | |
---|
515 | Set checkValid = If(EQ(valid, 1), Empty, |
---|
516 | { |
---|
517 | Set data = For(1, Card(varNames), Set(Real k) |
---|
518 | { |
---|
519 | Text name = varNames[k]; |
---|
520 | Real kUnkX = MatSum(SubCol(unkX, [[k]])); |
---|
521 | Real kPosInfX = MatSum(SubCol(posInfX, [[k]])); |
---|
522 | Real kNegInfX = MatSum(SubCol(negInfX, [[k]])); |
---|
523 | SetOfAnything(name, kUnkX, kPosInfX, kNegInfX) |
---|
524 | }); |
---|
525 | Set header = SetOfText("VarName", "Unk", "PosInf", "NegInf"); |
---|
526 | SetOfSet(header)<< |
---|
527 | SetOfSet(SetOfAnything("Y", isUnkY, isPosInfY, isNegInfY))<< |
---|
528 | data |
---|
529 | }); |
---|
530 | Real WriteLn(" Adjusting X matrix..."+Time); |
---|
531 | |
---|
532 | Matrix YPre = |
---|
533 | If(isUnkY, IfMat(unkY, VMat2Mat(Eye(Rows(Y), 1, 0, 0)), Y), Y); |
---|
534 | Matrix XPre = |
---|
535 | If(isUnkX, IfMat(unkX, VMat2Mat(Eye(Rows(X), Columns(X), 0, 0)), X), X); |
---|
536 | |
---|
537 | VMatrix vXPre = Mat2VMat(XPre); |
---|
538 | Set index = Range(1, Columns(X), 1); |
---|
539 | // Real WriteLn(" Correlation Y|X matrix..."+Time); |
---|
540 | // Matrix corVarX = Cor(Tra(YPre|XPre)); |
---|
541 | |
---|
542 | Real WriteLn(" X information column..."+Time); |
---|
543 | Set ColInfo = For(1, Card(varNames), Set(Real k) |
---|
544 | { |
---|
545 | Text name = varNames[k]; |
---|
546 | Matrix col = SubCol(XPre, [[k]]); |
---|
547 | Real min = MatMin(col); |
---|
548 | Real max = MatMax(col); |
---|
549 | Real stds = MatStDs(col); |
---|
550 | Real avr = MatAvr(col); |
---|
551 | Matrix freq = Frequency(col, 100, min, max); |
---|
552 | Matrix freq01 = Frequency(col$*Y, 100, min, max); |
---|
553 | Matrix ratioDisc = freq01$/freq; |
---|
554 | Real minValue = MatDat(freq01, 1, 2); |
---|
555 | Real maxValue = MatDat(freq01, 100, 2); |
---|
556 | Real maxRatio = MatDat(ratioDisc, 100, 2)/balanced; |
---|
557 | Real dicotomicRatio = (minValue+maxValue)/n ; |
---|
558 | |
---|
559 | VMatrix y = SubCol(vXPre, [[k]]); |
---|
560 | VMatrix x = SubCol(vXPre, index-[[k]]); |
---|
561 | |
---|
562 | Set linReg = LinReg::Get.GeneralInformation(y, x); |
---|
563 | Real R2MultiColinearity = linReg::R2; |
---|
564 | |
---|
565 | SetOfAnything |
---|
566 | ( |
---|
567 | name, |
---|
568 | min, |
---|
569 | max, |
---|
570 | stds, |
---|
571 | avr, |
---|
572 | freq, |
---|
573 | freq01, |
---|
574 | ratioDisc, |
---|
575 | maxRatio, |
---|
576 | maxValue, |
---|
577 | dicotomicRatio, |
---|
578 | R2MultiColinearity |
---|
579 | ) |
---|
580 | }); |
---|
581 | |
---|
582 | Text endMsg = |
---|
583 | "Model Logit PreTesting. End Time:"+Time+NL; |
---|
584 | Real WriteLn(endMsg); |
---|
585 | |
---|
586 | SetOfAnything |
---|
587 | (unkX, posInfX, negInfX, unkY, posInfY, negInfY, valid, checkValid, |
---|
588 | balanced, /*corVarX,*/ |
---|
589 | ColInfo, YPre, XPre) |
---|
590 | } |
---|
591 | ]]; |
---|
592 | //_.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-. |
---|
593 | |
---|
594 | |
---|
595 | //////////////////////////////////////////////////////////////////////////// |
---|
596 | // Aplica el metodo Logit a todos los outputs. |
---|
597 | Set _DoEstimation(Set allOutMat) |
---|
598 | //////////////////////////////////////////////////////////////////////////// |
---|
599 | { |
---|
600 | Set EvalSet(allOutMat, Set(NameBlock args) { |
---|
601 | Set results = Logit::Estimate.MaxLikelyhood.Default( |
---|
602 | args::outputData, |
---|
603 | args::inputData |
---|
604 | ); |
---|
605 | |
---|
606 | Set resultsMod = [[ |
---|
607 | Matrix Parameters = results["B"]; |
---|
608 | Matrix Residuals = results["error"]; |
---|
609 | Matrix Probabilities = results["p"]; |
---|
610 | Matrix Gradient = results["G"]; |
---|
611 | Matrix Hessian = results["H"]; |
---|
612 | Matrix Likelihoods = results["mLLCorrect"]; |
---|
613 | Real Likelihood = Exp(results["lnLikelyhood"]); |
---|
614 | Real LogLikelihood = results["lnLikelyhood"]; |
---|
615 | Set ParameterIndices = args::parameterIndices |
---|
616 | ]]; |
---|
617 | Set PutName(args::outputName, resultsMod) |
---|
618 | }) |
---|
619 | }; |
---|
620 | |
---|
621 | //////////////////////////////////////////////////////////////////////////// |
---|
622 | @MMS.ResultsAdapter Execute(Real void) |
---|
623 | //////////////////////////////////////////////////////////////////////////// |
---|
624 | { |
---|
625 | Set argsEstim = _BuildMatrices(0); |
---|
626 | Real ApplySettings(0); |
---|
627 | Set _results = _DoEstimation(argsEstim); |
---|
628 | Real RestoreSettings(0); |
---|
629 | @MMS.ResultsAdapterLogit resultsAdapter = |
---|
630 | @MMS.ResultsAdapterLogit::New(_results) |
---|
631 | }; |
---|
632 | |
---|
633 | //////////////////////////////////////////////////////////////////////////// |
---|
634 | Static @MMS.StrategyVLogit New(NameBlock args) |
---|
635 | //////////////////////////////////////////////////////////////////////////// |
---|
636 | { |
---|
637 | @MMS.StrategyVLogit obj = [[ |
---|
638 | // ¿necesita nombre y descripción? |
---|
639 | Text _.name = getOptArg(args, "_.name", "VLogit"); |
---|
640 | Text _.description = getOptArg(args, "_.description", "") |
---|
641 | ]]; |
---|
642 | // Settings de Logit construidas de acuerdo al ticket de TOL-Project #736 |
---|
643 | Real obj::AddSetting.FromObject(MaxIter); |
---|
644 | Real obj::AddSetting.FromObject(Tolerance); |
---|
645 | obj |
---|
646 | }; |
---|
647 | |
---|
648 | //////////////////////////////////////////////////////////////////////////// |
---|
649 | Static @MMS.StrategyVLogit Default(Real void) |
---|
650 | //////////////////////////////////////////////////////////////////////////// |
---|
651 | { |
---|
652 | @MMS.StrategyVLogit::New([[ Text _.name = "VLogit" ]]) |
---|
653 | } |
---|
654 | }; |
---|