-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGeneralizedLinearMixedModel.m
More file actions
3273 lines (2828 loc) · 145 KB
/
GeneralizedLinearMixedModel.m
File metadata and controls
3273 lines (2828 loc) · 145 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef (Sealed = true) GeneralizedLinearMixedModel < classreg.regr.LinearLikeMixedModel
%GeneralizedLinearMixedModel Fitted generalized linear mixed effects model.
% GLME = FITGLME(...) fits a generalized linear mixed effects model to
% data. The fitted model GLME is a GeneralizedLinearMixedModel object
% modeling the response variable from one of several supported
% distributions. A transformation of the conditional mean of the response
% is modelled as a linear function of fixed and random effect predictors.
% Several choices for the transformation are available via the supported
% link functions.
%
% GeneralizedLinearMixedModel methods:
% coefCI - Coefficient confidence intervals
% coefTest - Linear hypothesis test on coefficients
% predict - Compute predicted values given predictor values
% random - Generate random response values given predictor values
% plotResiduals - Plot of residuals
% designMatrix - Fixed and random effects design matrices
% fixedEffects - Stats on fixed effects
% randomEffects - Stats on random effects
% covarianceParameters - Extract covariance parameters
% fitted - Fitted response
% residuals - Various types of residuals
% response - Response used to fit the model
% compare - Compare fitted models
% anova - Marginal tests for fixed effect terms
% disp - Display a fitted model
% refit - Fit the model to new response vector
%
% GeneralizedLinearMixedModel properties:
% FitMethod - Method used for fitting
% Distribution - Distribution of the response
% Link - Link relating the distribution parameters to the predictors
% Dispersion - Theoretical or estimated dispersion parameter
% DispersionEstimated - Flag indicating if Dispersion was estimated
% Formula - Representation of the model used in this fit
% LogLikelihood - Log of likelihood function at coefficient estimates
% DFE - Degrees of freedom for residuals
% SSE - Error sum of squares
% SST - Total sum of squares
% SSR - Regression sum of squares
% CoefficientCovariance - Covariance matrix for coefficient estimates
% CoefficientNames - Coefficient names
% NumCoefficients - Number of coefficients
% NumEstimatedCoefficients - Number of estimated coefficients
% Coefficients - Coefficients and related statistics
% Rsquared - R-squared and adjusted R-squared
% ModelCriterion - AIC and other model criteria
% VariableInfo - Information about variables used in the fit
% ObservationInfo - Information about observations used in the fit
% Variables - Table of variables used in fit
% NumVariables - Number of variables used in fit
% VariableNames - Names of variables used in fit
% NumPredictors - Number of predictors
% PredictorNames - Names of predictors
% ResponseName - Name of response
% NumObservations - Number of observations in the fit
% ObservationNames - Names of observations in the fit
%
% See also FITGLME, FITLME, LinearMixedModel.
% Copyright 2013-2014 The MathWorks, Inc.
% Properties from Predictor.
properties(Dependent,GetAccess='public',SetAccess='protected',Hidden=true)
%Fitted - Fitted (predicted) values.
% The Fitted property is a vector of estimated conditional means that
% include contributions from both fixed and random effects and are on the
% scale of the response variable.
%
% The fitted values are computed using the predictor values used to fit
% the model. Use the predict method to compute predictions for other
% predictor values and to compute confidence bounds for the predicted
% values.
%
% See also FITTED.
Fitted
%Residuals - Residual values.
% The Residuals property is a table array with the following columns:
%
% 'Raw' The Raw conditional residuals
% 'Pearson' The Pearson conditional residuals
%
% The conditional residuals are based on fitted values that include
% contributions from both fixed and random effects and are on the scale
% of the response variable.
%
% For more details on various residuals, see the residuals method.
%
% See also RESIDUALS.
Residuals
end
% New public properties defined by GeneralizedLinearMixedModel.
properties(GetAccess=public, SetAccess='protected')
%FitMethod - Method used to fit the generalized linear mixed effects model.
% The FitMethod property is one of the following:
%
% 'MPL' - Maximum pseudo likelihood
% 'REMPL' - Restricted maximum pseudo likelihood
% 'ApproximateLaplace' - Maximum likelihood using approximate Laplace
% approximation with fixed effects profiled out
% 'Laplace' - Maximum likelihood using Laplace approximation
%
% See also FITGLME.
FitMethod
%Distribution Response distribution name.
% The Distribution property is a string containing the name of the
% distribution of the response.
%
% See also GeneralizedLinearMixedModel, Link, Dispersion, DispersionEstimated.
Distribution
%Link Link between the distribution parameters and predictor values.
% The Link property is a structure providing the name and other
% characteristics of the link function. The link is a function G that
% links the distribution parameter MU to the linear predictor ETA as
% follows: G(MU) = ETA. The structure has four fields:
%
% Name Name of the link function.
% Link The function that defines G.
% Derivative Derivative of G.
% SecondDerivative Second derivative of G.
% Inverse Inverse of G.
%
% See also GeneralizedLinearMixedModel, Distribution.
Link
%Dispersion Parameter defining the conditional variance of the response.
% For observation i, the conditional (given the random effects) variance
% of the response y_i given the conditional mean mu_i and dispersion
% parameter phi in a generalized linear mixed effects (GLME) model is
% given by:
%
% Var(y_i | mu_i, phi) = (phi/w_i) * v(mu_i), phi > 0
%
% where w_i is the i th observation weight and v is the variance function
% for the specified conditional distribution of the response. The
% Dispersion property contains an estimate of phi for the specified GLME
% model. The value of Dispersion depends on the specified conditional
% distribution of the response. For binomial and Poisson distributions,
% the theoretical value of Dispersion is equal to phi = 1.0.
%
% If 'FitMethod' is 'MPL' or 'REMPL' and the 'DispersionFlag' name/value
% pair in fitglme is true then a dispersion parameter is estimated from
% data even for binomial and Poisson distributions. If 'FitMethod' is
% equal to 'ApproximateLaplace' or 'Laplace' then 'DispersionFlag'
% name/value pair in fitglme does not apply and the dispersion parameter
% is always fixed at 1.0 for binomial and Poisson distributions. For all
% other distributions, Dispersion is always estimated from data.
%
% See also GeneralizedLinearMixedModel, DispersionEstimated.
Dispersion
%DispersionEstimated A flag indicating if dispersion was estimated.
% For the binomial and Poisson distributions the dispersion parameter has
% a known theoretical value of 1.0. If FitMethod is 'ApproximateLaplace'
% or 'Laplace', the dispersion parameter is fixed at its theoretical
% value of 1.0 for binomial and Poisson distributions.
%
% If FitMethod is 'MPL' or 'REMPL', the dispersion parameter is estimated
% even for binomial and Poisson distributions if the 'DispersionFlag'
% name/value pair in fitglme is true and fixed at its theoretical value
% of 1.0 if the 'DispersionFlag' name/value pair in fitglme is false.
%
% For distributions other than binomial and Poisson and for any
% 'FitMethod', the dispersion parameter is always estimated.
%
% See also GeneralizedLinearMixedModel, Dispersion.
DispersionEstimated
end
% New public hidden properties defined by GeneralizedLinearMixedModel.
properties(GetAccess='public', SetAccess='protected',Hidden=true)
%Response - Vector of response values used to fit the model
Response
end
% Internal constants.
properties(Constant=true,Hidden=true)
AllowedFitMethods = {'mpl','rempl','approximatelaplace','laplace'};
AllowedOptimizers = {'fminunc','quasinewton','fminsearch'};
AllowedStartMethods = {'random','default'};
AllowedDFMethods = {'none','residual'};
AllowedResidualTypes = {'raw','pearson'};
AllowedDistributions = {'normal','gaussian','binomial','poisson','gamma','inversegaussian','inverse gaussian'};
AllowedEBMethods = {'auto','default','linesearchnewton','linesearchmodifiednewton','trustregion2d','fsolve'};
AllowedCovarianceMethods = {'conditional','jointhessian'};
end
% Private properties.
properties(Access={?classreg.regr.LinearLikeMixedModel})
% The following variables only include observations used in the fit
% corresponding to ObservationInfo.Subset.
%BinomialSize - Vector of integers containing the number of trials using
% which the proportions in y were computed. Applies only when modeling a
% binomial distribution.
BinomialSize
%Offset - Offset vector for the linear predictor of the GLME model.
Offset
%DispersionFlag - Supplied value of 'DispersionFlag' property.
DispersionFlag
%CovariancePattern - A cell array of covariance patterns.
% If the GLME model has R grouping variables, CovariancePattern is a cell
% array of length R containing the covariance pattern used for each
% grouping variable.
CovariancePattern
%DummyVarCoding - A string containing the dummy variable coding used for
% creating design matrices.
DummyVarCoding
%Optimizer - A string containing the optimizer to use for optimization.
Optimizer
%OptimizerOptions - A structure or object specifying the optimization
% options.
OptimizerOptions
%StartMethod - A string specifying how to initialize parameters for
% optimization.
StartMethod
%CheckHessian - A logical scalar indicating whether Hessian checks should
% be performed after fitting the model.
CheckHessian
%PLIterations - A positive integer specifying the maximum number of pseudo
% likelihood (PL) iterations. Applies only if 'FitMethod' is 'MPL' or
% 'REMPL'.
PLIterations
%PLTolerance - A numeric, real scalar indicating the relative convergence
% tolerance for terminating PL iterations.
PLTolerance
%MuStart - A vector providing a starting value for the conditional mean of
% y given b to initialize PL iterations. Legal values of elements in
% MuStart are as follows:
%
% Distribution Legal values
% 'normal' (-Inf,Inf)
% 'binomial' (0,1)
% 'poisson' (0,Inf)
% 'gamma' (0,Inf)
% 'inverse gaussian' (0,Inf)
%
% If MuStart is empty, a default initialization for MuStart is used.
MuStart
%InitPLIterations - Initial number of PL iterations used to initialize ML
% based methods like 'Laplace' and 'ApproximateLaplace'.
InitPLIterations
%EBMethod - A string containing the optimization method to use for
% estimating the empirical Bayes (EB) predictors of random effects.
% Choices are 'Default', 'LineSearchNewton', 'TrustRegion2D' and
% 'fsolve'. The 'Default' 'EBMethod' is very similar to
% 'LineSearchNewton' but uses a different convergence criterion and does
% not display iterative progress. 'Default' and 'LineSearchNewton' may
% fail for non-canonical link functions. In these cases, 'TrustRegion2D'
% or 'fsolve' is the recommended 'EBMethod'. 'fsolve' can be used only if
% we detect Optimization Toolbox.
EBMethod
%EBOptions - A structure created using statset to control the EB
% optimization. EBOptions has the following fields:
%
% 'TolFun' Relative tolerance on the gradient norm.
% Default is 1e-6.
% 'TolX' Absolute tolerance on the step size.
% Default is 1e-8.
% 'MaxIter' Maximum number of iterations. Default is
% 100.
% 'Display' 'off', 'iter' or 'final'. Default is 'off'.
%
% For 'EBMethod' equal to 'Default', 'TolFun' is the relative tolerance
% on the linear predictor of the model and the option 'Display' does not
% apply. If 'EBMethod' is 'fsolve', this should be an object created by
% optimoptions('fsolve').
EBOptions
%CovarianceMethod - A string indicating the method used to compute the
% covariance matrix of estimated parameters. Choices are 'Conditional'
% and 'JointHessian'. The 'Conditional' method is fast and computes an
% approximate covariance of fixed effects conditional on the estimated
% covariance parameters equal to the true values. The 'JointHessian'
% method computes the joint Hessian of the Laplacian log likelihood with
% respect to all model parameters and uses this to compute the covariance
% of fixed effects and covariance parameters. Default is 'Conditional'.
% For the 'Conditional' method, the covariance of covariance parameters
% is not computed.
CovarianceMethod
%UseSequentialFitting - Either true or false. If false, all ML methods are
% initialized using 1 or more PL iterations. If true,
% the initial values from PL iterations are refined
% with 'ApproximateLaplace' for 'Laplace' based
% fitting.
UseSequentialFitting
%CovarianceTable - A cell array of tables returned by the method
% covarianceParameters. We store this info here so that we don't have to
% recompute this in disp.
CovarianceTable
%ShowPLOptimizerDisplay - Logical flag indicating whether we want to show
% the iterative display from PL optimizer.
ShowPLOptimizerDisplay = false;
end
% Abstract public methods from FitObject.
methods(Access='public', Hidden=true)
function t = title(model)
strLHS = model.ResponseName;
strFunArgs = internal.stats.strCollapse(model.Formula.PredictorNames,',');
t = sprintf( '%s = glme(%s)',strLHS,strFunArgs);
end % end of title.
function val = feval(model,varargin) %#ok<INUSD>
warning(message('stats:GeneralizedLinearMixedModel:NoFevalMethod'));
val = [];
end % end of feval.
end
% Abstract public methods from FitObject.
methods(Access='public')
function disp(model)
%DISP Display a GeneralizedLinearMixedModel.
% DISP(GLME) displays the GeneralizedLinearMixedModel object GLME.
%
% See also GeneralizedLinearMixedModel, FITGLME.
% 1. Can't display an empty model.
if isempty(model.ObservationInfo)
displayFormula(model);
error(message('stats:GeneralizedLinearMixedModel:NoConstructor'));
end
% 2. Display headline.
displayHeadLine(model);
% 3. Model information.
displayModelInfo(model);
% 4. Display the formula.
displayFormula(model);
% 5. Model fit stats.
displayModelFitStats(model);
% 6. Fixed effect stats.
displayFixedStats(model)
% 7. Random effects covariance parameter stats.
displayCovarianceStats(model);
end % end of disp.
end
% Abstract public methods from Predictor.
methods(Access='public')
function [mupred,muci,df] = predict(model,varargin)
%PREDICT Compute predicted values given predictor values.
% MUPRED = PREDICT(GLME) computes a vector MUPRED of predictions of the
% conditional mean of the response given the random effects at the
% original predictors used to create GLME. MUPRED includes contributions
% from both estimated fixed effects and approximate empirical Bayes
% predictors (EBPs) of the random effects.
%
% MUPRED = PREDICT(GLME,T) uses predictor variables from the table T to
% predict the conditional mean of the response. T must contain all of the
% predictor variables used to create GLME.
%
% [MUPRED,MUCI] = PREDICT(...) also returns the two-column matrix MUCI
% containing 95% pointwise confidence intervals for the predicted values.
% The lower limits of the bounds are in column 1, and the upper limits
% are in column 2.
%
% [MUPRED,MUCI,DF] = PREDICT(...) also returns the degrees of freedom DF.
% If the 'Simultaneous' name-value pair is 'false', then DF is a vector
% containing the degrees of freedom values used in computing the
% confidence intervals. If 'Simultaneous' is 'true', then DF is a scalar
% containing the degrees of freedom value used for computing the
% simultaneous confidence intervals.
%
% [...] = PREDICT(...,PARAM1,VALUE1,...) specifies one or more of the
% following name/value pairs:
%
% 'Conditional' Either true or false. If false then returns
% marginal predictions which include contribution
% only from the estimated fixed effects. When making
% predictions, if a particular grouping variable has
% new levels (ones that were not in the original
% data), then the random effects for the grouping
% variable do not make any contribution to the
% 'Conditional' prediction at observations where the
% grouping variable has new levels. Default is true.
%
% 'Simultaneous' Either true for simultaneous bounds, or false for
% non-simultaneous bounds. Default is false.
%
% 'DFMethod' Specifies the method to use for computing the
% approximate denominator degrees of freedom (DF)
% when computing the confidence intervals. Options
% are 'Residual' and 'None'. If 'DFMethod' is
% 'Residual', the DF values are assumed to be
% constant and equal to (N-P) where N is the number
% of observations and P is the number of fixed
% effects. If 'DFMethod' is 'None', then all DF
% values are set to infinity. Default is 'Residual'.
%
% 'Alpha' A value between 0 and 1 to specify the confidence
% level as 100(1-ALPHA)%. Default is 0.05 for 95%
% confidence.
%
% 'Offset' Specifies the offset vector of the model. Must be
% a vector of length M where M is the number of rows
% in T. Default is zeros(M,1).
%
% predict computes the confidence intervals using the conditional mean
% squared error of prediction (CMSEP) approach of Booth and Hobert (1998)
% conditional on the estimated covariance parameters and the observed
% response. An alternative interpretation of the confidence intervals
% from predict is that they are approximate Bayesian credible intervals
% conditional on the estimated covariance parameters and the observed
% response.
%
% The marginal predictions are not the predictions of the marginal mean
% of the response. Marginal predictions are computed by substituting a
% vector of zeros in place of the EBP vector of the random effects in the
% prediction for the conditional mean of the response given the random
% effects.
%
% Example: Model gas mileage as a function of car weight, with a random
% effect due to model year.
% load carsmall
% T = table(MPG,Weight,Model_Year);
% glme = fitglme(T,'MPG ~ Weight + (1|Model_Year)')
%
% % Plot predicted values conditional on each year.
% gscatter(T.Weight,T.MPG,T.Model_Year)
% T2 = table();
% T2.Weight = linspace(1500,5000)';
% T2.Model_Year = repmat(70,100,1);
% line(T2.Weight,predict(glme,T2),'color','r');
% T2.Model_Year(:) = 76;
% line(T2.Weight,predict(glme,T2),'color','g');
% T2.Model_Year(:) = 82;
% line(T2.Weight,predict(glme,T2),'color','b');
%
% See also FITTED, RANDOM.
% References:
% (1) James G. Booth and James P. Hobert (1998), Standard Errors of
% Prediction in Generalized Linear Mixed Models, Journal of the American
% Statistical Association, 93(441), 262-272.
if nargin < 2 || internal.stats.isString(varargin{1})
% 1. If no new design points are given, get conditional
% predictions from the fitted model at the original design
% points. Called like:
% mupred = predict(glme) or
% mupred = predict(glme,'Conditional',true,...).
haveDataset = true;
ds = model.Variables;
otherArgs = varargin;
else
% 2. Get supplied dataset and optional args. Called like:
% mupred = predict(glme,T,'Conditional',true,...).
[haveDataset,ds,~,~,~,otherArgs] ...
= model.handleDatasetOrMatrixInput(varargin{:});
end
assertThat(haveDataset,'stats:LinearMixedModel:MustBeDataset','T')
M = size(ds,1);
% 3. Parse and validate optional input args.
% 3.1 Default parameter values.
dfltConditional = true;
dfltSimultaneous = false;
dfltDFMethod = 'Residual';
dfltAlpha = 0.05;
dfltOffset = zeros(M,1);
% 3.2 Optional parameter names and their default values.
paramNames = {'Conditional', 'Simultaneous', 'DFMethod', 'Alpha', 'Offset'};
paramDflts = {dfltConditional, dfltSimultaneous, dfltDFMethod, dfltAlpha, dfltOffset};
% 3.3 Parse optional parameter name/value pairs.
[conditional,simultaneous,dfmethod,alpha,offset] ...
= internal.stats.parseArgs(paramNames,paramDflts,otherArgs{:});
% 3.4 Validate optional parameter values.
conditional = model.validateConditional(conditional);
simultaneous = model.validateSimultaneous(simultaneous);
dfmethod = model.validateDFMethod(dfmethod);
alpha = model.validateAlpha(alpha);
offset = model.validateOffset(offset,M);
% 4. Extract size info from model.
q = model.RandomInfo.q;
R = model.GroupingInfo.R;
lev = model.GroupingInfo.lev;
% 5. Validate ds.
predNames = model.PredictorNames;
varNames = model.Variables.Properties.VariableNames;
[~,predLocs] = ismember(predNames,varNames);
dsref = model.Variables(:,predLocs);
ds = model.validateDataset(ds,'DS',dsref);
% 6. Get X and Z.
% 6.1 Get X.
finfo = extractFixedInfo(model,ds);
X = finfo.X;
% 6.2 Get Z.
rinfo = extractRandomInfo(model,ds);
Z = rinfo.Z;
% 7. Get cell arrays Gid and GidLevelNames for the supplied
% observations.
ginfo = extractGroupingInfo(model,ds);
Gid = ginfo.Gid;
GidLevelNames = ginfo.GidLevelNames;
% 8. Modify Gid to newGid such that in newGid{i}, ID j is mapped
% to model.GroupingInfo.GidLevelNames{i}{j}. In other words, if we
% associated ID 5 with level name 'Green', we must associate ID 5
% with level 'Green' in the supplied observations as well. New
% levels in supplied data, not previously seen will be assigned a
% group ID of NaN.
newGid = cell(R,1);
for k = 1:R
newGid{k} = model.reorderGroupIDs(Gid{k},...
GidLevelNames{k},model.GroupingInfo.GidLevelNames{k});
end
% 9. X already contains the fixed effects design matrix. Get the
% full sparse random effects design matrix Zs. This matrix will
% have sum_{i=1 to R} (q(i)*lev(i)) columns and M rows.
Zs = model.makeSparseZ(Z,q,lev,newGid,M);
% 10. Get ypred and yci.
% 10.1 Prediction options.
wantConditional = conditional;
if simultaneous == true
wantPointwise = false;
else
wantPointwise = true;
end
% 10.2 Call predict on model.slme.
hasIntercept = model.Formula.FELinearFormula.HasIntercept;
args = {X,Zs,alpha,dfmethod,...
wantConditional,wantPointwise,offset,hasIntercept};
switch nargout
case {0,1}
mupred = predict(model.slme,args{:});
case 2
[mupred,muci] = predict(model.slme,args{:});
case 3
[mupred,muci,df] = predict(model.slme,args{:});
end
%[mupred,muci,df] = predict(model.slme,X,Zs,alpha,dfmethod,...
% wantConditional,wantPointwise,offset,hasIntercept);
end % end of predict.
function ynew = random(model,varargin)
%RANDOM Generate random response values given predictor values.
% YNEW = RANDOM(GLME) generates a vector YNEW of random values from the
% fitted generalized linear mixed effects model GLME at the original
% design points. YNEW is created by first generating the random effects
% vector from its fitted prior distribution and then generating YNEW from
% its fitted conditional distribution given the random effects. The
% effect of supplied observation weights when creating the fit (if any)
% is taken into account.
%
% YNEW = RANDOM(GLME,TNEW) uses predictor variables from the table TNEW,
% which must contain all of the predictor variables used to create GLME.
%
% YNEW = RANDOM(...,PARAM1,VALUE1,...) accepts optional name/value pairs:
%
% 'Name' 'Value'
% 'Weights' Vector of M non-negative weights, where M is the
% number of rows in TNEW. Default is ones(M,1). For
% binomial and Poisson distributions, 'Weights' must
% be a vector of positive integers.
%
% 'BinomialSize' Vector of length M, where M is the number of rows
% in TNEW. Default is ones(M,1). Applies only to the
% binomial distribution and specifies the number of
% binomial trials when generating the random
% response values. Elements of 'BinomialSize' must
% be positive integers.
%
% 'Offset' Specifies the offset vector of the model. Must be
% a vector of length M where M is the number of rows
% in TNEW. Default is zeros(M,1).
%
% Example: Fit a model. Simulate new random values for the first
% observation.
% load carsmall
% T = table(MPG,Weight,Model_Year);
% glme = fitglme(T,'MPG ~ Weight + (1|Model_Year)');
% newT = T(ones(10000,1),:);
% r = random(glme,newT);
% hist(r)
%
% % These random values share a common new random effect due to
% % Model_Year, but their variance is comparable to the model value.
% v1 = var(r)
% v2 = glme.Dispersion
%
% See also PREDICT, FITTED.
% 1. If no new design points are given, generate data from the
% fitted model at the original design points. Include the effect of
% originally supplied observation weights.
if nargin < 2
% Called like: ynew = random(model).
wp = model.slme.PriorWeights;
delta = model.slme.Offset;
ntrials = model.slme.BinomialSize;
ysim = random(model.slme,[],model.slme.X,model.slme.Z,delta,wp,ntrials);
subset = model.ObservationInfo.Subset;
ynew = NaN(length(subset),1);
ynew(subset) = ysim;
return;
end
% 2. Should we use the original dataset or a new one?
if internal.stats.isString(varargin{1})
% 2.1 Called like: ynew = random(model,'Weights',w,'Offset',offset,'BinomialSize',binomsize).
haveDataset = true;
ds = model.Variables;
otherArgs = varargin;
else
% 2.2 Called like: ynew = random(model,Tnew,'Weights',w,'Offset',offset,'BinomialSize',binomsize).
[haveDataset,ds,~,~,~,otherArgs] = model.handleDatasetOrMatrixInput(varargin{:});
end
assertThat(haveDataset,'stats:LinearMixedModel:MustBeDataset','TNEW');
M = size(ds,1);
% 3. Validate optional name/value pairs.
% 3.1 Default parameter values.
dfltWeights = ones(M,1);
dfltBinomialSize = ones(M,1);
dfltOffset = zeros(M,1);
% 3.2 Optional parameter names and their default values.
paramNames = {'Weights', 'BinomialSize', 'Offset'};
paramDflts = {dfltWeights, dfltBinomialSize, dfltOffset};
% 3.3 Parse optional parameter name/value pairs.
[weights,binomsize,offset] = internal.stats.parseArgs(paramNames,paramDflts,otherArgs{:});
% 3.4 Validate optional parameter values.
weights = model.validateWeights(weights,M,model.Distribution);
binomsize = model.validateBinomialSize(binomsize,M);
offset = model.validateOffset(offset,M);
% 4. Validate ds.
predNames = model.PredictorNames;
varNames = model.Variables.Properties.VariableNames;
[~,predLocs] = ismember(predNames,varNames);
dsref = model.Variables(:,predLocs);
ds = model.validateDataset(ds,'DS',dsref);
% 5. Extract size info from model.
q = model.RandomInfo.q;
% 6. Get X and Z from ds.
% 6.1 Get X.
finfo = extractFixedInfo(model,ds);
X = finfo.X;
% 6.2 Get Z.
rinfo = extractRandomInfo(model,ds);
Z = rinfo.Z;
% 7. Get a R-by-1 cell vector Gid such that Gid{i} is the group
% IDs for grouping variable i. Also get a R-by-1 vector lev such
% that lev(i) is the number of levels of grouping variable i in the
% input data. Extract grouping variable info from ds. In ginfo,
% GidLevelNames may contain levels not previously seen during model
% fitting. That's okay, every level gets its own random effects
% vector.
ginfo = extractGroupingInfo(model,ds);
Gid = ginfo.Gid;
lev = ginfo.lev;
% 8. X already contains the fixed effects design matrix. Get the
% full sparse random effects design matrix Zs. This matrix will
% have sum_{i=1 to R} (q(i)*lev(i)) columns and M rows.
Zs = model.makeSparseZ(Z,q,lev,Gid,M);
% 9. Call random on the standard object. We want the random effects
% vector to be of size sum_{i=1 to R} (q(i)*lev(i)) - so pass in
% lev as the last input argument.
ynew = random(model.slme,[],X,Zs,offset,weights,binomsize,lev);
end % end of random.
end
% Abstract public methods from ParametricRegression.
methods(Access='public', Hidden=true)
function v = varianceParam(model) % a consistent name for the dispersion/MSE/whatever
v = model.Dispersion;
end
end
% Public methods from ParametricRegression.
methods(Access='public')
function [feci,reci] = coefCI(model,varargin)
%coefCI Confidence intervals for coefficients.
% FECI = coefCI(GLME) computes 95% confidence intervals for the fixed
% effects parameters in the generalized linear mixed effects model GLME.
% The output FECI is a P-by-2 matrix where P is the number of fixed
% effects parameters in GLME. Rows of FECI from top to bottom correspond
% respectively to the P-by-1 fixed effects vector BETA displayed from top
% to bottom in the tabular display from the fixedEffects method. Column 1
% of FECI displays lower confidence limits and column 2 of FECI displays
% upper confidence limits.
%
% [FECI,RECI] = coefCI(GLME) also returns 95% confidence intervals for
% the random effects parameters in GLME. The output RECI is a Q-by-2
% matrix where Q is the total number of random effects parameters in
% GLME. Rows of RECI from top to bottom correspond respectively to the
% Q-by-1 random effects vector B displayed from top to bottom in the
% tabular display from the randomEffects method. Column 1 of RECI
% displays lower confidence limits and column 2 of RECI displays upper
% confidence limits.
%
% [FECI,RECI] = coefCI(GLME,'PARAM1','VALUE1',...) accepts optional
% name/value pairs:
%
% 'Name' 'Value'
% 'Alpha' ALPHA, a number between 0 and 1. Computes
% 100*(1-ALPHA)% confidence intervals. Default is
% ALPHA=0.05 for 95% confidence intervals.
%
% 'DFMethod' Specifies the method to use for computing the
% approximate degrees of freedom DF for confidence
% interval calculation. Options are 'Residual' and
% 'None'. If 'DFMethod' is 'Residual', the DF values
% are assumed to be constant and equal to (N-P) where
% N is the number of observations and P is the number
% of fixed effects. If 'DFMethod' is 'None', then all
% DF values are set to infinity. Default is
% 'Residual'.
%
% coefCI uses an approximation to the conditional mean squared error of
% prediction (CMSEP) of the random effects to compute confidence
% intervals. This accounts for the uncertainty in the estimation of
% fixed effects but not the covariance parameters. An alternative
% interpretation of RECI is that they are Bayesian credible intervals
% using an approximation to the posterior distribution of random effects
% given the estimated covariance parameters and the response.
%
% Example: Fit a model with Weight as a fixed effect, and a random effect
% due to Model_Year. Compute confidence intervals for the
% intercept and the coefficient of Weight.
% load carsmall
% T = table(MPG,Weight,Model_Year);
% glme = fitglme(T,'MPG ~ Weight + (1|Model_Year)','Distribution','Normal')
% coefCI(glme)
%
% See also coefTest, fixedEffects, randomEffects, covarianceParameters.
switch nargout
case {0,1}
feci = coefCI@classreg.regr.LinearLikeMixedModel(model,varargin{:});
case 2
[feci,reci] = coefCI@classreg.regr.LinearLikeMixedModel(model,varargin{:});
end
end % end of coefCI.
function [P,F,DF1,DF2] = coefTest(model,H,c,varargin)
%coefTest Linear hypothesis test on coefficients.
% PVAL = coefTest(GLME) computes the p-value for an F test that all fixed
% effects parameters in the generalized linear mixed effects model GLME
% except the intercept are zero.
%
% PVAL = coefTest(GLME,H) computes the p-value for an F test on the fixed
% effects part of GLME using the M-by-P matrix, H where P is the number
% of fixed effects parameters in GLME. Each row of H represents 1
% contrast, and the columns of H from left to right correspond
% respectively to the P-by-1 fixed effects vector BETA displayed from top
% to bottom in the tabular display from the fixedEffects method. The
% output PVAL is the p-value for an F test that H*BETA = 0. To include
% contrasts that involve the random effects, use the 'REContrast'
% name-value pair.
%
% PVAL = coefTest(GLME,H,C) also specifies a M-by-1 vector C for testing
% the hypothesis H*BETA = C.
%
% PVAL = coefTest(GLME,H,C,PARAM1,VALUE1,...) accepts optional name/value
% pairs to control the calculation of PVAL.
%
% Name Value
% 'DFMethod' A string that specifies the method to use for
% computing the approximate denominator degrees of
% freedom DF for the F test. If 'DFMethod' is
% 'Residual', the DF value is assumed to be equal to
% (N-P) where N is the number of observations and P is
% the number of fixed effects. If 'DFMethod' is
% 'None', then the DF value is taken to be infinity.
% Default is 'Residual'.
%
% 'REContrast' A M-by-Q matrix K where Q is the number of random
% effects parameters in GLME. Each row of K represents
% 1 contrast and the columns of K from left to right
% correspond respectively to the Q-by-1 random effects
% vector B displayed from top to bottom in the tabular
% display from the randomEffects method. The output
% PVAL is the p-value for an F test H*BETA + K*B = C.
%
% [PVAL,F,DF1,DF2] = coefTest(...) also returns the F-statistic F, the
% numerator degrees of freedom DF1 for F, and the denominator degrees of
% freedom DF2 for F. DF1 is equal to the number of linearly independent
% rows in H, or in [H,K] if you use the 'REContrast' name-value pair. The
% value of DF2 depends on the option selected for 'DFMethod'.
%
% coefTest uses an approximation to the conditional mean squared error of
% prediction (CMSEP) of the estimated linear combination of fixed and
% random effects to compute p-values. This accounts for the uncertainty
% in the estimation of fixed effects but not the covariance parameters.
%
% Example: Fit a model with two fixed-effect predictors and a random
% effect. Test for the significance of the Cylinders term. The
% p-value is the same as shown in the anova table.
% load carsmall
% T = table(MPG,Weight,Model_Year,Cylinders);
% T.Cylinders = nominal(T.Cylinders);
% glme = fitglme(T,'MPG ~ Weight + Cylinders + (1|Model_Year)','Distribution','Normal')
% p = coefTest(glme,[0 0 1 0;0 0 0 1])
% anova(glme)
%
% % Test for no difference between 6-cylinder and 8-cylinder cars
% coefTest(glme,[0 0 1 -1])
%
% See also anova, coefCI, fixedEffects, randomEffects, covarianceParameters.
if nargin < 2
% Called like: coefTest(model)
args = {};
elseif nargin < 3
% Called like: coefTest(model,H)
args = {H};
elseif nargin < 4
% Called like: coefTest(model,H,C)
args = {H,c};
else
% Called like: coefTest(model,H,C,PARAM1,VALUE1,...)
args = [{H,c},varargin];
end
[P,F,DF1,DF2] = coefTest@classreg.regr.LinearLikeMixedModel(model,args{:});
end % end of coefTest.
end
% Other inherited abstract, protected methods.
methods(Access='protected')
function model = fitter(model)% subclass-specific fitting algorithm, must fill in Coefs, CoefficientCovariance, and DFE
% 1. Save names for the big sparse Zs used to fit a standard GLME.
model.RandomInfo.ZsColNames = makeSparseZNames(model);
% 2. Fit a GLME model in standard form.
model.slme = fitStandardLMEModel(model);
% 3. Fill in DFE and Coefs so that get.NumCoefficients and
% get.NumEstimatedCoefficients in ParametricRegression work as
% required. Also fill in CoefficientCovariance.
model.Coefs = model.slme.betaHat;
N = model.NumObservations; % only contribution from subset.
P = length(model.Coefs);
model.DFE = N - P;
model.CoefficientCovariance = model.slme.covbetaHat;
end % end of fitter.
% The predict method would normally take a dataset/table array or a
% matrix containing all variables. This method exists to allow
% prediction with a matrix that contains only the required predictor
% variables without blowing it up to contain all the variables only to
% then pull it apart to get the design matrix.
function ypred = predictPredictorMatrix(model,Xpred) %#ok<INUSD>
ypred = [];
end % end of predictPredictorMatrix.
function D = get_diagnostics(model,type) %#ok<INUSD>
D = [];
end % end of get_diagnostics.
function L = getlogLikelihood(model)
% L will be the maximized pseudo log likelihood for PL based
% methods and the maximized log likelihood for ML based methods.
L = model.ModelCriterion.LogLikelihood;
end % end of getlogLikelihood.
function L0 = logLikelihoodNull(model) %#ok<MANU>
L0 = NaN;
end % end of logLikelihoodNull.
end
% Other inherited protected methods that we choose to redefine.
methods(Access='protected')
function model = postFit(model)
% 1. Set Dispersion, DispersionEstimated and Response.
model.Dispersion = (model.slme.sigmaHat)^2;
if ( model.slme.isSigmaFixed == true )
model.DispersionEstimated = false;
else
model.DispersionEstimated = true;
end
model.Response = response(model);
% 2. Fill in the log likelihoods.
model.LogLikelihood = getlogLikelihood(model);
model.LogLikelihoodNull = logLikelihoodNull(model);
% 3. Get SSE, SST and SSR.
[model.SSE,model.SSR,model.SST] = getSumOfSquares(model);
% 4. Get CoefficientNames.
model.CoefficientNames = getCoefficientNames(model);
% 5. Save a table of covariance parameters in the object. Computing
% the CIs on covariance parameters can be expensive - save the
% covariance parameters table without the CIs.
[~,~,model.CovarianceTable] = covarianceParameters(model,'WantCIs',false);
% 6. Fill out BinomSize in model.ObservationInfo for consistency
% with GeneralizedLinearModel.
subset = model.ObservationInfo.Subset;
N = length(subset);
model.ObservationInfo.BinomSize = ones(N,1);
model.ObservationInfo.BinomSize(subset) = model.BinomialSize;
end
function model = selectVariables(model)
f = model.Formula;
[~,model.PredLocs] = ismember(f.PredictorNames,f.VariableNames);
[~,model.RespLoc] = ismember(f.ResponseName,f.VariableNames);
model = selectVariables@classreg.regr.ParametricRegression(model);
end
end
% Dependent property get methods that we choose to redefine indirectly by
% overloading the methods that will be called in get.property methods in
% superclasses.
methods(Access='protected')
% (1) get.NumCoefficients in ParametricRegression will work if
% model.Coefs is well defined.
% (2) get.NumEstimatedCoefficients in ParametricRegression will work if
% model.DFE is well defined.
% (3) Called by get.Coefficients.
function table = tstats(model)
[~,~,table] = fixedEffects(model);
end % end of tstats.
% (4) Called by get.Rsquared. The inherited get_rsquared should work
% provided model.SSE, model.SST, model.DFE, model.NumObservations,
% model.LogLikelihood and model.LogLikelihoodNull have sensible values.
% Not definig a new get_rquared and using the default one.
%function rsq = get_rsquared(model)