-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulations.py
1642 lines (1354 loc) · 49.2 KB
/
simulations.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
import numpy as np
# Dictionary of simulations from Marron and Wand 1992
# keys: names of each simulation corresponding to the class MarronWandSims
# values: probabilities associated with the mixture of Gaussians
MARRON_WAND_SIMS = {
"skewed_unimodal": [1 / 5, 1 / 5, 3 / 5],
"strongly_skewed": [1 / 8] * 8,
"kurtotic_unimodal": [2 / 3, 1 / 3],
"outlier": [1 / 10, 9 / 10],
"bimodal": [1 / 2] * 2,
"separated_bimodal": [1 / 2] * 2,
"skewed_bimodal": [3 / 4, 1 / 4],
"trimodal": [9 / 20, 9 / 20, 1 / 10],
"claw": [1 / 2, *[1 / 10] * 5],
"double_claw": [49 / 100, 49 / 100, *[1 / 350] * 7],
"asymmetric_claw": [1 / 2, *[2 ** (1 - i) / 31 for i in range(-2, 3)]],
"asymmetric_double_claw": [*[46 / 100] * 2, *[1 / 300] * 3, *[7 / 300] * 3],
"smooth_comb": [2 ** (5 - i) / 63 for i in range(6)],
"discrete_comb": [*[2 / 7] * 3, *[1 / 21] * 3],
"independent": [],
}
def _moving_avg_cov(n_dim, rho):
# Create a meshgrid of indices
i, j = np.meshgrid(np.arange(1, n_dim + 1), np.arange(1, n_dim + 1), indexing="ij")
# Calculate the covariance matrix using the corrected formula
cov_matrix = rho ** np.abs(i - j)
# Apply the banding condition
cov_matrix[abs(i - j) > 1] = 0
return cov_matrix
def _autoregressive_cov(n_dim, rho):
# Create a meshgrid of indices
i, j = np.meshgrid(np.arange(1, n_dim + 1), np.arange(1, n_dim + 1), indexing="ij")
# Calculate the covariance matrix using the corrected formula
cov_matrix = rho ** np.abs(i - j)
return cov_matrix
def make_marron_wand_classification(
n_samples,
n_dim=4096,
n_informative=256,
simulation: str = "independent",
rho: int = 0,
band_type: str = "ma",
return_params: bool = False,
scaling_factor: float = 1.0,
seed=None,
):
"""Generate Marron-Wand binary classification dataset.
The simulation is similar to that of
:func:`sktree.datasets.make_trunk_classification`
where the first class is generated from a multivariate-Gaussians with mean vector of
0's. The second class is generated from a mixture of Gaussians with mean vectors
specified by the Marron-Wand simulations, but as the dimensionality increases,
the second class distribution approaches the first class distribution by a factor
of :math:`1 / sqrt(d)`.
Full details for the Marron-Wand simulations can be found in
:footcite:`marron1992exact`.
Instead of the identity covariance matrix, one can implement a banded covariance
matrix that follows :footcite:`Bickel_2008`.
Parameters
----------
n_samples : int
Number of sample to generate. Must be an even number, else the total number of
samples generated will be ``n_samples - 1``.
n_dim : int, optional
The dimensionality of the dataset and the number of
unique labels, by default 4096.
n_informative : int, optional
The informative dimensions. All others for ``n_dim - n_informative``
are Gaussian noise. Default is 256.
simulation : str, optional
Which simulation to run. Must be one of the
following Marron-Wand simulations: 'independent', 'skewed_unimodal',
'strongly_skewed', 'kurtotic_unimodal', 'outlier', 'bimodal',
'separated_bimodal', 'skewed_bimodal', 'trimodal', 'claw', 'double_claw',
'asymmetric_claw', 'asymmetric_double_claw', 'smooth_comb', 'discrete_comb'.
When calling the Marron-Wand simulations, only the covariance parameters are
considered (`rho` and `band_type`). Means are taken from
:footcite:`marron1992exact`. By default 'independent'.
rho : float, optional
The covariance value of the bands. By default 0 indicating, an identity matrix
is used.
band_type : str
The band type to use. For details, see Example 1 and 2 in
:footcite:`Bickel_2008`. Either 'ma', or 'ar'.
return_params : bool, optional
Whether or not to return the distribution parameters of the classes normal
distributions.
scaling_factor : float, optional
The scaling factor for the covariance matrix. By default 1.
seed : int, optional
Random seed, by default None.
Returns
-------
X : np.ndarray of shape (n_samples, n_dim), dtype=np.float64
Trunk dataset as a dense array.
y : np.ndarray of shape (n_samples,), dtype=np.intp
Labels of the dataset.
G : np.ndarray of shape (n_samples, n_dim), dtype=np.float64
The mixture of Gaussians for the Marron-Wand simulations.
Returned if ``return_params`` is True.
w : np.ndarray of shape (n_dim,), dtype=np.float64
The weight vector for the Marron-Wand simulations.
Returned if ``return_params`` is True.
Notes
-----
**Marron-Wand Simulations**: The Marron-Wand simulations generate two classes of
data with the setup specified in the paper.
Covariance: The covariance matrix among different dimensions is controlled by the
``rho`` parameter and the ``band_type`` parameter. The ``band_type`` parameter
controls the type of band to use, while the ``rho`` parameter controls the specific
scaling factor for the covariance matrix while going from one dimension to the next.
For each dimension in the first distribution, there is a mean of :math:`1 / d`,
where ``d`` is the dimensionality. The covariance is the identity matrix.
The second distribution has a mean vector that is the negative of the first.
As ``d`` increases, the two distributions become closer and closer.
Full details for the trunk simulation can be found in :footcite:`trunk1982`.
References
----------
.. footbibliography::
"""
if simulation not in MARRON_WAND_SIMS.keys():
raise ValueError(f"Simulation must be: {MARRON_WAND_SIMS.keys()}")
rng = np.random.default_rng(seed=seed)
# speed up computations for large multivariate normal matrix with SVD approximation
if n_informative > 1000:
mvg_sampling_method = "cholesky"
else:
mvg_sampling_method = "svd"
if simulation == "independent":
X = np.vstack(
(
rng.multivariate_normal(
np.zeros(n_dim),
np.identity(n_dim),
n_samples // 2,
method=mvg_sampling_method,
),
rng.multivariate_normal(
np.zeros(n_dim),
np.identity(n_dim),
n_samples // 2,
method=mvg_sampling_method,
),
)
)
else:
if n_dim < n_informative:
raise ValueError(
f"Number of informative dimensions {n_informative} must be less than"
f" number of dimensions, {n_dim}"
)
if rho != 0:
if band_type == "ma":
cov = _moving_avg_cov(n_informative, rho)
elif band_type == "ar":
cov = _autoregressive_cov(n_informative, rho)
else:
raise ValueError(f'Band type {band_type} must be one of "ma", or "ar".')
else:
cov = np.identity(n_informative)
# allow arbitrary uniform scaling of the covariance matrix
cov = scaling_factor * cov
mixture_idx = rng.choice(
len(MARRON_WAND_SIMS[simulation]), # type: ignore
size=n_samples // 2,
replace=True,
p=MARRON_WAND_SIMS[simulation],
)
# the parameters used for each Gaussian in the mixture for each Marron Wand
# simulation
norm_params = MarronWandSims(n_dim=n_informative, cov=cov)(simulation)
G = np.fromiter(
(
rng_children.multivariate_normal(
*(norm_params[i]), size=1, method=mvg_sampling_method
)
for i, rng_children in zip(mixture_idx, rng.spawn(n_samples // 2))
),
dtype=np.dtype((float, n_informative)),
)
# as the dimensionality of the simulations increasing, we are adding more and
# more noise to the data using the w parameter
w_vec = np.array([1.0 / np.sqrt(i) for i in range(1, n_informative + 1)])
# create new generator instance to ensure reproducibility with multiple runs
# with the same seed
rng_F = np.random.default_rng(seed=seed).spawn(2)
X = np.vstack(
(
rng_F[0].multivariate_normal(
np.zeros(n_informative),
cov,
n_samples // 2,
method=mvg_sampling_method,
),
(1 - w_vec)
* rng_F[1].multivariate_normal(
np.zeros(n_informative),
cov,
n_samples // 2,
method=mvg_sampling_method,
)
+ w_vec * G.reshape(n_samples // 2, n_informative),
)
)
if n_dim > n_informative:
# create new generator instance to ensure reproducibility with multiple
# runs with the same seed
rng_noise = np.random.default_rng(seed=seed)
X = np.hstack(
(
X,
np.hstack(
[
rng_children.normal(loc=0, scale=1, size=(X.shape[0], 1))
for rng_children in rng_noise.spawn(n_dim - n_informative)
]
),
)
)
y = np.concatenate((np.zeros(n_samples // 2), np.ones(n_samples // 2)))
if return_params and not simulation == "independent":
return [X, y, *list(zip(*norm_params)), G, w_vec]
return X, y
class MarronWandSims:
def __init__(self, n_dim=1, cov=1):
self.n_dim = n_dim
self.cov = cov
def __call__(self, simulation):
sims = self._my_method_generator()
if simulation in sims.keys():
return sims[simulation]()
else:
raise ValueError(f"simulation is not one of these: {sims.keys()}")
def _my_method_generator(self):
return {
method: getattr(self, method)
for method in dir(self)
if not method.startswith("__")
}
def skewed_unimodal(self):
return [
[np.zeros(self.n_dim), self.cov],
[np.full(self.n_dim, 1 / 2), self.cov * (2 / 3) ** 2],
[np.full(self.n_dim, 13 / 12), self.cov * (5 / 9) ** 2],
]
def strongly_skewed(self):
return [
[
np.full(self.n_dim, 3 * ((2 / 3) ** l_mix - 1)),
self.cov * (2 / 3) ** (2 * l_mix),
]
for l_mix in range(8)
]
def kurtotic_unimodal(self):
return [
[np.zeros(self.n_dim), self.cov],
[np.zeros(self.n_dim), self.cov * (1 / 10) ** 2],
]
def outlier(self):
return [
[np.zeros(self.n_dim), self.cov],
[np.zeros(self.n_dim), self.cov * (1 / 10) ** 2],
]
def bimodal(self):
return [
[-np.ones(self.n_dim), self.cov * (2 / 3) ** 2],
[np.ones(self.n_dim), self.cov * (2 / 3) ** 2],
]
def separated_bimodal(self):
return [
[-np.full(self.n_dim, 3 / 2), self.cov * (1 / 2) ** 2],
[np.full(self.n_dim, 3 / 2), self.cov * (1 / 2) ** 2],
]
def skewed_bimodal(self):
return [
[np.zeros(self.n_dim), self.cov],
[np.full(self.n_dim, 3 / 2), self.cov * (1 / 3) ** 2],
]
def trimodal(self):
return [
[np.full(self.n_dim, -6 / 5), self.cov * (3 / 5) ** 2],
[np.full(self.n_dim, 6 / 5), self.cov * (3 / 5) ** 2],
[np.zeros(self.n_dim), self.cov * (1 / 4) ** 2],
]
def claw(self):
return [
[np.zeros(self.n_dim), self.cov],
*[
[np.full(self.n_dim, (l_mix / 2) - 1), self.cov * (1 / 10) ** 2]
for l_mix in range(5)
],
]
def double_claw(self):
return [
[-np.ones(self.n_dim), self.cov * (2 / 3) ** 2],
[np.ones(self.n_dim), self.cov * (2 / 3) ** 2],
*[
[np.full(self.n_dim, (l_mix - 3) / 2), self.cov * (1 / 100) ** 2]
for l_mix in range(7)
],
]
def asymmetric_claw(self):
return [
[np.zeros(self.n_dim), self.cov],
*[
[
np.full(self.n_dim, l_mix + 1 / 2),
self.cov * (1 / ((2**l_mix) * 10)) ** 2,
]
for l_mix in range(-2, 3)
],
]
def asymmetric_double_claw(self):
return [
*[
[np.full(self.n_dim, 2 * l_mix - 1), self.cov * (2 / 3) ** 2]
for l_mix in range(2)
],
*[
[-np.full(self.n_dim, l_mix / 2), self.cov * (1 / 100) ** 2]
for l_mix in range(1, 4)
],
*[
[np.full(self.n_dim, l_mix / 2), self.cov * (7 / 100) ** 2]
for l_mix in range(1, 4)
],
]
def smooth_comb(self):
return [
[
np.full(self.n_dim, (65 - 96 * ((1 / 2) ** l_mix)) / 21),
self.cov * (32 / 63) ** 2 / (2 ** (2 * l_mix)),
]
for l_mix in range(6)
]
def discrete_comb(self):
return [
*[
[np.full(self.n_dim, (12 * l_mix - 15) / 7), self.cov * (2 / 7) ** 2]
for l_mix in range(3)
],
*[
[np.full(self.n_dim, (2 * l_mix) / 7), self.cov * (1 / 21) ** 2]
for l_mix in range(8, 11)
],
]
class _CheckInputs:
"""Check if additional arguments are correct"""
def __init__(self, n, p):
self.n = n
self.p = p
def __call__(self, *args):
if type(self.n) is not int or type(self.p) is not int:
raise ValueError(f"n and p must be ints; n is {type(self.n)} and p is {type(self.p)}")
if self.n < 5 or self.p < 1:
raise ValueError(
f"n is {self.n} and p is {self.p}; "
"n must be greater than or equal to 5 and p "
"must be greater than or equal to than 1"
)
for arg in args:
if arg[1] is float and type(arg[0]) is int:
continue
if type(arg[0]) is not arg[1]:
raise ValueError(f"{arg[0]} is {type(arg[0])}; expected {arg[1]}")
def _gen_coeffs(p):
"""Calculates coefficients polynomials"""
return np.array([1 / (i + 1) for i in range(p)]).reshape(-1, 1)
def _random_uniform(n, p, low=-1, high=1):
"""Generate random uniform data"""
return np.random.uniform(low, high, size=(n, p))
def _calc_eps(n):
"""Calculate noise"""
return np.random.normal(0, 1, size=(n, 1))
def linear(n, p, noise=False, low=-1, high=1):
r"""
Simulates univariate or multivariate linear data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
low : float, (default: -1)
The lower limit of the uniform distribution simulated from.
high : float, (default: -1)
The upper limit of the uniform distribution simulated from.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, 1)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
Linear :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}`:
.. math::
X &\sim \mathcal{U}(-1, 1)^p \\
Y &= w^T X + \kappa \epsilon
Examples
--------
>>> from hyppo.sims import linear
>>> x, y = linear(100, 2)
>>> print(x.shape, y.shape)
(100, 2) (100, 1)
"""
extra_args = [(noise, bool), (low, float), (high, float)]
check_in = _CheckInputs(n, p)
check_in(*extra_args)
x = _random_uniform(n, p, low, high)
coeffs = _gen_coeffs(p)
eps = _calc_eps(n)
y = x @ coeffs + 1 * noise * eps
return x, y
def exponential(n, p, noise=False, low=0, high=3):
r"""
Simulates univariate or multivariate exponential data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
low : float, (default: 0)
The lower limit of the uniform distribution simulated from.
high : float, (default: 3)
The upper limit of the uniform distribution simulated from.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, 1)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
Exponential :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}`:
.. math::
X &\sim \mathcal{U}(0, 3)^p \\
Y &= \exp (w^T X) + 10 \kappa \epsilon
Examples
--------
>>> from hyppo.sims import exponential
>>> x, y = exponential(100, 2)
>>> print(x.shape, y.shape)
(100, 2) (100, 1)
"""
extra_args = [(noise, bool), (low, float), (high, float)]
check_in = _CheckInputs(n, p)
check_in(*extra_args)
x = _random_uniform(n, p, low, high)
coeffs = _gen_coeffs(p)
eps = _calc_eps(n)
y = np.exp(x @ coeffs) + 10 * noise * eps
return x, y
def cubic(n, p, noise=False, low=-1, high=1, cubs=[-12, 48, 128], scale=1 / 3):
r"""
Simulates univariate or multivariate cubic data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
low : float, (default: -1)
The lower limit of the uniform distribution simulated from.
high : float, (default: -1)
The upper limit of the uniform distribution simulated from.
cubs : list of ints (default: [-12, 48, 128])
Coefficients of the cubic function where each value corresponds to the
order of the cubic polynomial.
scale : float (default: 1/3)
Scaling center of the cubic.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, 1)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
Cubic :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}`:
.. math::
X &\sim \mathcal{U}(-1, 1)^p \\
Y &= 128 \left( w^T X - \frac{1}{3} \right)^3
+ 48 \left( w^T X - \frac{1}{3} \right)^2
- 12 \left( w^T X - \frac{1}{3} \right)
+ 80 \kappa \epsilon
Examples
--------
>>> from hyppo.sims import cubic
>>> x, y = cubic(100, 2)
>>> print(x.shape, y.shape)
(100, 2) (100, 1)
"""
extra_args = [
(noise, bool),
(low, float),
(high, float),
(cubs, list),
(scale, float),
]
check_in = _CheckInputs(n, p)
check_in(*extra_args)
x = _random_uniform(n, p, low, high)
coeffs = _gen_coeffs(p)
eps = _calc_eps(n)
x_coeffs = x @ coeffs - scale
y = (
cubs[2] * x_coeffs**3
+ cubs[1] * x_coeffs**2
+ cubs[0] * x_coeffs**3
+ 80 * noise * eps
)
return x, y
def joint_normal(n, p, noise=False):
r"""
Simulates univariate or multivariate joint-normal data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, p)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
Joint Normal :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}^p`: Let
:math:`\rho = \frac{1}{2} p`, :math:`I_p` be the identity matrix of size
:math:`p \times p`, :math:`J_p` be the matrix of ones of size
:math:`p \times p` and
:math:`\Sigma = \begin{bmatrix} I_p & \rho J_p \\ \rho J_p & (1 + 0.5\kappa) I_p \end{bmatrix}`. Then,
.. math::
(X, Y) \sim \mathcal{N}(0, \Sigma)
Examples
--------
>>> from hyppo.sims import joint_normal
>>> x, y = joint_normal(100, 2)
>>> print(x.shape, y.shape)
(100, 2) (100, 1)
"""
if p > 10:
raise ValueError("Covariance matrix for p>10 is not positive" "semi-definite")
extra_args = [(noise, bool)]
check_in = _CheckInputs(n, p)
check_in(*extra_args)
coeffs = _gen_coeffs(p)
rho = 1 / (2 * coeffs)
cov1 = np.concatenate((np.identity(p), rho * np.ones((p, p))), axis=1)
cov2 = np.concatenate((rho * np.ones((p, p)), np.identity(p)), axis=1)
covT = np.concatenate((cov1.T, cov2.T), axis=1)
eps = _calc_eps(n)
x = np.random.multivariate_normal(np.zeros(2 * p), covT, n)
y = x[:, 0].reshape(-1, 1) + 0.5 * noise * eps
x = x[:, :p]
return x, y
def step(n, p, noise=False, low=-1, high=1):
r"""
Simulates univariate or multivariate step data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
low : float, (default: -1)
The lower limit of the uniform distribution simulated from.
high : float, (default: -1)
The upper limit of the uniform distribution simulated from.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, 1)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
Step :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}`:
.. math::
X &\sim \mathcal{U}(-1, 1)^p \\
Y &= \mathbb{1}_{w^T X > 0} + \epsilon
where :math:`\mathbb{1}` is the indicator function.
Examples
--------
>>> from hyppo.sims import step
>>> x, y = step(100, 2)
>>> print(x.shape, y.shape)
(100, 2) (100, 1)
"""
extra_args = [(noise, bool), (low, float), (high, float)]
check_in = _CheckInputs(n, p)
check_in(*extra_args)
if p > 1:
noise = True
x = _random_uniform(n, p, low, high)
coeffs = _gen_coeffs(p)
eps = _calc_eps(n)
x_coeff = ((x @ coeffs) > 0) * 1
y = x_coeff + noise * eps
return x, y
def quadratic(n, p, noise=False, low=-1, high=1):
r"""
Simulates univariate or multivariate quadratic data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
low : float, (default: -1)
The lower limit of the uniform distribution simulated from.
high : float, (default: -1)
The upper limit of the uniform distribution simulated from.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, 1)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
Quadratic :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}`:
.. math::
X &\sim \mathcal{U}(-1, 1)^p \\
Y &= (w^T X)^2 + 0.5 \kappa \epsilon
Examples
--------
>>> from hyppo.sims import quadratic
>>> x, y = quadratic(100, 2)
>>> print(x.shape, y.shape)
(100, 2) (100, 1)
"""
extra_args = [(noise, bool), (low, float), (high, float)]
check_in = _CheckInputs(n, p)
check_in(*extra_args)
x = _random_uniform(n, p, low, high)
coeffs = _gen_coeffs(p)
eps = _calc_eps(n)
x_coeffs = x @ coeffs
y = x_coeffs**2 + 0.5 * noise * eps
return x, y
def w_shaped(n, p, noise=False, low=-1, high=1):
r"""
Simulates univariate or multivariate quadratic data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
low : float, (default: -1)
The lower limit of the uniform distribution simulated from.
high : float, (default: -1)
The upper limit of the uniform distribution simulated from.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, 1)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
W-Shaped :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}`:
:math:`\mathcal{U}(-1, 1)^p`,
.. math::
X &\sim \mathcal{U}(-1, 1)^p \\
Y &= \left[ \left( (w^T X)^2 - \frac{1}{2} \right)^2
+ \frac{w^T U}{500} \right] + 0.5 \kappa \epsilon
Examples
--------
>>> from hyppo.sims import w_shaped
>>> x, y = w_shaped(100, 2)
>>> print(x.shape, y.shape)
(100, 2) (100, 1)
"""
extra_args = [(noise, bool), (low, float), (high, float)]
check_in = _CheckInputs(n, p)
check_in(*extra_args)
x = _random_uniform(n, p, low, high)
u = _random_uniform(n, p, 0, 1)
coeffs = _gen_coeffs(p)
eps = _calc_eps(n)
x_coeffs = x @ coeffs
u_coeffs = u @ coeffs
y = 4 * ((x_coeffs**2 - 0.5) ** 2 + u_coeffs / 500) + 0.5 * noise * eps
return x, y
def spiral(n, p, noise=False, low=0, high=5):
r"""
Simulates univariate or multivariate spiral data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
low : float, (default: 0)
The lower limit of the uniform distribution simulated from.
high : float, (default: 5)
The upper limit of the uniform distribution simulated from.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, 1)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
Spiral :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}`:
:math:`U \sim \mathcal{U}(0, 5)`, :math:`\epsilon \sim \mathcal{N}(0, 1)`
.. math::
X_{|d|} &= U \sin(\pi U) \cos^d(\pi U)\ \mathrm{for}\ d = 1,...,p-1 \\
X_{|p|} &= U \cos^p(\pi U) \\
Y &= U \sin(\pi U) + 0.4 p \epsilon
Examples
--------
>>> from hyppo.sims import spiral
>>> x, y = spiral(100, 2)
>>> print(x.shape, y.shape)
(100, 2) (100, 1)
"""
extra_args = [(noise, bool), (low, float), (high, float)]
check_in = _CheckInputs(n, p)
check_in(*extra_args)
coeffs = _gen_coeffs(p)
if p > 1:
noise = True
rx = _random_uniform(n, p=1, low=low, high=high)
ry = rx
rx = np.repeat(rx, p, axis=1)
z = rx
x = np.zeros((n, p))
x[:, 0] = np.cos(z[:, 0] * np.pi)
for i in range(p - 1):
x[:, i + 1] = x[:, i] * np.cos(z[:, i + 1] * np.pi)
x[:, i] = x[:, i] * np.sin(z[:, i + 1] * np.pi)
x = rx * x
y = ry * np.sin(z @ coeffs * np.pi)
eps = _calc_eps(n)
y = y + 0.4 * p * noise * eps
return x, y
def uncorrelated_bernoulli(n, p, noise=False, prob=0.5):
r"""
Simulates univariate or multivariate uncorrelated Bernoulli data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
prob : float, (default: 0.5)
The probability of the bernoulli distribution simulated from.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, 1)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
Uncorrelated Bernoulli :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}`:
:math:`U \sim \mathcal{B}(0.5)`, :math:`\epsilon_1 \sim \mathcal{N}(0, I_p)`,
:math:`\epsilon_2 \sim \mathcal{N}(0, 1)`,
.. math::
X &= \mathcal{B}(0.5)^p + 0.5 \epsilon_1 \\
Y &= (2U - 1) w^T X + 0.5 \epsilon_2
Examples
--------
>>> from hyppo.sims import uncorrelated_bernoulli
>>> x, y = uncorrelated_bernoulli(100, 2)
>>> print(x.shape, y.shape)
(100, 2) (100, 1)
"""
extra_args = [(noise, bool), (prob, float)]
check_in = _CheckInputs(n, p)
check_in(*extra_args)
binom = np.random.binomial(1, prob, size=(n, 1))
sig = np.identity(p)
gauss_noise = np.random.multivariate_normal(np.zeros(p), sig, size=n)
x = np.random.binomial(1, prob, size=(n, p)) + 0.5 * noise * gauss_noise
coeffs = _gen_coeffs(p)
eps = _calc_eps(n)
x_coeffs = x @ coeffs
y = binom * 2 - 1
y = np.multiply(x_coeffs, y) + 0.5 * noise * eps
return x, y
def logarithmic(n, p, noise=False):
r"""
Simulates univariate or multivariate logarithmic data.
Parameters
----------
n : int
The number of samples desired by the simulation.
p : int
The number of dimensions desired by the simulation.
noise : bool, (default: False)
Whether or not to include noise in the simulation.
Returns
-------
x, y : ndarray
Simulated data matrices. `x` and `y` have shapes `(n, p)` and `(n, p)`
where `n` is the number of samples and `p` is the number of
dimensions.
Notes
-----
Logarithmic :math:`(X, Y) \in \mathbb{R}^p \times \mathbb{R}^p`:
:math:`\epsilon \sim \mathcal{N}(0, I_p)`,
.. math::
X &\sim \mathcal{N}(0, I_p) \\
Y_{|d|} &= 2 \log_2 (|X_{|d|}|) + 3 \kappa \epsilon_{|d|}