forked from pymc-devs/pymc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
2034 lines (1710 loc) · 68.7 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, List, Optional, Type, TypeVar, Union, cast
import numpy as np
import scipy.sparse as sps
import theano
import theano.graph.basic
import theano.sparse as sparse
import theano.tensor as tt
from pandas import Series
from theano.compile import SharedVariable
from theano.graph.basic import Apply
from theano.tensor.var import TensorVariable
import pymc3 as pm
from pymc3.blocking import ArrayOrdering, DictToArrayBijection
from pymc3.exceptions import ImputationWarning
from pymc3.math import flatten_list
from pymc3.memoize import WithMemoization, memoize
from pymc3.theanof import floatX, generator, gradient, hessian, inputvars
from pymc3.util import get_transformed_name, get_var_name
from pymc3.vartypes import continuous_types, discrete_types, isgenerator, typefilter
__all__ = [
"Model",
"Factor",
"compilef",
"fn",
"fastfn",
"modelcontext",
"Point",
"Deterministic",
"Potential",
"set_data",
]
FlatView = collections.namedtuple("FlatView", "input, replacements, view")
class PyMC3Variable(TensorVariable):
"""Class to wrap Theano TensorVariable for custom behavior."""
# Implement matrix multiplication infix operator: X @ w
__matmul__ = tt.dot
def __rmatmul__(self, other):
return tt.dot(other, self)
def _str_repr(self, name=None, dist=None, formatting="plain"):
if getattr(self, "distribution", None) is None:
if "latex" in formatting:
return None
else:
return super().__str__()
if name is None and hasattr(self, "name"):
name = self.name
if dist is None and hasattr(self, "distribution"):
dist = self.distribution
return self.distribution._str_repr(name=name, dist=dist, formatting=formatting)
def _repr_latex_(self, *, formatting="latex_with_params", **kwargs):
return self._str_repr(formatting=formatting, **kwargs)
def __str__(self, **kwargs):
try:
return self._str_repr(formatting="plain", **kwargs)
except:
return super().__str__()
__latex__ = _repr_latex_
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)
def get_named_nodes_and_relations(graph):
"""Get the named nodes in a theano graph (i.e., nodes whose name
attribute is not None) along with their relationships (i.e., the
node's named parents, and named children, while skipping unnamed
intermediate nodes)
Parameters
----------
graph: a theano node
Returns:
--------
leaf_dict: Dict[str, node]
A dictionary of name:node pairs, of the named nodes that
have no named ancestors in the provided theano graph.
descendents: Dict[node, Set[node]]
Each key is a theano named node, and the corresponding value
is the set of theano named nodes that are descendents with no
intervening named nodes in the supplied ``graph``.
ancestors: Dict[node, Set[node]]
A dictionary of node:set([ancestors]) pairs. Each key
is a theano named node, and the corresponding value is the set
of theano named nodes that are ancestors with no intervening named
nodes in the supplied ``graph``.
"""
# We don't enforce distribution parameters to have a name but we may
# attempt to get_named_nodes_and_relations from them anyway in
# distributions.draw_values. This means that must take care only to add
# graph to the ancestors and descendents dictionaries if it has a name.
if graph.name is not None:
ancestors = {graph: set()}
descendents = {graph: set()}
else:
ancestors = {}
descendents = {}
descendents, ancestors = _get_named_nodes_and_relations(graph, None, ancestors, descendents)
leaf_dict = {node.name: node for node, ancestor in ancestors.items() if len(ancestor) == 0}
return leaf_dict, descendents, ancestors
def _get_named_nodes_and_relations(graph, descendent, descendents, ancestors):
if getattr(graph, "owner", None) is None: # Leaf node
if graph.name is not None: # Named leaf node
if descendent is not None: # Is None for the first node
try:
descendents[graph].add(descendent)
except KeyError:
descendents[graph] = {descendent}
ancestors[descendent].add(graph)
else:
descendents[graph] = set()
# Flag that the leaf node has no children
ancestors[graph] = set()
else: # Intermediate node
if graph.name is not None: # Intermediate named node
if descendent is not None: # Is only None for the root node
try:
descendents[graph].add(descendent)
except KeyError:
descendents[graph] = {descendent}
ancestors[descendent].add(graph)
else:
descendents[graph] = set()
# The current node will be set as the descendent of the next
# nodes only if it is a named node
descendent = graph
# Init the nodes children to an empty set
ancestors[graph] = set()
for i in graph.owner.inputs:
temp_desc, temp_ances = _get_named_nodes_and_relations(
i, descendent, descendents, ancestors
)
descendents.update(temp_desc)
ancestors.update(temp_ances)
return descendents, ancestors
def build_named_node_tree(graphs):
"""Build the combined descence/ancestry tree of named nodes (i.e., nodes
whose name attribute is not None) in a list (or iterable) of theano graphs.
The relationship tree does not include unnamed intermediate nodes present
in the supplied graphs.
Parameters
----------
graphs - iterable of theano graphs
Returns:
--------
leaf_dict: Dict[str, node]
A dictionary of name:node pairs, of the named nodes that
have no named ancestors in the provided theano graphs.
descendents: Dict[node, Set[node]]
A dictionary of node:set([parents]) pairs. Each key is
a theano named node, and the corresponding value is the set of
theano named nodes that are descendents with no intervening named
nodes in the supplied ``graphs``.
ancestors: Dict[node, Set[node]]
A dictionary of node:set([ancestors]) pairs. Each key
is a theano named node, and the corresponding value is the set
of theano named nodes that are ancestors with no intervening named
nodes in the supplied ``graphs``.
"""
leaf_dict = {}
named_nodes_descendents = {}
named_nodes_ancestors = {}
for graph in graphs:
# Get the named nodes under the `param` node
nn, nnd, nna = get_named_nodes_and_relations(graph)
leaf_dict.update(nn)
# Update the discovered parental relationships
for k in nnd.keys():
if k not in named_nodes_descendents.keys():
named_nodes_descendents[k] = nnd[k]
else:
named_nodes_descendents[k].update(nnd[k])
# Update the discovered child relationships
for k in nna.keys():
if k not in named_nodes_ancestors.keys():
named_nodes_ancestors[k] = nna[k]
else:
named_nodes_ancestors[k].update(nna[k])
return leaf_dict, named_nodes_descendents, named_nodes_ancestors
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._theano_config is set in Model.__new__
self._config_context = None
if hasattr(self, "_theano_config"):
self._config_context = theano.config.change_flags(**self._theano_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._theano_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):
"""Theano 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):
"""Theano scalar of log-probability, excluding jacobian terms."""
if getattr(self, "total_size", None) is not None:
logp = tt.sum(self.logp_nojac_unscaledt) * self.scaling
else:
logp = tt.sum(self.logp_nojac_unscaledt)
if self.name is not None:
logp.name = "__logp_%s" % self.name
return logp
def withparent(meth):
"""Helper wrapper that passes calls to parent's instance"""
def wrapped(self, *args, **kwargs):
res = meth(self, *args, **kwargs)
if getattr(self, "parent", None) is not None:
getattr(self.parent, meth.__name__)(*args, **kwargs)
return res
# Unfortunately functools wrapper fails
# when decorating built-in methods so we
# need to fix that improper behaviour
wrapped.__name__ = meth.__name__
return wrapped
class treelist(list):
"""A list that passes mutable extending operations used in Model
to parent list instance.
Extending treelist you will also extend its parent
"""
def __init__(self, iterable=(), parent=None):
super().__init__(iterable)
assert isinstance(parent, list) or parent is None
self.parent = parent
if self.parent is not None:
self.parent.extend(self)
# typechecking here works bad
append = withparent(list.append)
__iadd__ = withparent(list.__iadd__)
extend = withparent(list.extend)
def tree_contains(self, item):
if isinstance(self.parent, treedict):
return list.__contains__(self, item) or self.parent.tree_contains(item)
elif isinstance(self.parent, list):
return list.__contains__(self, item) or self.parent.__contains__(item)
else:
return list.__contains__(self, item)
def __setitem__(self, key, value):
raise NotImplementedError(
"Method is removed as we are not able to determine appropriate logic for it"
)
# Added this because mypy didn't like having __imul__ without __mul__
# This is my best guess about what this should do. I might be happier
# to kill both of these if they are not used.
def __mul__(self, other) -> "treelist":
return cast("treelist", list.__mul__(self, other))
def __imul__(self, other) -> "treelist":
t0 = len(self)
list.__imul__(self, other)
if self.parent is not None:
self.parent.extend(self[t0:])
return self # python spec says should return the result.
class treedict(dict):
"""A dict that passes mutable extending operations used in Model
to parent dict instance.
Extending treedict you will also extend its parent
"""
def __init__(self, iterable=(), parent=None, **kwargs):
super().__init__(iterable, **kwargs)
assert isinstance(parent, dict) or parent is None
self.parent = parent
if self.parent is not None:
self.parent.update(self)
# typechecking here works bad
__setitem__ = withparent(dict.__setitem__)
update = withparent(dict.update)
def tree_contains(self, item):
# needed for `add_random_variable` method
if isinstance(self.parent, treedict):
return dict.__contains__(self, item) or self.parent.tree_contains(item)
elif isinstance(self.parent, dict):
return dict.__contains__(self, item) or self.parent.__contains__(item)
else:
return dict.__contains__(self, item)
class ValueGradFunction:
"""Create a theano function that computes a value and its gradient.
Parameters
----------
costs: list of theano variables
We compute the weighted sum of the specified theano values, and the gradient
of that sum. The weights can be specified with `ValueGradFunction.set_weights`.
grad_vars: list of named theano variables or None
The arguments with respect to which the gradient is computed.
extra_vars: list of named theano variables or None
Other arguments of the function that are assumed constant. They
are stored in shared variables and can be set using
`set_extra_values`.
dtype: str, default=theano.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 `theano.function`.
Attributes
----------
size: int
The number of elements in the parameter array.
profile: theano profiling object or None
The profiling object of the theano 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=None,
*,
dtype=None,
casting="no",
compute_grads=True,
**kwargs,
):
from pymc3.distributions import TensorType
if extra_vars is None:
extra_vars = []
names = [arg.name for arg in grad_vars + extra_vars]
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 = extra_vars
self._extra_var_names = {var.name for var in extra_vars}
if dtype is None:
dtype = theano.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 = theano.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._cost = cost
self._ordering = ArrayOrdering(grad_vars)
self.size = self._ordering.size
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 in extra_vars:
shared = theano.shared(var.tag.test_value, var.name + "_shared__")
# test TensorType compatibility
if hasattr(var.tag.test_value, "shape"):
testtype = TensorType(var.dtype, var.tag.test_value.shape)
if testtype != shared.type:
shared.type = testtype
self._extra_vars_shared[var.name] = shared
givens.append((var, shared))
self._vars_joined, self._cost_joined = self._build_joined(
self._cost, grad_vars, self._ordering.vmap
)
if compute_grads:
grad = tt.grad(self._cost_joined, self._vars_joined)
grad.name = "__grad"
outputs = [self._cost_joined, grad]
else:
outputs = self._cost_joined
inputs = [self._vars_joined]
self._theano_function = theano.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, array, 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 array.shape != (self.size,):
raise ValueError(
"Invalid shape for array. Must be {} but is {}.".format((self.size,), array.shape)
)
if grad_out is None:
out = np.empty_like(array)
else:
out = grad_out
output = self._theano_function(array)
if grad_out is None:
return output
else:
np.copyto(out, output[1])
return output[0]
@property
def profile(self):
"""Profiling information of the underlying theano function."""
return self._theano_function.profile
def dict_to_array(self, point):
"""Convert a dictionary with values for grad_vars to an array."""
array = np.empty(self.size, dtype=self.dtype)
for varmap in self._ordering.vmap:
array[varmap.slc] = point[varmap.var].ravel().astype(self.dtype)
return array
def array_to_dict(self, array):
"""Convert an array to a dictionary containing the grad_vars."""
if array.shape != (self.size,):
raise ValueError(f"Array should have shape ({self.size},) but has {array.shape}")
if array.dtype != self.dtype:
raise ValueError(
f"Array has invalid dtype. Should be {self._dtype} but is {self.dtype}"
)
point = {}
for varmap in self._ordering.vmap:
data = array[varmap.slc].reshape(varmap.shp)
point[varmap.var] = data.astype(varmap.dtyp)
return point
def array_to_full_dict(self, array):
"""Convert an array to a dictionary with grad_vars and extra_vars."""
point = self.array_to_dict(array)
for name, var in self._extra_vars_shared.items():
point[name] = var.get_value()
return point
def _build_joined(self, cost, args, vmap):
args_joined = tt.vector("__args_joined")
args_joined.tag.test_value = np.zeros(self.size, dtype=self.dtype)
joined_slices = {}
for vmap in vmap:
sliced = args_joined[vmap.slc].reshape(vmap.shp)
sliced.name = vmap.var
joined_slices[vmap.var] = sliced
replace = {var: joined_slices[var.name] for var in args}
return args_joined, theano.clone(cost, replace=replace)
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.
theano_config: dict
A dictionary of theano config values that should be set
temporarily in the model context. See the documentation
of theano for a complete list. Set config key
``compute_test_value`` to `raise` if it is None.
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.
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', tt.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)
theano_config = kwargs.get("theano_config", None)
if theano_config is None or "compute_test_value" not in theano_config:
theano_config = {"compute_test_value": "raise"}
instance._theano_config = theano_config
return instance
def __init__(self, name="", model=None, theano_config=None, coords=None, check_bounds=True):
self.name = name
self.coords = {}
self.RV_dims = {}
self.add_coords(coords)
self.check_bounds = check_bounds
if self.parent is not None:
self.named_vars = treedict(parent=self.parent.named_vars)
self.free_RVs = treelist(parent=self.parent.free_RVs)
self.observed_RVs = treelist(parent=self.parent.observed_RVs)
self.deterministics = treelist(parent=self.parent.deterministics)
self.potentials = treelist(parent=self.parent.potentials)
self.missing_values = treelist(parent=self.parent.missing_values)
else:
self.named_vars = treedict()
self.free_RVs = treelist()
self.observed_RVs = treelist()
self.deterministics = treelist()
self.potentials = treelist()
self.missing_values = 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 # type: ignore
@memoize(bound=True)
def bijection(self):
vars = inputvars(self.vars)
bij = DictToArrayBijection(ArrayOrdering(vars), self.test_point)
return bij
@property
def dict_to_array(self):
return self.bijection.map
@property
def ndim(self):
return sum(var.dsize for var in self.free_RVs)
@property
def logp_array(self):
return self.bijection.mapf(self.fastlogp)
@property
def dlogp_array(self):
vars = inputvars(self.cont_vars)
return self.bijection.mapf(self.fastdlogp(vars))
def logp_dlogp_function(self, grad_vars=None, tempered=False, **kwargs):
"""Compile a theano 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 = list(typefilter(self.free_RVs, continuous_types))
else:
for var in grad_vars:
if var.dtype not in continuous_types:
raise ValueError("Can only compute the gradient of continuous types: %s" % var)
if tempered:
with self:
free_RVs_logp = tt.sum(
[tt.sum(var.logpt) for var in self.free_RVs + self.potentials]
)
observed_RVs_logp = tt.sum([tt.sum(var.logpt) for var in self.observed_RVs])
costs = [free_RVs_logp, observed_RVs_logp]
else:
costs = [self.logpt]