-
Notifications
You must be signed in to change notification settings - Fork 818
/
metric.py
63 lines (51 loc) · 1.66 KB
/
metric.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from abc import abstractmethod
from collections import Hashable
from functools import wraps
from aif360.datasets import Dataset
from aif360.decorating_metaclass import ApplyDecorator
def _make_key(args, kwargs, unhashable, kwd_mark=(object(),)):
"""Simplified version of functools."""
key = args
if kwargs:
key += kwd_mark
for item in kwargs.items():
if not isinstance(item[1], Hashable):
return unhashable
key += item
return key
def memoize(func):
"""Based off functools.lru_cache (not available in Python 2).
A little inefficient but we're just storing floats.
"""
sentinal = object()
unhashable = object()
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = _make_key(args, kwargs, unhashable)
if key is unhashable:
return func(*args, **kwargs)
result = cache.get(key, sentinal)
if result is not sentinal:
return result
result = func(*args, **kwargs)
cache[key] = result
return result
return wrapper
BaseClass = ApplyDecorator(memoize)
class Metric(BaseClass):
"""Base class for metrics."""
@abstractmethod
def __init__(self, dataset):
"""Initialize a `Metrics` object.
Args:
dataset (Dataset): Dataset on which to evaluate metrics.
"""
if isinstance(dataset, Dataset):
self.dataset = dataset
else:
raise TypeError("dataset must be of Dataset class")