/
representations.py
1062 lines (875 loc) · 40.9 KB
/
representations.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
"""Vector representations of persistence diagrams."""
# License: GNU AGPLv3
import types
from numbers import Real
import numpy as np
import plotly.graph_objects as gobj
from joblib import Parallel, delayed, effective_n_jobs
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import gen_even_slices
from sklearn.utils.validation import check_is_fitted
from ._metrics import betti_curves, landscapes, heats, \
persistence_images, silhouettes
from ._utils import _subdiagrams, _bin, _calculate_weights
from ..base import PlotterMixin
from ..plotting import plot_heatmap
from ..utils._docs import adapt_fit_transform_docs
from ..utils.intervals import Interval
from ..utils.validation import validate_params, check_diagrams
def identity(x):
"""The identity function."""
return x
@adapt_fit_transform_docs
class BettiCurve(BaseEstimator, TransformerMixin, PlotterMixin):
""":ref:`Betti curves <betti_curve>` of persistence diagrams.
Given a persistence diagram consisting of birth-death-dimension triples
[b, d, q], subdiagrams corresponding to distinct homology dimensions are
considered separately, and their respective Betti curves are obtained by
evenly sampling the :ref:`filtration parameter <filtered_complex>`.
Parameters
----------
n_bins : int, optional, default: ``100``
The number of filtration parameter values, per available homology
dimension, to sample during :meth:`fit`.
n_jobs : int or None, optional, default: ``None``
The number of jobs to use for the computation. ``None`` means 1
unless in a :obj:`joblib.parallel_backend` context. ``-1`` means
using all processors.
Attributes
----------
homology_dimensions_ : list
Homology dimensions seen in :meth:`fit`, sorted in ascending order.
samplings_ : dict
For each number in `homology_dimensions_`, a discrete sampling of
filtration parameters, calculated during :meth:`fit` according to the
minimum birth and maximum death values observed across all samples.
See also
--------
PersistenceLandscape, PersistenceEntropy, HeatKernel, Amplitude, \
PairwiseDistance, Silhouette, PersistenceImage,\
gtda.homology.VietorisRipsPersistence
Notes
-----
The samplings in :attr:`samplings_` are in general different between
different homology dimensions. This means that the j-th entry of a Betti
curve in homology dimension q typically arises from a different parameter
values to the j-th entry of a curve in dimension q'.
"""
_hyperparameters = {
'n_bins': {'type': int, 'in': Interval(1, np.inf, closed='left')}}
def __init__(self, n_bins=100, n_jobs=None):
self.n_bins = n_bins
self.n_jobs = n_jobs
def fit(self, X, y=None):
"""Store all observed homology dimensions in
:attr:`homology_dimensions_` and, for each dimension separately,
store evenly sample filtration parameter values in :attr:`samplings_`.
Then, return the estimator.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
self : object
"""
X = check_diagrams(X)
validate_params(
self.get_params(), self._hyperparameters, exclude=['n_jobs'])
self.homology_dimensions_ = sorted(list(set(X[0, :, 2])))
self._n_dimensions = len(self.homology_dimensions_)
self._samplings, _ = _bin(X, metric='betti', n_bins=self.n_bins)
self.samplings_ = {dim: s.flatten()
for dim, s in self._samplings.items()}
return self
def transform(self, X, y=None):
"""Compute the Betti curves of diagrams in `X`.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
Xt : ndarray of shape (n_samples, n_homology_dimensions, n_bins)
Betti curves: one curve (represented as a one-dimensional array
of integer values) per sample and per homology dimension seen
in :meth:`fit`. Index i along axis 1 corresponds to the i-th
homology dimension in :attr:`homology_dimensions_`.
"""
check_is_fitted(self)
X = check_diagrams(X)
Xt = Parallel(n_jobs=self.n_jobs)(delayed(betti_curves)(
_subdiagrams(X, [dim], remove_dim=True)[s],
self._samplings[dim])
for dim in self.homology_dimensions_
for s in gen_even_slices(X.shape[0],
effective_n_jobs(self.n_jobs)))
Xt = np.concatenate(Xt).\
reshape(self._n_dimensions, X.shape[0], -1).\
transpose((1, 0, 2))
return Xt
def plot(self, Xt, sample=0, homology_dimensions=None):
"""Plot a sample from a collection of Betti curves arranged as in
the output of :meth:`transform`. Include homology in multiple
dimensions.
Parameters
----------
Xt : ndarray of shape (n_samples, n_homology_dimensions, n_bins)
Collection of Betti curves, such as returned by :meth:`transform`.
sample : int, optional, default: ``0``
Index of the sample in `Xt` to be plotted.
homology_dimensions : list, tuple or None, optional, default: ``None``
Which homology dimensions to include in the plot. ``None`` means
plotting all dimensions present in :attr:`homology_dimensions_`.
"""
check_is_fitted(self)
if homology_dimensions is None:
_homology_dimensions = list(enumerate(self.homology_dimensions_))
else:
_homology_dimensions = []
for dim in homology_dimensions:
if dim not in self.homology_dimensions_:
raise ValueError(
f"All homology dimensions must be in "
f"self.homology_dimensions_ which is "
f"{self.homology_dimensions_}. {dim} is not.")
else:
homology_dimensions_arr = np.array(
self.homology_dimensions_)
ix = np.flatnonzero(homology_dimensions_arr == dim)[0]
_homology_dimensions.append((ix, dim))
layout = dict(
xaxis1=dict(
title="Filtration parameter",
side="bottom",
type="linear",
ticks="outside",
anchor="x1",
showline=True,
zeroline=True,
showexponent="all",
exponentformat="e"
),
yaxis1=dict(
title="Betti number",
side="left",
type="linear",
ticks="outside",
anchor="y1",
showline=True,
zeroline=True,
showexponent="all",
exponentformat="e"
),
plot_bgcolor="white"
)
fig = gobj.Figure(layout=layout)
fig.update_xaxes(zeroline=True, linewidth=1, linecolor="black",
mirror=False)
fig.update_yaxes(zeroline=True, linewidth=1, linecolor="black",
mirror=False)
for ix, dim in _homology_dimensions:
fig.add_trace(gobj.Scatter(x=self.samplings_[dim],
y=Xt[sample][ix],
mode='lines', showlegend=True,
name=f"H{int(dim)}"))
fig.show()
@adapt_fit_transform_docs
class PersistenceLandscape(BaseEstimator, TransformerMixin, PlotterMixin):
""":ref:`Persistence landscapes <persistence_landscape>` of persistence
diagrams.
Given a persistence diagram consisting of birth-death-dimension triples
[b, d, q], subdiagrams corresponding to distinct homology dimensions are
considered separately, and layers of their respective persistence
landscapes are obtained by evenly sampling the :ref:`filtration parameter
<filtered_complex>`.
Parameters
----------
n_layers : int, optional, default: ``1``
How many layers to consider in the persistence landscape.
n_bins : int, optional, default: ``100``
The number of filtration parameter values, per available
homology dimension, to sample during :meth:`fit`.
n_jobs : int or None, optional, default: ``None``
The number of jobs to use for the computation. ``None`` means 1 unless
in a :obj:`joblib.parallel_backend` context. ``-1`` means using all
processors.
Attributes
----------
homology_dimensions_ : list
Homology dimensions seen in :meth:`fit`.
samplings_ : dict
For each number in `homology_dimensions_`, a discrete sampling of
filtration parameters, calculated during :meth:`fit` according to the
minimum birth and maximum death values observed across all samples.
See also
--------
BettiCurve, PersistenceEntropy, HeatKernel, Amplitude, \
PairwiseDistance, Silhouette, PersistenceImage, \
gtda.homology.VietorisRipsPersistence
Notes
-----
The samplings in :attr:`samplings_` are in general different between
different homology dimensions. This means that the j-th entry of the
k-layer of a persistence landscape in homology dimension q typically
arises from a different parameter value to the j-th entry of a k-layer in
dimension q'.
"""
_hyperparameters = {
'n_bins': {'type': int, 'in': Interval(1, np.inf, closed='left')},
'n_layers': {'type': int, 'in': Interval(1, np.inf, closed='left')}}
def __init__(self, n_layers=1, n_bins=100, n_jobs=None):
self.n_layers = n_layers
self.n_bins = n_bins
self.n_jobs = n_jobs
def fit(self, X, y=None):
"""Store all observed homology dimensions in
:attr:`homology_dimensions_` and, for each dimension separately,
store evenly sample filtration parameter values in :attr:`samplings_`.
Then, return the estimator.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
self : object
"""
X = check_diagrams(X)
validate_params(
self.get_params(), self._hyperparameters, exclude=['n_jobs'])
self.homology_dimensions_ = sorted(list(set(X[0, :, 2])))
self._n_dimensions = len(self.homology_dimensions_)
self._samplings, _ = _bin(X, metric="landscape", n_bins=self.n_bins)
self.samplings_ = {dim: s.flatten()
for dim, s in self._samplings.items()}
return self
def transform(self, X, y=None):
"""Compute the persistence landscapes of diagrams in `X`.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
Xt : ndarray of shape (n_samples, n_homology_dimensions, \
n_layers, n_bins)
Persistence lanscapes: one landscape (represented as a
two-dimensional array) per sample and per homology dimension seen
in :meth:`fit`. Each landscape contains a number `n_layers` of
layers. Index i along axis 1 corresponds to the i-th homology
dimension in :attr:`homology_dimensions_`.
"""
check_is_fitted(self)
X = check_diagrams(X)
Xt = Parallel(n_jobs=self.n_jobs)(delayed(landscapes)(
_subdiagrams(X, [dim], remove_dim=True)[s],
self._samplings[dim],
self.n_layers)
for dim in self.homology_dimensions_
for s in gen_even_slices(X.shape[0],
effective_n_jobs(self.n_jobs)))
Xt = np.concatenate(Xt).reshape(self._n_dimensions, X.shape[0],
self.n_layers, self.n_bins).\
transpose((1, 0, 2, 3))
return Xt
def plot(self, Xt, sample=0, homology_dimensions=None):
"""Plot a sample from a collection of persistence landscapes arranged
as in the output of :meth:`transform`. Include homology in multiple
dimensions.
Parameters
----------
Xt : ndarray of shape (n_samples, n_homology_dimensions, n_layers, \
n_bins
Collection of persistence landscapes, such as returned by
:meth:`transform`.
sample : int, optional, default: ``0``
Index of the sample in `Xt` to be plotted.
homology_dimensions : list, tuple or None, optional, default: ``None``
Homology dimensions for which the landscape should be plotted.
``None`` means plotting all dimensions present in
:attr:`homology_dimensions_`.
"""
check_is_fitted(self)
if homology_dimensions is None:
_homology_dimensions = list(enumerate(self.homology_dimensions_))
else:
_homology_dimensions = []
for dim in homology_dimensions:
if dim not in self.homology_dimensions_:
raise ValueError(
f"All homology dimensions must be in "
f"self.homology_dimensions_ which is "
f"{self.homology_dimensions_}. {dim} is not.")
else:
homology_dimensions_arr = np.array(
self.homology_dimensions_)
ix = np.flatnonzero(homology_dimensions_arr == dim)[0]
_homology_dimensions.append((ix, dim))
layout = dict(
xaxis1=dict(
side="bottom",
type="linear",
ticks="outside",
anchor="y1",
showline=True,
zeroline=True,
showexponent="all",
exponentformat="e"
),
yaxis1=dict(
side="left",
type="linear",
ticks="outside",
anchor="x1",
showline=True,
zeroline=True,
showexponent="all",
exponentformat="e"
),
plot_bgcolor="white"
)
Xt_sample = Xt[sample]
for ix, dim in _homology_dimensions:
layout_dim = layout.copy()
layout_dim['title'] = "Persistence landscape for homology " + \
"dimension {}".format(int(dim))
fig = gobj.Figure(layout=layout_dim)
fig.update_xaxes(zeroline=True, linewidth=1, linecolor="black",
mirror=False)
fig.update_yaxes(zeroline=True, linewidth=1, linecolor="black",
mirror=False)
n_layers = Xt_sample.shape[1]
for layer in range(n_layers):
fig.add_trace(gobj.Scatter(x=self.samplings_[dim],
y=Xt_sample[ix, layer],
mode='lines', showlegend=True,
hoverinfo='none',
name=f"Layer {layer + 1}"))
fig.show()
@adapt_fit_transform_docs
class HeatKernel(BaseEstimator, TransformerMixin, PlotterMixin):
"""Convolution of persistence diagrams with a Gaussian kernel.
Based on ideas in [1]_. Given a persistence diagram consisting of
birth-death-dimension triples [b, d, q], subdiagrams corresponding to
distinct homology dimensions are considered separately and regarded as sums
of Dirac deltas. Then, the convolution with a Gaussian kernel is computed
over a rectangular grid of locations evenly sampled from appropriate
ranges of the :ref:`filtration parameter <filtered_complex>`. The
same is done with the reflected images of the subdiagrams about the
diagonal, and the difference between the results of the two convolutions is
computed. The result can be thought of as a (multi-channel) raster image.
Parameters
----------
sigma : float, optional default ``1.``
Standard deviation for Gaussian kernel.
n_bins : int, optional, default: ``100``
The number of filtration parameter values, per available homology
dimension, to sample during :meth:`fit`.
n_jobs : int or None, optional, default: ``None``
The number of jobs to use for the computation. ``None`` means 1 unless
in a :obj:`joblib.parallel_backend` context. ``-1`` means using all
processors.
Attributes
----------
homology_dimensions_ : list
Homology dimensions seen in :meth:`fit`.
samplings_ : dict
For each number in `homology_dimensions_`, a discrete sampling of
filtration parameters, calculated during :meth:`fit` according to the
minimum birth and maximum death values observed across all samples.
See also
--------
BettiCurve, PersistenceLandscape, PersistenceEntropy, Amplitude, \
PairwiseDistance, Silhouette, PersistenceImage, \
gtda.homology.VietorisRipsPersistence
Notes
-----
The samplings in :attr:`samplings_` are in general different between
different homology dimensions. This means that the (i, j)-th pixel
of an image in homology dimension q typically arises from a different
pair of parameter values to the (i, j)-th pixel of an image in
dimension q'.
References
----------
.. [1] J. Reininghaus, S. Huber, U. Bauer, and R. Kwitt, "A Stable
Multi-Scale Kernel for Topological Machine Learning"; *2015 IEEE
Conference on Computer Vision and Pattern Recognition (CVPR)*,
pp. 4741--4748, 2015; doi: `10.1109/CVPR.2015.7299106
<http://dx.doi.org/10.1109/CVPR.2015.7299106>`_.
"""
_hyperparameters = {
'n_bins': {'type': int, 'in': Interval(1, np.inf, closed='left')},
'sigma': {'type': Real, 'in': Interval(0, np.inf, closed='neither')}}
def __init__(self, sigma=1., n_bins=100, n_jobs=None):
self.sigma = sigma
self.n_bins = n_bins
self.n_jobs = n_jobs
def fit(self, X, y=None):
"""Store all observed homology dimensions in
:attr:`homology_dimensions_` and, for each dimension separately,
store evenly sample filtration parameter values in :attr:`samplings_`.
Then, return the estimator.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
self : object
"""
X = check_diagrams(X)
validate_params(
self.get_params(), self._hyperparameters, exclude=['n_jobs'])
self.homology_dimensions_ = sorted(list(set(X[0, :, 2])))
self._n_dimensions = len(self.homology_dimensions_)
self._samplings, self._step_size = _bin(
X, metric='heat', n_bins=self.n_bins)
self.samplings_ = {dim: s.flatten()
for dim, s in self._samplings.items()}
return self
def transform(self, X, y=None):
"""Compute multi-channel raster images from diagrams in `X` by
convolution with a Gaussian kernel and reflection about the diagonal.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
Xt : ndarray of shape (n_samples, n_homology_dimensions, n_bins, \
n_bins)
Multi-channel raster images: one image per sample and one
channel per homology dimension seen in :meth:`fit`. Index i
along axis 1 corresponds to the i-th homology dimension in
:attr:`homology_dimensions_`.
"""
check_is_fitted(self)
X = check_diagrams(X, copy=True)
Xt = Parallel(n_jobs=self.n_jobs)(delayed(
heats)(_subdiagrams(X, [dim], remove_dim=True)[s],
self._samplings[dim], self._step_size[dim], self.sigma)
for dim in self.homology_dimensions_
for s in gen_even_slices(X.shape[0],
effective_n_jobs(self.n_jobs)))
Xt = np.concatenate(Xt).reshape(self._n_dimensions, X.shape[0],
self.n_bins, self.n_bins).\
transpose((1, 0, 2, 3))
return Xt
def plot(self, Xt, sample=0, homology_dimension_ix=0, colorscale='blues'):
"""Plot a single channel – corresponding to a given homology
dimension – in a sample from a collection of heat kernel images.
Parameters
----------
Xt : ndarray of shape (n_samples, n_homology_dimensions, n_bins, \
n_bins)
Collection of multi-channel raster images, such as returned by
:meth:`transform`.
sample : int, optional, default: ``0``
Index of the sample in `Xt` to be selected.
homology_dimension_ix : int, optional, default: ``0``
Index of the channel in the selected sample to be plotted. If
`Xt` is the result of a call to :meth:`transform` and this
index is i, the plot corresponds to the homology dimension given by
the i-th entry in :attr:`homology_dimensions_`.
colorscale : str, optional, default: ``'blues'``
Color scale to be used in the heat map. Can be anything allowed by
:class:`plotly.graph_objects.Heatmap`.
"""
check_is_fitted(self)
return plot_heatmap(Xt[sample][homology_dimension_ix],
x=self.samplings_[homology_dimension_ix],
y=self.samplings_[homology_dimension_ix],
colorscale=colorscale)
@adapt_fit_transform_docs
class PersistenceImage(BaseEstimator, TransformerMixin, PlotterMixin):
""":ref:`Persistence images <persistence_image>` of persistence
diagrams.
Based on ideas in [1]_. Given a persistence diagram consisting of
birth-death-dimension triples [b, d, q], the equivalent diagrams of
birth-persistence-dimension [b, d-b, q] triples are computed and
subdiagrams corresponding to distinct homology dimensions are considered
separately and regarded as sums of Dirac deltas. Then, the convolution
with a Gaussian kernel is computed over a rectangular grid of locations
evenly sampled from appropriate ranges of the :ref:`filtration parameter
<filtered_complex>`. The result can be thought of as a (multi-channel)
raster image.
Parameters
----------
sigma : float, optional default ``1.``
Standard deviation for Gaussian kernel.
n_bins : int, optional, default: ``100``
The number of filtration parameter values, per available homology
dimension, to sample during :meth:`fit`.
weight_function : callable or None, default: ``None``
Function mapping the 1D array of persistence values of the points of an
input diagram to a 1D array of weights. ``None`` is equivalent to
passing the identity function.
n_jobs : int or None, optional, default: ``None``
The number of jobs to use for the computation. ``None`` means 1 unless
in a :obj:`joblib.parallel_backend` context. ``-1`` means using all
processors.
Attributes
----------
effective_weight_function_ : callable
Effective function corresponding to `weight_function`. Set in
:meth:`fit`.
homology_dimensions_ : list
Homology dimensions seen in :meth:`fit`.
samplings_ : dict
For each number in `homology_dimensions_`, a discrete sampling of
filtration parameters, calculated during :meth:`fit` according to the
minimum birth and maximum death values observed across all samples.
weights_ : dict
For each number in `homology_dimensions_`, an array of weights
corresponding to the persistence values obtained from `samplings_`
calculated during :meth:`fit` using the `weight_function`.
See also
--------
BettiCurve, PersistenceLandscape, PersistenceEntropy, HeatKernel, \
Amplitude, PairwiseDistance, gtda.homology.VietorisRipsPersistence
Notes
-----
The samplings in :attr:`samplings_` are in general different between
different homology dimensions. This means that the (i, j)-th pixel of a
persistence image in homology dimension q typically arises from a different
pair of parameter values to the (i, j)-th pixel of a persistence image in
dimension q'.
References
----------
.. [1] H. Adams, T. Emerson, M. Kirby, R. Neville, C. Peterson, P. Shipman,
S. Chepushtanova, E. Hanson, F. Motta, and L. Ziegelmeier,
"Persistence Images: A Stable Vector Representation of Persistent
Homology"; *Journal of Machine Learning Research 18, 1*,
pp. 218-252, 2017; doi: `10.5555/3122009.3122017
<http://dx.doi.org/10.5555/3122009.3122017>`_.
"""
_hyperparameters = {
'n_bins': {'type': int, 'in': Interval(1, np.inf, closed='left')},
'sigma': {'type': Real, 'in': Interval(0, np.inf, closed='neither')},
'weight_function': {'type': (types.FunctionType, type(None))}}
def __init__(self, sigma=1., n_bins=100, weight_function=None,
n_jobs=None):
self.sigma = sigma
self.n_bins = n_bins
self.weight_function = weight_function
self.n_jobs = n_jobs
def fit(self, X, y=None):
"""Store all observed homology dimensions in
:attr:`homology_dimensions_` and, for each dimension separately,
store evenly sample filtration parameter values in :attr:`samplings_`.
Then, return the estimator.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
self : object
"""
X = check_diagrams(X)
validate_params(
self.get_params(), self._hyperparameters, exclude=['n_jobs'])
if self.weight_function is None:
self.effective_weight_function_ = identity
else:
self.effective_weight_function_ = self.weight_function
self.homology_dimensions_ = sorted(list(set(X[0, :, 2])))
self._n_dimensions = len(self.homology_dimensions_)
self._samplings, self._step_size = _bin(
X, metric='persistence_image', n_bins=self.n_bins)
self.samplings_ = {dim: s.transpose()
for dim, s in self._samplings.items()}
self.weights_ = _calculate_weights(X, self.effective_weight_function_,
self._samplings)
return self
def transform(self, X, y=None):
"""Compute multi-channel raster images from diagrams in `X` by
convolution with a Gaussian kernel.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
Xt : ndarray of shape (n_samples, n_homology_dimensions, n_bins, \
n_bins)
Multi-channel raster images: one image per sample and one channel
per homology dimension seen in :meth:`fit`. Index i along axis 1
corresponds to the i-th homology dimension in
:attr:`homology_dimensions_`.
"""
check_is_fitted(self)
X = check_diagrams(X, copy=True)
Xt = Parallel(n_jobs=self.n_jobs)(
delayed(persistence_images)(_subdiagrams(X, [dim],
remove_dim=True)[s],
self._samplings[dim],
self._step_size[dim],
self.weights_[dim],
self.sigma)
for dim in self.homology_dimensions_
for s in gen_even_slices(X.shape[0],
effective_n_jobs(self.n_jobs))
)
Xt = np.concatenate(Xt).reshape(self._n_dimensions, X.shape[0],
self.n_bins, self.n_bins).\
transpose((1, 0, 2, 3))
return Xt
def plot(self, Xt, sample=0, homology_dimension_ix=0, colorscale='blues'):
"""Plot a single channel – corresponding to a given homology
dimension – in a sample from a collection of persistence images.
Parameters
----------
Xt : ndarray of shape (n_samples, n_homology_dimensions, n_bins, \
n_bins)
Collection of multi-channel raster images, such as returned by
:meth:`transform`.
sample : int, optional, default: ``0``
Index of the sample in `Xt` to be selected.
homology_dimension_ix : int, optional, default: ``0``
Index of the channel in the selected sample to be plotted. If
`Xt` is the result of a call to :meth:`transform` and this
index is i, the plot corresponds to the homology dimension given by
the i-th entry in :attr:`homology_dimensions_`.
colorscale : str, optional, default: ``'blues'``
Color scale to be used in the heat map. Can be anything allowed by
:class:`plotly.graph_objects.Heatmap`.
"""
check_is_fitted(self)
samplings_x, samplings_y = self.samplings_[homology_dimension_ix]
return plot_heatmap(Xt[sample][homology_dimension_ix],
x=samplings_x,
y=samplings_y,
colorscale=colorscale)
@adapt_fit_transform_docs
class Silhouette(BaseEstimator, TransformerMixin, PlotterMixin):
""":ref:`Power-weighted silhouettes <weighted_silhouette>` of persistence
diagrams.
Based on ideas in [1]_. Given a persistence diagram consisting of
birth-death-dimension triples [b, d, q], subdiagrams corresponding to
distinct homology dimensions are considered separately, and their
respective silhouette by sampling the silhouette function over evenly
spaced locations from appropriate ranges of the :ref:`filtration parameter
<filtered_complex>`.
Parameters
----------
power: float, optional, default: ``1.``
The power to which persistence values are raised to define the
:ref:`power-weighted silhouettes <weighted_silhouette>`.
n_bins : int, optional, default: ``100``
The number of filtration parameter values, per available homology
dimension, to sample during :meth:`fit`.
n_jobs : int or None, optional, default: ``None``
The number of jobs to use for the computation. ``None`` means 1
unless in a :obj:`joblib.parallel_backend` context. ``-1`` means
using all processors.
Attributes
----------
homology_dimensions_ : list
Homology dimensions seen in :meth:`fit`, sorted in ascending order.
samplings_ : dict
For each number in `homology_dimensions_`, a discrete sampling of
filtration parameters, calculated during :meth:`fit` according to the
minimum birth and maximum death values observed across all samples.
See also
--------
PersistenceLandscape, PersistenceEntropy, HeatKernel, Amplitude, \
PairwiseDistance, BettiCurve, gtda.homology.VietorisRipsPersistence
Notes
-----
The samplings in :attr:`samplings_` are in general different between
different homology dimensions. This means that the j-th entry of
a silhouette in homology dimension q typically arises from
a different parameter values to the j-th entry of a curve
in dimension q'.
References
----------
.. [1] F. Chazal, B. T. Fasy, F. Lecci, A. Rinaldo, and L. Wasserman,
"Stochastic Convergence of Persistence Landscapes and Silhouettes";
*In Proceedings of the thirtieth annual symposium on Computational
Geometry*, Kyoto, Japan, 2014, pp. 474–483;
doi: `10.1145/2582112.2582128
<http://dx.doi.org/10.1145/2582112.2582128>`_.
"""
_hyperparameters = {
'n_bins': {'type': int, 'in': Interval(1, np.inf, closed='left')},
'power': {'type': Real, 'in': Interval(0, np.inf, closed='right')}}
def __init__(self, power=1., n_bins=100, n_jobs=None):
self.power = power
self.n_bins = n_bins
self.n_jobs = n_jobs
def fit(self, X, y=None):
"""Store all observed homology dimensions in
:attr:`homology_dimensions_` and, for each dimension separately,
store evenly sample filtration parameter values in :attr:`samplings_`.
Then, return the estimator.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
self : object
"""
X = check_diagrams(X)
validate_params(
self.get_params(), self._hyperparameters, exclude=['n_jobs'])
self.homology_dimensions_ = sorted(list(set(X[0, :, 2])))
self._n_dimensions = len(self.homology_dimensions_)
self._samplings, _ = _bin(X, metric='silhouette', n_bins=self.n_bins)
self.samplings_ = {dim: s.flatten()
for dim, s in self._samplings.items()}
return self
def transform(self, X, y=None):
"""Compute silhouettes of diagrams in `X`.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
Xt : ndarray of shape (n_samples, n_homology_dimensions, n_bins)
One silhouette (represented as a one-dimensional array)
per sample and per homology dimension seen
in :meth:`fit`. Index i along axis 1 corresponds to the i-th
homology dimension in :attr:`homology_dimensions_`.
"""
check_is_fitted(self)
X = check_diagrams(X)
Xt = (Parallel(n_jobs=self.n_jobs)
(delayed(silhouettes)(_subdiagrams(X, [dim], remove_dim=True)[s],
self._samplings[dim], power=self.power)
for dim in self.homology_dimensions_
for s in gen_even_slices(X.shape[0],
effective_n_jobs(self.n_jobs))))
Xt = np.concatenate(Xt). \
reshape(self._n_dimensions, X.shape[0], -1). \
transpose((1, 0, 2))
return Xt
def plot(self, Xt, sample=0, homology_dimensions=None):
"""Plot a sample from a collection of silhouettes arranged as in
the output of :meth:`transform`. Include homology in multiple
dimensions.
Parameters
----------
Xt : ndarray of shape (n_samples, n_homology_dimensions, n_bins)
Collection of silhouettes, such as returned by :meth:`transform`.
sample : int, optional, default: ``0``
Index of the sample in `Xt` to be plotted.