forked from allenai/reclip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lattice.py
70 lines (52 loc) · 1.81 KB
/
lattice.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
"""Implement lattice interface."""
from overrides import overrides
import numpy as np
from abc import ABCMeta, abstractmethod
class Lattice(metaclass=ABCMeta):
"""Abstract base class representing a complemented lattice."""
@classmethod
@abstractmethod
def join(cls, probs1: np.ndarray, probs2: np.ndarray) -> np.ndarray:
return NotImplemented
@classmethod
@abstractmethod
def meet(cls, probs1: np.ndarray, probs2: np.ndarray) -> np.ndarray:
return NotImplemented
@classmethod
@abstractmethod
def join_reduce(cls, probs: np.ndarray) -> np.ndarray:
return NotImplemented
@classmethod
@abstractmethod
def meet_reduce(cls, probs: np.ndarray) -> np.ndarray:
return NotImplemented
class Product(Lattice):
"""Lattice where meet=prod and sum is defined accordingly.
Equivalent to assuming independence, more or less.
"""
eps = 1e-9
@classmethod
@overrides
def join(cls, probs1: np.ndarray, probs2: np.ndarray) -> np.ndarray:
return probs1 + probs2 - cls.meet(probs1, probs2)
@classmethod
@overrides
def meet(cls, probs1: np.ndarray, probs2: np.ndarray) -> np.ndarray:
return probs1 * probs2
@classmethod
@overrides
def join_reduce(cls, probs: np.ndarray) -> np.ndarray:
"""Assumes disjoint events."""
# return cls.comp(cls.meet_reduce(cls.comp(probs)))
return np.sum(probs, axis=-1)
@classmethod
@overrides
def meet_reduce(cls, probs: np.ndarray) -> np.ndarray:
return np.prod(probs, axis=-1)
@classmethod
def comp(cls, probs):
return 1 - probs
@classmethod
def normalize(cls, probs):
"""Normalize a distribution by dividing by the total mass."""
return probs / np.sum(probs + cls.eps, axis=-1)