-
Notifications
You must be signed in to change notification settings - Fork 6
/
database.py
1630 lines (1361 loc) · 67.4 KB
/
database.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
# Copyright 2020 resspect software
# Author: Emille E. O. Ishida
#
# created on 14 April 2020
#
# Licensed GNU General Public License v3.0;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.gnu.org/licenses/gpl-3.0.en.html
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import io
import os
import pandas as pd
import tarfile
from resspect.classifiers import *
from resspect.feature_extractors.bazin import BazinFeatureExtractor
from resspect.feature_extractors.bump import BumpFeatureExtractor
from resspect.query_strategies import *
from resspect.query_budget_strategies import *
from resspect.metrics import get_snpcc_metric
__all__ = ['DataBase']
FEATURE_EXTRACTOR_MAPPING = {
"bazin": BazinFeatureExtractor,
"bump": BumpFeatureExtractor
}
class DataBase:
"""DataBase object, upon which the active learning loop is performed.
Attributes
----------
alt_label: bool
Flag indicating training with less probable label.
classifier: sklearn.classifier
Classifier object.
classprob: np.array
Classification probability for all objects, [pIa, pnon-Ia].
data: pd.DataFrame
Complete information read from features files.
features: pd.DataFrame
Feature matrix to be used in classification (no metadata).
features_names: list
Header for attribute `features`.
metadata: pd.DataFrame
Features matrix which will not be used in classification.
metadata_names: list
Header for metadata.
metrics_list_names: list
Values for metric elements.
output_photo_Ia: pd.DataFrame
Returns metadata for photometrically classified Ia.
photo_Ia_metadata: pd.DataFrame
Metadata for photometrically classified object ids.
plasticc_mjd_lim: list
[min, max] mjds for plasticc data
predicted_class: np.array
Predicted classes - results from ML classifier.
queried_sample: list
Complete information of queried objects.
queryable_ids: np.array
Flag for objects available to be queried.
SNANA_types: dict
Map between PLAsTiCC zenodo and SNANA types.
telescope_names: list
Name of telescopes for which costs are given.
test_features: np.array
Features matrix for the test sample.
test_metadata: pd.DataFrame
Metadata for the test sample
test_labels: np.array
True classification for the test sample.
train_features: np.array
Features matrix for the train sample.
train_metadata: pd.DataFrame
Metadata for the training sample.
train_labels: np.array
Classes for the training sample.
validation_class: np.array
Estimated classes for validation sample.
validation_features: np.array
Features matrix for the validation sample.
validation_labels: np.array
Classes for the validation sample.
validation_metadata: pd.DataFrame
Metadata for the validation sample.
validation_prob: np.array
Estimated probabilities for validation sample.
Methods
-------
build_orig_samples()
Construct train and test samples as given in the original data set.
build_random_training(initial_training: int)
Construct initial random training and corresponding test sample.
build_previous_runs(path_to_train: str, path_to_queried: str)
Build train, test and queryable samples from previous runs.
build_samples(initial_training: str or int, nclass: int)
Separate train and test samples.
classify(method: str)
Apply a machine learning classifier.
classify_bootstrap(method: str)
Apply a machine learning classifier bootstrapping the classifier
evaluate_classification(metric_label: str)
Evaluate results from classification.
identify_keywords()
Break degenerescency between keywords with equal meaning.
load_extracted_features(path_to_features_file: str)
Load features from file
load_photometry_features(path_to_photometry_file:str)
Load photometric light curves from file
load_plasticc_mjd(path_to_data_dir: str)
Get min and max mjds for PLAsTiCC data
load_features_from_file(path_to_file: str, method: str)
Load features according to the chosen feature extraction method.
load_features(path_to_file: str, method: str)
Load features or photometry according to the chosen feature extraction method.
make_query(strategy: str, batch: int) -> list
Identify new object to be added to the training sample.
output_photo_Ia(threshold: float)
Returns the metadata for photometrically classified SN Ia.
save_metrics(loop: int, output_metrics_file: str)
Save current metrics to file.
save_queried_sample(queried_sample_file: str, loop: int, full_sample: str)
Save queried sample to file.
update_samples(query_indx: list)
Add the queried obj(s) to training and remove them from test.
Examples
--------
>>> from resspect import DataBase
Define the necessary paths
>>> path_to_bazin_file = 'results/Bazin.dat'
>>> metrics_file = 'results/metrics.dat'
>>> query_file = 'results/query_file.dat'
Initiate the DataBase object and load the data.
>>> data = DataBase()
>>> data.load_features(path_to_bazin_file, method='bazin')
Separate training and test samples and classify
>>> data.build_samples(initial_training='original', nclass=2)
>>> data.classify(method='RandomForest')
>>> print(data.classprob) # check predicted probabilities
[[0.461 0.539]
[0.346print(data.metrics_list_names) # check metric header
['acc', 'eff', 'pur', 'fom']
>>> print(data.metrics_list_values) # check metric values
[0.5975434599574068, 0.9024767801857585,
0.34684684684684686, 0.13572404702012383] 0.654]
...
[0.398 0.602]
[0.396 0.604]]
Calculate classification metrics
>>> data.evaluate_classification(metric_label='snpcc')
>>>
Make query, choose object and update samples
>>> indx = data.make_query(strategy='UncSampling', batch=1)
>>> data.update_samples(indx)
Save results to file
>>> data.save_metrics(loop=0, output_metrics_file=metrics_file)
>>> data.save_queried_sample(loop=0, queried_sample_file=query_file,
>>> full_sample=False)
"""
def __init__(self):
self.alt_label = False
self.classifier = None
self.classprob = np.array([])
self.data = pd.DataFrame()
self.ensemble_probs = None
self.features = pd.DataFrame([])
self.features_names = []
self.metadata = pd.DataFrame()
self.metadata_names = []
self.metrics_list_names = []
self.metrics_list_values = []
self.pool_features = np.array([])
self.pool_metadata = pd.DataFrame()
self.pool_labels = np.array([])
self.predicted_class = np.array([])
self.queried_sample = []
self.queryable_ids = np.array([])
self.SNANA_types = {90:11, 62:{1:3, 2:13}, 42:{1:2, 2:12, 3:14},
67:41, 52:43, 64:51, 95:60, 994:61, 992:62,
993:63, 15:64, 88:70, 92:80, 65:81, 16:83,
53:84, 991:90, 6:{1:91, 2:93}}
self.telescope_names = ['4m', '8m']
self.test_features = np.array([])
self.test_metadata = pd.DataFrame()
self.test_labels = np.array([])
self.train_features = np.array([])
self.train_metadata = pd.DataFrame()
self.train_labels = np.array([])
self.validation_class = np.array([])
self.validation_features = np.array([])
self.validation_labels = np.array([])
self.validation_metadata = pd.DataFrame()
self.validation_prob = np.array([])
def load_features_from_file(self, path_to_features_file: str, screen=False,
survey='DES', sample=None, feature_extractor='bazin'):
"""Load features from file.
Populate properties: features, feature_names, metadata
and metadata_names.
Parameters
----------
path_to_features_file: str
Complete path to features file.
screen: bool (optional)
If True, print on screen number of light curves processed.
Default is False.
survey: str (optional)
Name of survey. Used to infer the filter set.
Options are DES or LSST. Default is DES.
sample: str (optional)
If None, sample is given by a column within the given file.
else, read independent files for 'train' and 'test'.
Default is None.
feature_extractor: str (optional)
Function used for feature extraction. Options are "bazin" or
"bump". Default is "bump".
"""
# read matrix with features
if '.tar.gz' in path_to_features_file:
tar = tarfile.open(path_to_features_file, 'r:gz')
fname = tar.getmembers()[0]
content = tar.extractfile(fname).read()
data = pd.read_csv(io.BytesIO(content))
tar.close()
else:
data = pd.read_csv(path_to_features_file, index_col=False)
# check if queryable is there
if 'queryable' not in data.keys():
data['queryable'] = [True for i in range(data.shape[0])]
# list of features to use
if survey == 'DES':
if feature_extractor == "bazin":
self.features_names = ['gA', 'gB', 'gt0', 'gtfall', 'gtrise', 'rA',
'rB', 'rt0', 'rtfall', 'rtrise', 'iA', 'iB',
'it0', 'itfall', 'itrise', 'zA', 'zB', 'zt0',
'ztfall', 'ztrise']
elif feature_extractor == 'bump':
self.features_names = ['gp1', 'gp2', 'gp3', 'gmax_flux',
'rp1', 'rp2', 'rp3', 'rmax_flux',
'ip1', 'ip2', 'ip3', 'imax_flux',
'zp1', 'zp2', 'zp3', 'zmax_flux']
self.metadata_names = ['id', 'redshift', 'type', 'code',
'orig_sample', 'queryable']
if 'last_rmag' in data.keys():
self.metadata_names.append('last_rmag')
for name in self.telescope_names:
if 'cost_' + name in data.keys():
self.metadata_names = self.metadata_names + ['cost_' + name]
elif survey == 'LSST':
self.features_names = ['uA', 'uB', 'ut0', 'utfall', 'utrise',
'gA', 'gB', 'gt0', 'gtfall', 'gtrise',
'rA', 'rB', 'rt0', 'rtfall', 'rtrise',
'iA', 'iB', 'it0', 'itfall', 'itrise',
'zA', 'zB', 'zt0', 'ztfall', 'ztrise',
'YA', 'YB', 'Yt0', 'Ytfall', 'Ytrise']
if 'objid' in data.keys():
self.metadata_names = ['objid', 'redshift', 'type', 'code',
'orig_sample', 'queryable']
elif 'id' in data.keys():
self.metadata_names = ['id', 'redshift', 'type', 'code',
'orig_sample', 'queryable']
if 'last_rmag' in data.keys():
self.metadata_names.append('last_rmag')
for name in self.telescope_names:
if 'cost_' + name in data.keys():
self.metadata_names = self.metadata_names + ['cost_' + name]
else:
raise ValueError('Only "DES" and "LSST" filters are ' + \
'implemented at this point!')
if sample == None:
self.features = data[self.features_names].values
self.metadata = data[self.metadata_names]
if screen:
print('Loaded ', self.metadata.shape[0], ' samples!')
elif sample == 'train':
self.train_features = data[self.features_names].values
self.train_metadata = data[self.metadata_names]
if screen:
print('Loaded ', self.train_metadata.shape[0], ' ' + \
sample + ' samples!')
elif sample == 'test':
self.test_features = data[self.features_names].values
self.test_metadata = data[self.metadata_names]
if screen:
print('Loaded ', self.test_metadata.shape[0], ' ' + \
sample + ' samples!')
elif sample == 'validation':
self.validation_features = data[self.features_names].values
self.validation_metadata = data[self.metadata_names]
if screen:
print('Loaded ', self.validation_metadata.shape[0], ' ' + \
sample + ' samples!')
elif sample == 'pool':
self.pool_features = data[self.features_names].values
self.pool_metadata = data[self.metadata_names]
if screen:
print('Loaded ', self.pool_metadata.shape[0], ' ' + \
sample + ' samples!')
def load_photometry_features(self, path_to_photometry_file: str,
screen=False, sample=None):
"""Load photometry features from file.
Gets as input file containing fitted flux in homogeneized cadences.
Each line of the file is 1 object with concatenated fitted flux values.
Populate properties: data, features, feature_list, header
and header_list.
Parameters
----------
path_to_photometry_file: str
Complete path to photometry features file.
screen: bool (optional)
If True, print on screen number of light curves processed.
Default is False.
sample: str (optional)
If None, sample is given by a column within the given file.
else, read independent files for 'train' and 'test'.
Default is None.
"""
# read matrix with full photometry
if '.tar.gz' in path_to_photometry_file:
tar = tarfile.open(path_to_photometry_file, 'r:gz')
fname = tar.getmembers()[0]
content = tar.extractfile(fname).read()
data = pd.read_csv(io.BytesIO(content))
tar.close()
else:
data = pd.read_csv(path_to_photometry_file,
index_col=False)
if ' ' in data.keys()[0]:
data = pd.read_csv(path_to_photometry_file,
sep=' ', index_col=False)
# list of features to use
self.features_names = data.keys()[5:]
if 'objid' in data.keys():
id_name = 'objid'
elif 'id' in data.keys():
id_name = 'id'
self.metadata_names = [id_name, 'redshift', 'type',
'code', 'orig_sample']
if sample == None:
self.features = data[self.features_names]
self.metadata = data[self.metadata_names]
if screen:
print('Loaded ', self.metadata.shape[0], ' samples!')
elif sample == 'train':
self.train_features = data[self.features_names].values
self.train_metadata = data[self.metadata_names]
if screen:
print('Loaded ', self.train_metadata.shape[0], ' samples!')
elif sample == 'test':
self.test_features = data[self.features_names].values
self.test_metadata = data[self.metadata_names]
if screen:
print('\n Loaded ', self.test_metadata.shape[0],
' samples! \n')
def load_features(self, path_to_file: str, feature_extractor: str ='bazin',
screen=False, survey='DES', sample=None ):
"""Load features according to the chosen feature extraction method.
Populates properties: data, features, feature_list, header
and header_list.
Parameters
----------
path_to_file: str
Complete path to features file.
feature_extractor: str (optional)
Feature extraction method. The current implementation only
accepts =='bazin', 'bump' or 'photometry'.
Default is 'bazin'.
screen: bool (optional)
If True, print on screen number of light curves processed.
Default is False.
survey: str (optional)
Survey used to obtain the data. The current implementation
only accepts survey='DES' or 'LSST'.
Default is 'DES'.
sample: str (optional)
If None, sample is given by a column within the given file.
else, read independent files for 'train' and 'test'.
Default is None.
"""
if feature_extractor == "photometry":
self.load_photometry_features(path_to_file, screen=screen,
survey=survey, sample=sample)
elif feature_extractor in FEATURE_EXTRACTOR_MAPPING:
self.load_features_from_file(
path_to_file, screen=screen, survey=survey,
sample=sample, feature_extractor=feature_extractor)
else:
raise ValueError('Only bazin, bump or photometry features are implemented!'
'\n Feel free to add other options.')
def load_plasticc_mjd(self, path_to_data_dir):
"""Return all MJDs from 1 file from PLAsTiCC simulations.
Parameters
----------
path_to_data_dir: str
Complete path to PLAsTiCC data directory.
"""
# list of PLAsTiCC photometric files
flist = ['plasticc_test_lightcurves_' + str(x).zfill(2) + '.csv.gz'
for x in range(1, 12)]
# add training file
flist = flist + ['plasticc_train_lightcurves.csv.gz']
# store max and min mjds
min_mjd = []
max_mjd = []
for fname in flist:
# read photometric points
if '.tar.gz' in fname:
tar = tarfile.open(path_to_data_dir + fname, 'r:gz')
name = tar.getmembers()[0]
content = tar.extractfile(name).read()
all_photo = pd.read_csv(io.BytesIO(content))
else:
all_photo = pd.read_csv(path_to_data_dir + fname, index_col=False)
if ' ' in all_photo.keys()[0]:
all_photo = pd.read_csv(path_to_data_dir + fname, sep=' ',
index_col=False)
# get limit mjds
min_mjd.append(min(all_photo['mjd']))
max_mjd.append(max(all_photo['mjd']))
self.plasticc_mjd_lim = [min(min_mjd), max(max_mjd)]
def identify_keywords(self):
"""Break degenerescency between keywords with equal meaning.
Returns
-------
id_name: str
String of object identification.
"""
if 'id' in self.metadata_names:
id_name = 'id'
elif 'objid' in self.metadata_names:
id_name = 'objid'
return id_name
def build_orig_samples(self, nclass=2, screen=False, queryable=False,
sep_files=False):
"""Construct train and test samples as given in the original data set.
Populate properties: train_features, train_header, test_features,
test_header, queryable_ids (if flag available), train_labels and
test_labels.
Parameters
----------
nclass: int (optional)
Number of classes to consider in the classification
Currently only nclass == 2 is implemented.
queryable: bool (optional)
If True use queryable flag from file. Default is False.
screen: bool (optional)
If True display the dimensions of training and test samples.
sep_files: bool (optional)
If True, consider train and test samples separately read
from independent files.
"""
# object if keyword
id_name = self.identify_keywords()
if sep_files:
# get samples labels in a separate object
if self.train_metadata.shape[0] > 0:
train_labels = self.train_metadata['type'].values == 'Ia'
self.train_labels = train_labels.astype(int)
if self.test_metadata.shape[0] > 0:
test_labels = self.test_metadata['type'].values == 'Ia'
self.test_labels = test_labels.astype(int)
if self.validation_metadata.shape[0] > 0:
validation_labels = self.validation_metadata['type'].values == 'Ia'
self.validation_labels = validation_labels.astype(int)
if self.pool_metadata.shape[0] > 0:
pool_labels = self.pool_metadata['type'].values == 'Ia'
self.pool_labels = pool_labels.astype(int)
# identify asked to consider queryable flag
if queryable and len(self.pool_metadata) > 0:
queryable_flag = self.pool_metadata['queryable'].values
self.queryable_ids = self.pool_metadata[queryable_flag][id_name].values
elif len(self.pool_metadata) > 0:
self.queryable_ids = self.pool_metadata[id_name].values
else:
train_flag = self.metadata['orig_sample'] == 'train'
train_data = self.features[train_flag]
self.train_features = train_data
self.train_metadata = self.metadata[train_flag]
test_flag = self.metadata['orig_sample'] == 'test'
test_data = self.features[test_flag]
self.test_features = test_data
self.test_metadata = self.metadata[test_flag]
if 'validation' in self.metadata['orig_sample'].values:
val_flag = self.metadata['orig_sample'] == 'validation'
else:
val_flag = test_flag
val_data = self.features[val_flag]
self.validation_features = val_data
self.validation_metadata = self.metadata[val_flag]
if 'pool' in self.metadata['orig_sample'].values:
pool_flag = self.metadata['orig_sample'] == 'pool'
else:
pool_flag = test_flag
pool_data = self.features[pool_flag]
self.pool_features = pool_data
self.pool_metadata = self.metadata[pool_flag]
if queryable:
queryable_flag = self.pool_metadata['queryable'].values
self.queryable_ids = self.pool_metadata[queryable_flag][id_name].values
else:
self.queryable_ids = self.pool_metadata[id_name].values
if nclass == 2:
train_ia_flag = self.train_metadata['type'].values == 'Ia'
self.train_labels = train_ia_flag.astype(int)
test_ia_flag = self.test_metadata['type'].values == 'Ia'
self.test_labels = test_ia_flag.astype(int)
val_ia_flag = self.validation_metadata['type'].values == 'Ia'
self.validation_labels = val_ia_flag.astype(int)
pool_ia_flag = self.pool_metadata['type'].values == 'Ia'
self.pool_labels = pool_ia_flag.astype(int)
else:
raise ValueError("Only 'Ia x non-Ia' are implemented! "
"\n Feel free to add other options.")
if screen:
print('\n')
print('** Inside build_orig_samples: **')
print('Training set size: ', len(self.train_metadata))
print('Test set size: ', len(self.test_metadata))
print('Validation set size: ', len(self.validation_metadata))
print('Pool set size: ', len(self.pool_metadata))
print(' From which queryable: ', len(self.queryable_ids), '\n')
# check repeated ids between training and pool
if len(self.train_metadata) > 0 and len(self.pool_metadata) > 0:
for name in self.train_metadata[id_name].values:
if name in self.pool_metadata[id_name].values:
raise ValueError('Object ', name, 'found in both, training ' +\
'and pool samples!')
# check if there are repeated ids within each sample
names = ['train', 'pool', 'validation', 'test']
pds = [self.train_metadata, self.pool_metadata,
self.validation_metadata, self.test_metadata]
repeated_ids_samples = []
for i in range(4):
if pds[i].shape[0] > 0:
delta = len(np.unique(pds[i][id_name].values)) - pds[i].shape[0]
if abs(delta) > 0:
repeated_ids_samples.append([names[i], delta])
if len(repeated_ids_samples) > 0:
raise ValueError('There are repeated ids within ' + \
str(repeated_ids_samples) + ' sample!')
def build_random_training(self, initial_training: int, nclass=2, screen=False,
Ia_frac=0.5, queryable=False, sep_files=False):
"""Construct initial random training and corresponding test sample.
Populate properties: train_features, train_header, test_features,
test_header, queryable_ids (if flag available), train_labels and
test_labels.
Parameters
----------
initial_training : int
Required number of samples at random
Default is 10.
nclass: int (optional)
Number of classes to consider in the classification
Currently only nclass == 2 is implemented.
queryable: bool (optional)
If True build also queryable sample for time domain analysis.
Default is False.
screen: bool (optional)
If True display the dimensions of training and test samples.
Ia_frac: float in [0,1] (optional)
Fraction of Ia required in initial training sample.
Default is 0.5.
sep_files: bool (optional)
If True, consider train and test samples separately read
from independent files. Default is False.
"""
# object if keyword
id_name = self.identify_keywords()
# identify Ia
if sep_files:
data_copy = self.train_metadata.copy()
else:
data_copy = self.metadata.copy()
ia_flag = data_copy['type'] == 'Ia'
# separate per class
Ia_data = data_copy[ia_flag]
nonIa_data = data_copy[~ia_flag]
# get subsamples for training
temp_train_ia = Ia_data.sample(n=int(Ia_frac * initial_training))
temp_train_nonia = nonIa_data.sample(n=int((1-Ia_frac)*initial_training))
# join classes
frames_train = [temp_train_ia, temp_train_nonia]
temp_train = pd.concat(frames_train, ignore_index=True, axis=0)
train_flag = np.array([data_copy[id_name].values[i] in temp_train[id_name].values
for i in range(data_copy.shape[0])])
self.train_metadata = data_copy[train_flag]
if sep_files:
self.train_features = self.train_features[train_flag]
test_labels = self.test_metadata['type'].values == 'Ia'
self.test_labels = test_labels.astype(int)
validation_labels = self.validation_metadata['type'].values == 'Ia'
self.validation_labels = validation_labels.astype(int)
pool_labels = self.pool_metadata['type'].values == 'Ia'
self.pool_labels = pool_labels.astype(int)
else:
self.train_features = self.features[train_flag]
# get test sample
test_flag = ~train_flag
self.test_metadata = data_copy[test_flag]
self.test_features = self.features[test_flag]
self.pool_metadata = self.test_metadata
self.pool_features = self.test_features
self.validation_features = self.test_features
self.validation_metadata = self.test_metadata
test_label_flag = data_copy['type'][test_flag].values == 'Ia'
self.test_labels = test_label_flag.astype(int)
self.pool_labels = self.test_labels
self.validation_labels = self.test_labels
train_label_flag = data_copy['type'][train_flag].values == 'Ia'
self.train_labels = train_label_flag.astype(int)
if queryable and not sep_files:
queryable_flag = data_copy['queryable'].values
combined_flag = np.logical_and(~train_flag, queryable_flag)
self.queryable_ids = data_copy[combined_flag][id_name].values
elif not queryable and not sep_files:
self.queryable_ids = self.test_metadata[id_name].values
elif queryable and sep_files:
queryable_flag = self.pool_metadata['queryable'].values == True
self.queryable_ids = self.pool_metadata[id_name].values[queryable_flag]
elif not queryable and sep_files:
self.queryable_ids = self.pool_metadata[id_name].values
if screen:
print('\n')
print('** Inside build_random_training: **')
print('Training set size: ', self.train_metadata.shape[0])
print('Test set size: ', self.test_metadata.shape[0])
print('Validation set size: ', self.validation_metadata.shape[0])
print('Pool set size: ', self.pool_metadata.shape[0])
print(' From which queryable: ', self.queryable_ids.shape[0], '\n')
# check if there are repeated ids
for name in self.train_metadata[id_name].values:
if name in self.pool_metadata[id_name].values:
raise ValueError('Object ', name, ' present in both, ' + \
'training and pool samples!')
# check if there are repeated ids within each sample
names = ['train', 'pool', 'validation', 'test']
pds = [self.train_metadata, self.pool_metadata,
self.validation_metadata, self.test_metadata]
repeated_ids_samples = []
for i in range(4):
delta = len(np.unique(pds[i][id_name].values)) - pds[i].shape[0]
if abs(delta) > 0:
repeated_ids_samples.append([names[i], delta])
if len(repeated_ids_samples) > 0:
raise ValueError('There are repeated ids within ' + \
str(repeated_ids_samples) + ' sample!')
def build_samples(self, initial_training='original', nclass=2,
screen=False, Ia_frac=0.5,
queryable=False, save_samples=False, sep_files=False,
survey='DES', output_fname=' '):
"""Separate train, test and validation samples.
Populate properties: train_features, train_header, test_features,
test_header, queryable_ids (if flag available), train_labels and
test_labels.
Parameters
----------
initial_training : str or int
Choice of initial training sample.
If 'original': begin from the train sample flagged in original file
elif 'previous': continue from a previously run loop
elif int: choose the required number of samples at random,
ensuring that at least half are SN Ia.
Ia_frac: float in [0,1] (optional)
Fraction of Ia required in initial training sample.
Default is 0.5.
nclass: int (optional)
Number of classes to consider in the classification
Currently only nclass == 2 is implemented.
output_fname: str (optional)
Complete path to output file where initial training will be stored.
Only used if save_samples == True.
queryable: bool (optional)
If True build also queryable sample for time domain analysis.
Default is False.
screen: bool (optional)
If True display the dimensions of training and test samples.
save_samples: bool (optional)
If True, save training and test samples to file.
Default is False.
survey: str (optional)
Survey used to obtain the data. The current implementation
only accepts survey='DES' or 'LSST'. Default is 'DES'.
sep_files: bool (optional)
If True, consider samples separately read
from independent files. Default is False.
"""
if initial_training == 'original':
self.build_orig_samples(nclass=nclass, screen=screen,
queryable=queryable, sep_files=sep_files)
elif isinstance(initial_training, int):
self.build_random_training(initial_training=initial_training,
nclass=nclass, screen=screen,
Ia_frac=Ia_frac, queryable=queryable,
sep_files=sep_files)
if screen:
print('\n')
print('** Inside build_samples ** : ')
print('Training set size: ', self.train_metadata.shape[0])
print('Test set size: ', self.test_metadata.shape[0])
print('Validation set size: ', self.validation_metadata.shape[0])
print('Pool set size: ', self.pool_metadata.shape[0])
if len(self.pool_metadata) > 0:
print(' From which queryable: ',
self.queryable_ids.shape[0], '\n')
if save_samples:
full_header = self.metadata_names + self.features_names
wsample = open(output_fname, 'w')
for item in full_header:
wsample.write(item + ',')
wsample.write('\n')
for j in range(self.train_metadata.shape[0]):
for name in self.metadata_names:
wsample.write(str(self.train_metadata[name].iloc[j]) + ',')
for k in range(self.train_features.shape[1] - 1):
wsample.write(str(self.train_features[j][k]) + ',')
wsample.write(str(self.train_features[j][-1]) + '\n')
wsample.close()
def classify(self, method: str, save_predictions=False, pred_dir=None,
loop=None, screen=False, **kwargs):
"""Apply a machine learning classifier.
Populate properties: predicted_class and class_prob
Parameters
----------
method: str
Chosen classifier.
The current implementation accepts `RandomForest`,
'GradientBoostedTrees', 'KNN', 'MLP', 'SVM' and 'NB'.
loop: int (boolean)
Iteration loop. Only used if save+predictions==True.
Default is None
screen: bool (optional)
If True, print debug statements to screen.
Default is False.
save_predictions: bool (optional)
Save predictions to file. Default is False.
pred_dir: str (optional)
Output directory to store class predictions.
Only used if `save_predictions == True`. Default is None.
kwargs: extra parameters
Parameters required by the chosen classifier.
"""
if screen:
print('\n Inside classify: ')
print(' ... train_features: ', self.train_features.shape)
print(' ... train_labels: ', self.train_labels.shape)
print(' ... pool_features: ', self.pool_features.shape)
if method == 'RandomForest':
self.predicted_class, self.classprob, self.classifier = \
random_forest(self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'GradientBoostedTrees':
self.predicted_class, self.classprob, self.classifier = \
gradient_boosted_trees(self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'KNN':
self.predicted_class, self.classprob, self.classifier = \
knn(self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'MLP':
self.predicted_class, self.classprob, self.classifier = \
mlp(self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'SVM':
self.predicted_class, self.classprob, self.classifier = \
svm(self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'NB':
self.predicted_class, self.classprob, self.classifier = \
nbg(self.train_features, self.train_labels,
self.pool_features, **kwargs)
else:
raise ValueError("The only classifiers implemented are" +
"'RandomForest', 'GradientBoostedTrees'," +
"'KNN', 'MLP' and NB'." +
"\n Feel free to add other options.")
# estimate classification for validation sample
self.validation_class = \
self.classifier.predict(self.validation_features)
self.validation_prob = \
self.classifier.predict_proba(self.validation_features)
if save_predictions:
id_name = self.identify_keywords()
if self.alt_label:
out_fname = 'predict_loop_' + str(loop) + '_alt_label.csv'
else:
out_fname = 'predict_loop_' + str(loop) + '.csv'
op = open(pred_dir + '/' + out_fname, 'w')
op.write(id_name + ',' + 'prob_nIa, prob_Ia,pred_class\n')
for i in range(self.validation_metadata.shape[0]):
op.write(str(self.validation_metadata[id_name].iloc[i]) + ',')
op.write(str(self.validation_prob[i][0]) + ',')
op.write(str(self.validation_prob[i][1]) + ',')
op.write(str(self.validation_class[i]) + '\n')
op.close()
def classify_bootstrap(self, method: str, save_predictions=False, pred_dir=None,
loop=None, n_ensembles=10, screen=False, **kwargs):
"""Apply a machine learning classifier bootstrapping the classifier.
Populate properties: predicted_class, class_prob and ensemble_probs.
Parameters
----------
method: str
Chosen classifier.
The current implementation accepts `RandomForest`,
'GradientBoostedTrees', 'KNN', 'MLP', 'SVM' and 'NB'.
save_predictions: bool (optional)
Save predictions to file. Default is False.
pred_dir: str (optional)
Output directory to store class predictions.
Only used if `save_predictions == True`. Default is None.
loop: int (optional)
Corresponding loop. Default is None.
kwargs: extra parameters
Parameters required by the chosen classifier.
"""
if screen:
print('\n Inside classify_bootstrap: ')
print(' ... train_features: ', self.train_features.shape)
print(' ... train_labels: ', self.train_labels.shape)
print(' ... pool_features: ', self.pool_features.shape)
if method == 'RandomForest':
self.predicted_class, self.classprob, self.ensemble_probs, self.classifier = \
bootstrap_clf(random_forest, n_ensembles,
self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'GradientBoostedTrees':
self.predicted_class, self.classprob, self.ensemble_probs, self.classifier = \
bootstrap_clf(gradient_boosted_trees, n_ensembles,
self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'KNN':
self.predicted_class, self.classprob, self.ensemble_probs, self.classifier = \
bootstrap_clf(knn, n_ensembles,
self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'MLP':
self.predicted_class, self.classprob, self.ensemble_probs, self.classifier = \
bootstrap_clf(mlp, n_ensembles,
self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'SVM':
self.predicted_class, self.classprob, self.ensemble_probs, self.classifier = \
bootstrap_clf(svm, n_ensembles,
self.train_features, self.train_labels,
self.pool_features, **kwargs)
elif method == 'NB':