-
Notifications
You must be signed in to change notification settings - Fork 105
/
base.py
631 lines (487 loc) · 18.8 KB
/
base.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
"""Base Univariate class."""
import pickle
from abc import ABC
from enum import Enum
import numpy as np
from copulas import NotFittedError, get_instance, get_qualified_name, store_args
from copulas.univariate.selection import select_univariate
class ParametricType(Enum):
"""Parametric Enum."""
NON_PARAMETRIC = 0
PARAMETRIC = 1
class BoundedType(Enum):
"""Bounded Enum."""
UNBOUNDED = 0
SEMI_BOUNDED = 1
BOUNDED = 2
class Univariate(object):
"""Univariate Distribution.
Args:
candidates (list[str or type or Univariate]):
List of candidates to select the best univariate from.
It can be a list of strings representing Univariate FQNs,
or a list of Univariate subclasses or a list of instances.
parametric (ParametricType):
If not ``None``, only select subclasses of this type.
Ignored if ``candidates`` is passed.
bounded (BoundedType):
If not ``None``, only select subclasses of this type.
Ignored if ``candidates`` is passed.
random_seed (int):
Random seed to use.
selection_sample_size (int):
Size of the subsample to use for candidate selection.
If ``None``, all the data is used.
"""
PARAMETRIC = ParametricType.NON_PARAMETRIC
BOUNDED = BoundedType.UNBOUNDED
fitted = False
_constant_value = None
_instance = None
@classmethod
def _select_candidates(cls, parametric=None, bounded=None):
"""Select which subclasses fulfill the specified constriants.
Args:
parametric (ParametricType):
If not ``None``, only select subclasses of this type.
bounded (BoundedType):
If not ``None``, only select subclasses of this type.
Returns:
list:
Selected subclasses.
"""
candidates = []
for subclass in cls.__subclasses__():
candidates.extend(subclass._select_candidates(parametric, bounded))
if ABC in subclass.__bases__:
continue
if parametric is not None and subclass.PARAMETRIC != parametric:
continue
if bounded is not None and subclass.BOUNDED != bounded:
continue
candidates.append(subclass)
return candidates
@store_args
def __init__(self, candidates=None, parametric=None, bounded=None, random_seed=None,
selection_sample_size=None):
self.candidates = candidates or self._select_candidates(parametric, bounded)
self.random_seed = random_seed
self.selection_sample_size = selection_sample_size
@classmethod
def __repr__(cls):
"""Return class name."""
return cls.__name__
def check_fit(self):
"""Check whether this model has already been fit to a random variable.
Raise a ``NotFittedError`` if it has not.
Raises:
NotFittedError:
if the model is not fitted.
"""
if not self.fitted:
raise NotFittedError('This model is not fitted.')
def _constant_sample(self, num_samples):
"""Sample values for a constant distribution.
Args:
num_samples (int):
Number of rows to sample
Returns:
numpy.ndarray:
Sampled values. Array of shape (num_samples,).
"""
return np.full(num_samples, self._constant_value)
def _constant_cumulative_distribution(self, X):
"""Cumulative distribution for the degenerate case of constant distribution.
Note that the output of this method will be an array whose unique values are 0 and 1.
More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution
Arguments:
X (numpy.ndarray):
Values for which the cumulative distribution will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Cumulative distribution values for points in X.
"""
result = np.ones(X.shape)
result[np.nonzero(X < self._constant_value)] = 0
return result
def _constant_probability_density(self, X):
"""Probability density for the degenerate case of constant distribution.
Note that the output of this method will be an array whose unique values are 0 and 1.
More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution
Arguments:
X (numpy.ndarray):
Values for which the probability density will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Probability density values for points in X.
"""
result = np.zeros(X.shape)
result[np.nonzero(X == self._constant_value)] = 1
return result
def _constant_percent_point(self, X):
"""Percent point for the degenerate case of constant distribution.
Note that the output of this method will be an array whose unique values are `np.nan`
and self._constant_value.
More information can be found here: https://en.wikipedia.org/wiki/Degenerate_distribution
Arguments:
U (numpy.ndarray):
Values for which the cumulative distribution will be computed.
It must have shape (n, 1) and values must be in [0,1].
Returns:
numpy.ndarray:
Inverse cumulative distribution values for points in U.
"""
return np.full(X.shape, self._constant_value)
def _replace_constant_methods(self):
"""Replace conventional distribution methods by its constant counterparts."""
self.cumulative_distribution = self._constant_cumulative_distribution
self.percent_point = self._constant_percent_point
self.probability_density = self._constant_probability_density
self.sample = self._constant_sample
def _set_constant_value(self, constant_value):
"""Set the distribution up to behave as a degenerate distribution.
The constant value is stored as ``self._constant_value`` and all
the methods are replaced by their degenerate counterparts.
Args:
constant_value (float):
Value to set as the constant one.
"""
self._constant_value = constant_value
self._replace_constant_methods()
def _check_constant_value(self, X):
"""Check if a Series or array contains only one unique value.
If it contains only one value, set the instance up to behave accordingly.
Args:
X (numpy.ndarray):
Data to analyze.
Returns:
float:
Whether the input data had only one value or not.
"""
uniques = np.unique(X)
if len(uniques) == 1:
self._set_constant_value(uniques[0])
return True
return False
def fit(self, X):
"""Fit the model to a random variable.
Arguments:
X (numpy.ndarray):
Values of the random variable. It must have shape (n, 1).
"""
if self.selection_sample_size and self.selection_sample_size < len(X):
selection_sample = np.random.choice(X, size=self.selection_sample_size)
else:
selection_sample = X
self._instance = select_univariate(selection_sample, self.candidates)
self._instance.fit(X)
self.fitted = True
def probability_density(self, X):
"""Compute the probability density for each point in X.
Arguments:
X (numpy.ndarray):
Values for which the probability density will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Probability density values for points in X.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
return self._instance.probability_density(X)
def log_probability_density(self, X):
"""Compute the log of the probability density for each point in X.
It should be overridden with numerically stable variants whenever possible.
Arguments:
X (numpy.ndarray):
Values for which the log probability density will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Log probability density values for points in X.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
if self._instance:
return self._instance.log_probability_density(X)
return np.log(self.probability_density(X))
def pdf(self, X):
"""Compute the probability density for each point in X.
Arguments:
X (numpy.ndarray):
Values for which the probability density will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Probability density values for points in X.
"""
return self.probability_density(X)
def cumulative_distribution(self, X):
"""Compute the cumulative distribution value for each point in X.
Arguments:
X (numpy.ndarray):
Values for which the cumulative distribution will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Cumulative distribution values for points in X.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
return self._instance.cumulative_distribution(X)
def cdf(self, X):
"""Compute the cumulative distribution value for each point in X.
Arguments:
X (numpy.ndarray):
Values for which the cumulative distribution will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Cumulative distribution values for points in X.
"""
return self.cumulative_distribution(X)
def percent_point(self, U):
"""Compute the inverse cumulative distribution value for each point in U.
Arguments:
U (numpy.ndarray):
Values for which the cumulative distribution will be computed.
It must have shape (n, 1) and values must be in [0,1].
Returns:
numpy.ndarray:
Inverse cumulative distribution values for points in U.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
return self._instance.percent_point(U)
def ppf(self, U):
"""Compute the inverse cumulative distribution value for each point in U.
Arguments:
U (numpy.ndarray):
Values for which the cumulative distribution will be computed.
It must have shape (n, 1) and values must be in [0,1].
Returns:
numpy.ndarray:
Inverse cumulative distribution values for points in U.
"""
return self.percent_point(U)
def sample(self, n_samples=1):
"""Sample values from this model.
Argument:
n_samples (int):
Number of values to sample
Returns:
numpy.ndarray:
Array of shape (n_samples, 1) with values randomly
sampled from this model distribution.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
return self._instance.sample(n_samples)
def _get_params(self):
"""Return attributes from self.model to serialize.
Returns:
dict:
Parameters of the underlying distribution.
"""
return self._instance._get_params()
def _set_params(self, params):
"""Set the parameters of this univariate.
Must be implemented in all the subclasses.
Args:
dict:
Parameters to recreate this instance.
"""
raise NotImplementedError()
def to_dict(self):
"""Return the parameters of this model in a dict.
Returns:
dict:
Dictionary containing the distribution type and all
the parameters that define the distribution.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
params = self._get_params()
if self.__class__ is Univariate:
params['type'] = get_qualified_name(self._instance)
else:
params['type'] = get_qualified_name(self)
return params
@classmethod
def from_dict(cls, params):
"""Build a distribution from its params dict.
Args:
params (dict):
Dictionary containing the FQN of the distribution and the
necessary parameters to rebuild it.
The input format is exactly the same that is outputted by
the distribution class ``to_dict`` method.
Returns:
Univariate:
Distribution instance.
"""
params = params.copy()
distribution = get_instance(params.pop('type'))
distribution._set_params(params)
distribution.fitted = True
return distribution
def save(self, path):
"""Serialize this univariate instance using pickle.
Args:
path (str):
Path to where this distribution will be serialized.
"""
with open(path, 'wb') as pickle_file:
pickle.dump(self, pickle_file)
@classmethod
def load(cls, path):
"""Load a Univariate instance from a pickle file.
Args:
path (str):
Path to the pickle file where the distribution has been serialized.
Returns:
Univariate:
Loaded instance.
"""
with open(path, 'rb') as pickle_file:
return pickle.load(pickle_file)
class ScipyModel(Univariate, ABC):
"""Wrapper for scipy models.
This class makes the probability_density, cumulative_distribution,
percent_point and sample point at the underlying pdf, cdf, ppd and rvs
methods respectively.
fit, _get_params and _set_params must be implemented by the subclasses.
"""
MODEL_CLASS = None
_params = None
def __init__(self):
# Overwrite Univariate __init__ to skip candiate initialization
pass
def probability_density(self, X):
"""Compute the probability density for each point in X.
Arguments:
X (numpy.ndarray):
Values for which the probability density will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Probability density values for points in X.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
return self.MODEL_CLASS.pdf(X, **self._params)
def log_probability_density(self, X):
"""Compute the log of the probability density for each point in X.
Arguments:
X (numpy.ndarray):
Values for which the log probability density will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Log probability density values for points in X.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
if hasattr(self.MODEL_CLASS, 'logpdf'):
return self.MODEL_CLASS.logpdf(X, **self._params)
return np.log(self.probability_density(X))
def cumulative_distribution(self, X):
"""Compute the cumulative distribution value for each point in X.
Arguments:
X (numpy.ndarray):
Values for which the cumulative distribution will be computed.
It must have shape (n, 1).
Returns:
numpy.ndarray:
Cumulative distribution values for points in X.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
return self.MODEL_CLASS.cdf(X, **self._params)
def percent_point(self, U):
"""Compute the inverse cumulative distribution value for each point in U.
Arguments:
U (numpy.ndarray):
Values for which the cumulative distribution will be computed.
It must have shape (n, 1) and values must be in [0,1].
Returns:
numpy.ndarray:
Inverse cumulative distribution values for points in U.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
return self.MODEL_CLASS.ppf(U, **self._params)
def sample(self, n_samples=1):
"""Sample values from this model.
Argument:
n_samples (int):
Number of values to sample
Returns:
numpy.ndarray:
Array of shape (n_samples, 1) with values randomly
sampled from this model distribution.
Raises:
NotFittedError:
if the model is not fitted.
"""
self.check_fit()
return self.MODEL_CLASS.rvs(size=n_samples, **self._params)
def _fit(self, X):
"""Fit the model to a non-constant random variable.
Must be implemented in all the subclasses.
Arguments:
X (numpy.ndarray):
Values of the random variable. It must have shape (n, 1).
"""
raise NotImplementedError()
def fit(self, X):
"""Fit the model to a random variable.
Arguments:
X (numpy.ndarray):
Values of the random variable. It must have shape (n, 1).
"""
if self._check_constant_value(X):
self._fit_constant(X)
else:
self._fit(X)
self.fitted = True
def _get_params(self):
"""Return attributes from self._model to serialize.
Must be implemented in all the subclasses.
Returns:
dict:
Parameters to recreate self._model in its current fit status.
"""
return self._params.copy()
def _set_params(self, params):
"""Set the parameters of this univariate.
Args:
params (dict):
Parameters to recreate this instance.
"""
self._params = params.copy()
if self._is_constant():
constant = self._extract_constant()
self._set_constant_value(constant)