forked from pymc-devs/pymc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
1781 lines (1475 loc) · 63.4 KB
/
model.py
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
# Copyright 2020 The PyMC Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
import itertools
import threading
import warnings
from sys import modules
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
)
import aesara
import aesara.sparse as sparse
import aesara.tensor as at
import numpy as np
import scipy.sparse as sps
from aesara.compile.sharedvalue import SharedVariable
from aesara.gradient import grad
from aesara.graph.basic import Constant, Variable, graph_inputs
from aesara.graph.fg import FunctionGraph, MissingInputError
from aesara.tensor.random.opt import local_subtensor_rv_lift
from aesara.tensor.sharedvar import ScalarSharedVariable
from aesara.tensor.var import TensorVariable
from pandas import Series
from pymc3.aesaraf import (
change_rv_size,
gradient,
hessian,
inputvars,
pandas_to_array,
rvs_to_value_vars,
)
from pymc3.blocking import DictToArrayBijection, RaveledVars
from pymc3.data import GenTensorVariable, Minibatch
from pymc3.distributions import logp_transform, logpt, logpt_sum
from pymc3.exceptions import ImputationWarning, SamplingError, ShapeError
from pymc3.math import flatten_list
from pymc3.util import UNSET, WithMemoization, get_var_name, treedict, treelist
from pymc3.vartypes import continuous_types, discrete_types, typefilter
__all__ = [
"Model",
"Factor",
"compilef",
"fn",
"fastfn",
"modelcontext",
"Point",
"Deterministic",
"Potential",
"set_data",
]
FlatView = collections.namedtuple("FlatView", "input, replacements")
class InstanceMethod:
"""Class for hiding references to instance methods so they can be pickled.
>>> self.method = InstanceMethod(some_object, 'method_name')
"""
def __init__(self, obj, method_name):
self.obj = obj
self.method_name = method_name
def __call__(self, *args, **kwargs):
return getattr(self.obj, self.method_name)(*args, **kwargs)
def incorporate_methods(source, destination, methods, wrapper=None, override=False):
"""
Add attributes to a destination object which point to
methods from from a source object.
Parameters
----------
source: object
The source object containing the methods.
destination: object
The destination object for the methods.
methods: list of str
Names of methods to incorporate.
wrapper: function
An optional function to allow the source method to be
wrapped. Should take the form my_wrapper(source, method_name)
and return a single value.
override: bool
If the destination object already has a method/attribute
an AttributeError will be raised if override is False (the default).
"""
for method in methods:
if hasattr(destination, method) and not override:
raise AttributeError(
f"Cannot add method {method!r}" + "to destination object as it already exists. "
"To prevent this error set 'override=True'."
)
if hasattr(source, method):
if wrapper is None:
setattr(destination, method, getattr(source, method))
else:
setattr(destination, method, wrapper(source, method))
else:
setattr(destination, method, None)
T = TypeVar("T", bound="ContextMeta")
class ContextMeta(type):
"""Functionality for objects that put themselves in a context using
the `with` statement.
"""
def __new__(cls, name, bases, dct, **kargs): # pylint: disable=unused-argument
"Add __enter__ and __exit__ methods to the class."
def __enter__(self):
self.__class__.context_class.get_contexts().append(self)
# self._aesara_config is set in Model.__new__
self._config_context = None
if hasattr(self, "_aesara_config"):
self._config_context = aesara.config.change_flags(**self._aesara_config)
self._config_context.__enter__()
return self
def __exit__(self, typ, value, traceback): # pylint: disable=unused-argument
self.__class__.context_class.get_contexts().pop()
# self._aesara_config is set in Model.__new__
if self._config_context:
self._config_context.__exit__(typ, value, traceback)
dct[__enter__.__name__] = __enter__
dct[__exit__.__name__] = __exit__
# We strip off keyword args, per the warning from
# StackExchange:
# DO NOT send "**kargs" to "type.__new__". It won't catch them and
# you'll get a "TypeError: type() takes 1 or 3 arguments" exception.
return super().__new__(cls, name, bases, dct)
# FIXME: is there a more elegant way to automatically add methods to the class that
# are instance methods instead of class methods?
def __init__(
cls, name, bases, nmspc, context_class: Optional[Type] = None, **kwargs
): # pylint: disable=unused-argument
"""Add ``__enter__`` and ``__exit__`` methods to the new class automatically."""
if context_class is not None:
cls._context_class = context_class
super().__init__(name, bases, nmspc)
def get_context(cls, error_if_none=True) -> Optional[T]:
"""Return the most recently pushed context object of type ``cls``
on the stack, or ``None``. If ``error_if_none`` is True (default),
raise a ``TypeError`` instead of returning ``None``."""
try:
candidate = cls.get_contexts()[-1] # type: Optional[T]
except IndexError as e:
# Calling code expects to get a TypeError if the entity
# is unfound, and there's too much to fix.
if error_if_none:
raise TypeError("No %s on context stack" % str(cls))
return None
return candidate
def get_contexts(cls) -> List[T]:
"""Return a stack of context instances for the ``context_class``
of ``cls``."""
# This lazily creates the context class's contexts
# thread-local object, as needed. This seems inelegant to me,
# but since the context class is not guaranteed to exist when
# the metaclass is being instantiated, I couldn't figure out a
# better way. [2019/10/11:rpg]
# no race-condition here, contexts is a thread-local object
# be sure not to override contexts in a subclass however!
context_class = cls.context_class
assert isinstance(context_class, type), (
"Name of context class, %s was not resolvable to a class" % context_class
)
if not hasattr(context_class, "contexts"):
context_class.contexts = threading.local()
contexts = context_class.contexts
if not hasattr(contexts, "stack"):
contexts.stack = []
return contexts.stack
# the following complex property accessor is necessary because the
# context_class may not have been created at the point it is
# specified, so the context_class may be a class *name* rather
# than a class.
@property
def context_class(cls) -> Type:
def resolve_type(c: Union[Type, str]) -> Type:
if isinstance(c, str):
c = getattr(modules[cls.__module__], c)
if isinstance(c, type):
return c
raise ValueError("Cannot resolve context class %s" % c)
assert cls is not None
if isinstance(cls._context_class, str):
cls._context_class = resolve_type(cls._context_class)
if not isinstance(cls._context_class, (str, type)):
raise ValueError(
"Context class for %s, %s, is not of the right type"
% (cls.__name__, cls._context_class)
)
return cls._context_class
# Inherit context class from parent
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.context_class = super().context_class
# Initialize object in its own context...
# Merged from InitContextMeta in the original.
def __call__(cls, *args, **kwargs):
instance = cls.__new__(cls, *args, **kwargs)
with instance: # appends context
instance.__init__(*args, **kwargs)
return instance
def modelcontext(model: Optional["Model"]) -> "Model":
"""
Return the given model or, if none was supplied, try to find one in
the context stack.
"""
if model is None:
model = Model.get_context(error_if_none=False)
if model is None:
# TODO: This should be a ValueError, but that breaks
# ArviZ (and others?), so might need a deprecation.
raise TypeError("No model on context stack.")
return model
class Factor:
"""Common functionality for objects with a log probability density
associated with them.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def logp(self):
"""Compiled log probability density function"""
return self.model.fn(self.logpt)
@property
def logp_elemwise(self):
return self.model.fn(self.logp_elemwiset)
def dlogp(self, vars=None):
"""Compiled log probability density gradient function"""
return self.model.fn(gradient(self.logpt, vars))
def d2logp(self, vars=None):
"""Compiled log probability density hessian function"""
return self.model.fn(hessian(self.logpt, vars))
@property
def logp_nojac(self):
return self.model.fn(self.logp_nojact)
def dlogp_nojac(self, vars=None):
"""Compiled log density gradient function, without jacobian terms."""
return self.model.fn(gradient(self.logp_nojact, vars))
def d2logp_nojac(self, vars=None):
"""Compiled log density hessian function, without jacobian terms."""
return self.model.fn(hessian(self.logp_nojact, vars))
@property
def fastlogp(self):
"""Compiled log probability density function"""
return self.model.fastfn(self.logpt)
def fastdlogp(self, vars=None):
"""Compiled log probability density gradient function"""
return self.model.fastfn(gradient(self.logpt, vars))
def fastd2logp(self, vars=None):
"""Compiled log probability density hessian function"""
return self.model.fastfn(hessian(self.logpt, vars))
@property
def fastlogp_nojac(self):
return self.model.fastfn(self.logp_nojact)
def fastdlogp_nojac(self, vars=None):
"""Compiled log density gradient function, without jacobian terms."""
return self.model.fastfn(gradient(self.logp_nojact, vars))
def fastd2logp_nojac(self, vars=None):
"""Compiled log density hessian function, without jacobian terms."""
return self.model.fastfn(hessian(self.logp_nojact, vars))
@property
def logpt(self):
"""Aesara scalar of log-probability of the model"""
if getattr(self, "total_size", None) is not None:
logp = self.logp_sum_unscaledt * self.scaling
else:
logp = self.logp_sum_unscaledt
if self.name is not None:
logp.name = "__logp_%s" % self.name
return logp
@property
def logp_nojact(self):
"""Aesara scalar of log-probability, excluding jacobian terms."""
if getattr(self, "total_size", None) is not None:
logp = at.sum(self.logp_nojac_unscaledt) * self.scaling
else:
logp = at.sum(self.logp_nojac_unscaledt)
if self.name is not None:
logp.name = "__logp_%s" % self.name
return logp
class ValueGradFunction:
"""Create an Aesara function that computes a value and its gradient.
Parameters
----------
costs: list of Aesara variables
We compute the weighted sum of the specified Aesara values, and the gradient
of that sum. The weights can be specified with `ValueGradFunction.set_weights`.
grad_vars: list of named Aesara variables or None
The arguments with respect to which the gradient is computed.
extra_vars_and_values: dict of Aesara variables and their initial values
Other arguments of the function that are assumed constant and their
values. They are stored in shared variables and can be set using
`set_extra_values`.
dtype: str, default=aesara.config.floatX
The dtype of the arrays.
casting: {'no', 'equiv', 'save', 'same_kind', 'unsafe'}, default='no'
Casting rule for casting `grad_args` to the array dtype.
See `numpy.can_cast` for a description of the options.
Keep in mind that we cast the variables to the array *and*
back from the array dtype to the variable dtype.
compute_grads: bool, default=True
If False, return only the logp, not the gradient.
kwargs
Extra arguments are passed on to `aesara.function`.
Attributes
----------
profile: Aesara profiling object or None
The profiling object of the Aesara function that computes value and
gradient. This is None unless `profile=True` was set in the
kwargs.
"""
def __init__(
self,
costs,
grad_vars,
extra_vars_and_values=None,
*,
dtype=None,
casting="no",
compute_grads=True,
**kwargs,
):
if extra_vars_and_values is None:
extra_vars_and_values = {}
names = [arg.name for arg in grad_vars + list(extra_vars_and_values.keys())]
if any(name is None for name in names):
raise ValueError("Arguments must be named.")
if len(set(names)) != len(names):
raise ValueError("Names of the arguments are not unique.")
self._grad_vars = grad_vars
self._extra_vars = list(extra_vars_and_values.keys())
self._extra_var_names = {var.name for var in extra_vars_and_values.keys()}
if dtype is None:
dtype = aesara.config.floatX
self.dtype = dtype
self._n_costs = len(costs)
if self._n_costs == 0:
raise ValueError("At least one cost is required.")
weights = np.ones(self._n_costs - 1, dtype=self.dtype)
self._weights = aesara.shared(weights, "__weights")
cost = costs[0]
for i, val in enumerate(costs[1:]):
if cost.ndim > 0 or val.ndim > 0:
raise ValueError("All costs must be scalar.")
cost = cost + self._weights[i] * val
self._extra_are_set = False
for var in self._grad_vars:
if not np.can_cast(var.dtype, self.dtype, casting):
raise TypeError(
f"Invalid dtype for variable {var.name}. Can not "
f"cast to {self.dtype} with casting rule {casting}."
)
if not np.issubdtype(var.dtype, np.floating):
raise TypeError(
f"Invalid dtype for variable {var.name}. Must be "
f"floating point but is {var.dtype}."
)
givens = []
self._extra_vars_shared = {}
for var, value in extra_vars_and_values.items():
shared = aesara.shared(
value, var.name + "_shared__", broadcastable=[s == 1 for s in value.shape]
)
self._extra_vars_shared[var.name] = shared
givens.append((var, shared))
if compute_grads:
grads = grad(cost, grad_vars, disconnected_inputs="ignore")
for grad_wrt, var in zip(grads, grad_vars):
grad_wrt.name = f"{var.name}_grad"
outputs = [cost] + grads
else:
outputs = [cost]
inputs = grad_vars
self._aesara_function = aesara.function(inputs, outputs, givens=givens, **kwargs)
def set_weights(self, values):
if values.shape != (self._n_costs - 1,):
raise ValueError("Invalid shape. Must be (n_costs - 1,).")
self._weights.set_value(values)
def set_extra_values(self, extra_vars):
self._extra_are_set = True
for var in self._extra_vars:
self._extra_vars_shared[var.name].set_value(extra_vars[var.name])
def get_extra_values(self):
if not self._extra_are_set:
raise ValueError("Extra values are not set.")
return {var.name: self._extra_vars_shared[var.name].get_value() for var in self._extra_vars}
def __call__(self, grad_vars, grad_out=None, extra_vars=None):
if extra_vars is not None:
self.set_extra_values(extra_vars)
if not self._extra_are_set:
raise ValueError("Extra values are not set.")
if isinstance(grad_vars, RaveledVars):
grad_vars = list(DictToArrayBijection.rmap(grad_vars).values())
cost, *grads = self._aesara_function(*grad_vars)
if grads:
grads_raveled = DictToArrayBijection.map(
{v.name: gv for v, gv in zip(self._grad_vars, grads)}
)
if grad_out is None:
return cost, grads_raveled.data
else:
np.copyto(grad_out, grads_raveled.data)
return cost
else:
return cost
@property
def profile(self):
"""Profiling information of the underlying Aesara function."""
return self._aesara_function.profile
class Model(Factor, WithMemoization, metaclass=ContextMeta):
"""Encapsulates the variables and likelihood factors of a model.
Model class can be used for creating class based models. To create
a class based model you should inherit from :class:`~.Model` and
override :meth:`~.__init__` with arbitrary definitions (do not
forget to call base class :meth:`__init__` first).
Parameters
----------
name: str
name that will be used as prefix for names of all random
variables defined within model
model: Model
instance of Model that is supposed to be a parent for the new
instance. If ``None``, context will be used. All variables
defined within instance will be passed to the parent instance.
So that 'nested' model contributes to the variables and
likelihood factors of parent model.
aesara_config: dict
A dictionary of Aesara config values that should be set
temporarily in the model context. See the documentation
of Aesara for a complete list.
check_bounds: bool
Ensure that input parameters to distributions are in a valid
range. If your model is built in a way where you know your
parameters can only take on valid values you can set this to
False for increased speed. This should not be used if your model
contains discrete variables.
Examples
--------
How to define a custom model
.. code-block:: python
class CustomModel(Model):
# 1) override init
def __init__(self, mean=0, sigma=1, name='', model=None):
# 2) call super's init first, passing model and name
# to it name will be prefix for all variables here if
# no name specified for model there will be no prefix
super().__init__(name, model)
# now you are in the context of instance,
# `modelcontext` will return self you can define
# variables in several ways note, that all variables
# will get model's name prefix
# 3) you can create variables with Var method
self.Var('v1', Normal.dist(mu=mean, sigma=sd))
# this will create variable named like '{prefix_}v1'
# and assign attribute 'v1' to instance created
# variable can be accessed with self.v1 or self['v1']
# 4) this syntax will also work as we are in the
# context of instance itself, names are given as usual
Normal('v2', mu=mean, sigma=sd)
# something more complex is allowed, too
half_cauchy = HalfCauchy('sd', beta=10, testval=1.)
Normal('v3', mu=mean, sigma=half_cauchy)
# Deterministic variables can be used in usual way
Deterministic('v3_sq', self.v3 ** 2)
# Potentials too
Potential('p1', at.constant(1))
# After defining a class CustomModel you can use it in several
# ways
# I:
# state the model within a context
with Model() as model:
CustomModel()
# arbitrary actions
# II:
# use new class as entering point in context
with CustomModel() as model:
Normal('new_normal_var', mu=1, sigma=0)
# III:
# just get model instance with all that was defined in it
model = CustomModel()
# IV:
# use many custom models within one context
with Model() as model:
CustomModel(mean=1, name='first')
CustomModel(mean=2, name='second')
"""
if TYPE_CHECKING:
def __enter__(self: "Model") -> "Model":
...
def __exit__(self: "Model", *exc: Any) -> bool:
...
def __new__(cls, *args, **kwargs):
# resolves the parent instance
instance = super().__new__(cls)
if kwargs.get("model") is not None:
instance._parent = kwargs.get("model")
else:
instance._parent = cls.get_context(error_if_none=False)
instance._aesara_config = kwargs.get("aesara_config", {})
return instance
def __init__(self, name="", model=None, aesara_config=None, coords=None, check_bounds=True):
self.name = name
self._coords = {}
self._RV_dims = {}
self._dim_lengths = {}
self.add_coords(coords)
self.check_bounds = check_bounds
self.default_rng = aesara.shared(np.random.RandomState(), name="default_rng", borrow=True)
self.default_rng.tag.is_rng = True
self.default_rng.default_update = self.default_rng
if self.parent is not None:
self.named_vars = treedict(parent=self.parent.named_vars)
self.values_to_rvs = treedict(parent=self.parent.values_to_rvs)
self.rvs_to_values = treedict(parent=self.parent.rvs_to_values)
self.free_RVs = treelist(parent=self.parent.free_RVs)
self.observed_RVs = treelist(parent=self.parent.observed_RVs)
self.auto_deterministics = treelist(parent=self.parent.auto_deterministics)
self.deterministics = treelist(parent=self.parent.deterministics)
self.potentials = treelist(parent=self.parent.potentials)
else:
self.named_vars = treedict()
self.values_to_rvs = treedict()
self.rvs_to_values = treedict()
self.free_RVs = treelist()
self.observed_RVs = treelist()
self.auto_deterministics = treelist()
self.deterministics = treelist()
self.potentials = treelist()
@property
def model(self):
return self
@property
def parent(self):
return self._parent
@property
def root(self):
model = self
while not model.isroot:
model = model.parent
return model
@property
def isroot(self):
return self.parent is None
@property
def ndim(self):
return sum(var.ndim for var in self.value_vars)
def logp_dlogp_function(self, grad_vars=None, tempered=False, **kwargs):
"""Compile an Aesara function that computes logp and gradient.
Parameters
----------
grad_vars: list of random variables, optional
Compute the gradient with respect to those variables. If None,
use all free random variables of this model.
tempered: bool
Compute the tempered logp `free_logp + alpha * observed_logp`.
`alpha` can be changed using `ValueGradFunction.set_weights([alpha])`.
"""
if grad_vars is None:
grad_vars = [v.tag.value_var for v in typefilter(self.free_RVs, continuous_types)]
else:
for i, var in enumerate(grad_vars):
if var.dtype not in continuous_types:
raise ValueError("Can only compute the gradient of continuous types: %s" % var)
# We allow one to pass the random variable terms as arguments
if hasattr(var.tag, "value_var"):
grad_vars[i] = var.tag.value_var
if tempered:
with self:
# Convert random variables into their log-likelihood inputs and
# apply their transforms, if any
potentials, _ = rvs_to_value_vars(self.potentials, apply_transforms=True)
free_RVs_logp = at.sum(
[at.sum(logpt(var, self.rvs_to_values.get(var, None))) for var in self.free_RVs]
+ list(potentials)
)
observed_RVs_logp = at.sum(
[at.sum(logpt(obs, obs.tag.observations)) for obs in self.observed_RVs]
)
costs = [free_RVs_logp, observed_RVs_logp]
else:
costs = [self.logpt]
input_vars = {i for i in graph_inputs(costs) if not isinstance(i, Constant)}
extra_vars = [self.rvs_to_values.get(var, var) for var in self.free_RVs]
extra_vars_and_values = {
var: self.initial_point[var.name]
for var in extra_vars
if var in input_vars and var not in grad_vars
}
return ValueGradFunction(costs, grad_vars, extra_vars_and_values, **kwargs)
@property
def logpt(self):
"""Aesara scalar of log-probability of the model"""
with self:
factors = [logpt_sum(var, self.rvs_to_values.get(var, None)) for var in self.free_RVs]
factors += [logpt_sum(obs, obs.tag.observations) for obs in self.observed_RVs]
# Convert random variables into their log-likelihood inputs and
# apply their transforms, if any
potentials, _ = rvs_to_value_vars(self.potentials, apply_transforms=True)
factors += potentials
logp_var = at.sum([at.sum(factor) for factor in factors])
if self.name:
logp_var.name = "__logp_%s" % self.name
else:
logp_var.name = "__logp"
return logp_var
@property
def logp_nojact(self):
"""Aesara scalar of log-probability of the model but without the jacobian
if transformed Random Variable is presented.
Note that if there is no transformed variable in the model, logp_nojact
will be the same as logpt as there is no need for Jacobian correction.
"""
with self:
factors = [
logpt_sum(var, getattr(var.tag, "value_var", None), jacobian=False)
for var in self.free_RVs
]
factors += [
logpt_sum(obs, obs.tag.observations, jacobian=False) for obs in self.observed_RVs
]
# Convert random variables into their log-likelihood inputs and
# apply their transforms, if any
potentials, _ = rvs_to_value_vars(self.potentials, apply_transforms=True)
factors += potentials
logp_var = at.sum([at.sum(factor) for factor in factors])
if self.name:
logp_var.name = "__logp_nojac_%s" % self.name
else:
logp_var.name = "__logp_nojac"
return logp_var
@property
def varlogpt(self):
"""Aesara scalar of log-probability of the unobserved random variables
(excluding deterministic)."""
with self:
factors = [logpt_sum(var, getattr(var.tag, "value_var", None)) for var in self.free_RVs]
return at.sum(factors)
@property
def datalogpt(self):
with self:
factors = [logpt(obs, obs.tag.observations) for obs in self.observed_RVs]
# Convert random variables into their log-likelihood inputs and
# apply their transforms, if any
potentials, _ = rvs_to_value_vars(self.potentials, apply_transforms=True)
factors += [at.sum(factor) for factor in potentials]
return at.sum(factors)
@property
def vars(self):
warnings.warn(
"Model.vars has been deprecated. Use Model.value_vars instead.",
DeprecationWarning,
)
return self.value_vars
@property
def value_vars(self):
"""List of unobserved random variables used as inputs to the model's
log-likelihood (which excludes deterministics).
"""
return [self.rvs_to_values[v] for v in self.free_RVs]
@property
def unobserved_value_vars(self):
"""List of all random variables (including untransformed projections),
as well as deterministics used as inputs and outputs of the the model's
log-likelihood graph
"""
vars = []
for rv in self.free_RVs:
value_var = self.rvs_to_values[rv]
transform = getattr(value_var.tag, "transform", None)
if transform is not None:
# We need to create and add an un-transformed version of
# each transformed variable
untrans_value_var = transform.backward(rv, value_var)
untrans_value_var.name = rv.name
vars.append(untrans_value_var)
vars.append(value_var)
# Remove rvs from deterministics graph
deterministics, _ = rvs_to_value_vars(self.deterministics, apply_transforms=True)
return vars + deterministics
@property
def basic_RVs(self):
"""List of random variables the model is defined in terms of
(which excludes deterministics).
These are the actual random variable terms that make up the
"sample-space" graph (i.e. you can sample these graphs by compiling them
with `aesara.function`). If you want the corresponding log-likelihood terms,
use `var.tag.value_var`.
"""
return self.free_RVs + self.observed_RVs
@property
def RV_dims(self) -> Dict[str, Tuple[Union[str, None], ...]]:
"""Tuples of dimension names for specific model variables.
Entries in the tuples may be ``None``, if the RV dimension was not given a name.
"""
return self._RV_dims
@property
def coords(self) -> Dict[str, Union[Sequence, None]]:
"""Coordinate values for model dimensions."""
return self._coords
@property
def dim_lengths(self) -> Dict[str, Tuple[Variable, ...]]:
"""The symbolic lengths of dimensions in the model.
The values are typically instances of ``TensorVariable`` or ``ScalarSharedVariable``.
"""
return self._dim_lengths
@property
def unobserved_RVs(self):
"""List of all random variables, including deterministic ones.
These are the actual random variable terms that make up the
"sample-space" graph (i.e. you can sample these graphs by compiling them
with `aesara.function`). If you want the corresponding log-likelihood terms,
use `var.tag.value_var`.
"""
return self.free_RVs + self.deterministics
@property
def independent_vars(self):
"""List of all variables that are non-stochastic inputs to the model.
These are the actual random variable terms that make up the
"sample-space" graph (i.e. you can sample these graphs by compiling them
with `aesara.function`). If you want the corresponding log-likelihood terms,
use `var.tag.value_var`.
"""
return inputvars(self.unobserved_RVs)
@property
def test_point(self):
warnings.warn(
"`Model.test_point` has been deprecated. Use `Model.initial_point` instead.",
DeprecationWarning,
)
return self.initial_point
@property
def initial_point(self):
points = []
for rv_var in self.free_RVs:
value_var = rv_var.tag.value_var
var_value = getattr(value_var.tag, "test_value", None)
if var_value is None:
rv_var_value = getattr(rv_var.tag, "test_value", None)
if rv_var_value is None:
try:
rv_var_value = rv_var.eval()
except MissingInputError:
raise MissingInputError(f"Couldn't generate an initial value for {rv_var}")
transform = getattr(value_var.tag, "transform", None)
if transform:
try:
rv_var_value = transform.forward(rv_var, rv_var_value).eval()
except MissingInputError:
raise MissingInputError(f"Couldn't generate an initial value for {rv_var}")
var_value = rv_var_value
value_var.tag.test_value = var_value
points.append((value_var, var_value))
return Point(points, model=self)
@property
def disc_vars(self):
"""All the discrete variables in the model"""
return list(typefilter(self.value_vars, discrete_types))
@property
def cont_vars(self):
"""All the continuous variables in the model"""
return list(typefilter(self.value_vars, continuous_types))
def shape_from_dims(self, dims):
shape = []
if len(set(dims)) != len(dims):
raise ValueError("Can not contain the same dimension name twice.")
for dim in dims:
if dim not in self.coords:
raise ValueError(
"Unknown dimension name '%s'. All dimension "
"names must be specified in the `coords` "
"argument of the model or through a pm.Data "
"variable." % dim
)
shape.extend(np.shape(self.coords[dim]))
return tuple(shape)
def add_coord(
self,
name: str,
values: Optional[Sequence] = None,
*,
length: Optional[Variable] = None,
):
"""Registers a dimension coordinate with the model.
Parameters
----------
name : str
Name of the dimension.
Forbidden: {"chain", "draw"}
values : optional, array-like
Coordinate values or ``None`` (for auto-numbering).
If ``None`` is passed, a ``length`` must be specified.
length : optional, scalar
A symbolic scalar of the dimensions length.
Defaults to ``aesara.shared(len(values))``.
"""
if name in {"draw", "chain"}:
raise ValueError(
"Dimensions can not be named `draw` or `chain`, as they are reserved for the sampler's outputs."
)
if values is None and length is None:
raise ValueError(
f"Either `values` or `length` must be specified for the '{name}' dimension."
)
if length is not None and not isinstance(length, Variable):
raise ValueError(
f"The `length` passed for the '{name}' coord must be an Aesara Variable or None."
)
if name in self.coords:
if not values.equals(self.coords[name]):
raise ValueError("Duplicate and incompatiple coordinate: %s." % name)
else:
self._coords[name] = values
self._dim_lengths[name] = length or aesara.shared(len(values))
def add_coords(
self,
coords: Dict[str, Optional[Sequence]],
*,
lengths: Optional[Dict[str, Union[Variable, None]]] = None,
):
"""Vectorized version of ``Model.add_coord``."""
if coords is None:
return
lengths = lengths or {}
for name, values in coords.items():