-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcreate_sets.py
executable file
·1421 lines (1082 loc) · 51.1 KB
/
create_sets.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
#!/usr/bin/env python3
# pylint: disable=too-many-lines
"""
CBDA validation and training set creation.
This script defines validation and training sets for a CBDA project.
Inputs:
File name of original data file.
This may be a zip file or a plain text csv file.
If a zip file is specified, the following assumptions are made:
There is only one file in the file archive.
The name of the file in the file archive is the same as the
name of the zip file, except it has no path and it ends with
'.csv' instead of '.zip'.
The contents file in the file archive conform to the same
format as a file read directly from disk, described next.
The following assumptions are made about the contents of the actual
data file, whether read from a zip file or directly from a regular
file:
It is a text file.
It has a header line with column names.
It is a csv file/
All lines have the same number of columns, including the header
line.
The name of a Python Pickle file containing the following information
about the original data file:
The number of lines in the original data file.
The number of comma separated columns in the header line of the
original data file. It is assumed that all other lines in the file
also have that number of columns.
The number of rows to extract.
The specific rows to extract are chosen at random from the original
file. The first row is not included, nor are any rows in the
validation set.
The number of columns to extract.
The specific columns to extract are chosen at random.
The case number column ordinal.
To exclude from the selection of data columns for a data set, but to
be written to each training set in addition to the selected data
columns. This is the column whose value corresponds to each patient.
The output column ordinal.
To exclude from the selection of data columns for a data set, but to
be written to each training set in addition to the selected data
columns. This is the outcome column whose value is to be predicted
by the algorithm defined by the machine learning processing of the
training sets generated here.
The number of training sets to create.
The starting set number. Optional.
If not present the default value is 1.
Needed to create unique output file names when this script is run
more than once for an original data file, to create more training and
validation sets than the max number of open files allowed.
The file name of a file containing an optional set of columns to restrict
the selection to. Optional.
If not present all columns are available to select from, except the
case number column and output column.
If present only the specified columns are available to select from.
These must not include the case number column or output column.
This is for a second set of training/validation runs to determine
which subset of the important columns, identified by the first
training/validation runs, are most useful.
This file has 2 numbers per line:
A column ordinal.
A value indicating the predictive power ranking of that column.
The columns should appear in descending order by this ranking.
The column with the highest ranking should appear first, etc.
However, this is not checked by this script.
Outputs:
An output file for each training set.
A validation set file for each training set file.
A training set file will not contain any of the original data file
lines as its corresponding validation set file.
"""
import sys
import argparse
import os
import pickle
import random
from contextlib import contextmanager
import zipfile
import time
class SelectionSet:
"""
A base class for data sets to be selected from an original data file.
Each subclass should have the following members:
row_ordinals: A Python set object that has the row ordinals of the rows
(lines) of the original file to be written for this set.
column_ordinals: A list of the randomly selected columns to write from
a line of the original file. It does not include the
case number column or the output column.
output_columns: A list of the columns to write from a line of the
original file. It is the output_ordinal columns plus
the case number and output columns. The case number is
the first column, the output column is the second
column followed by the column_ordinals. The
column_ordinals are sorted in ascending order when
appended to output_columns, so they are in the same
order as in the original file.
set_file: An open file object to write the selected data to.
"""
def __init__(self):
self.row_ordinals = set()
self.column_ordinals = None
self.output_columns = None
self.set_file = None
def define_output_columns(self, args):
"""
For writing the selected columns in the same order as they are in the
original file. Also, to optionally include the case number and
output columns in the output, as the first and second columns.
When creating training sets, both the training set and its associated
validation set will shave the case number and output as the first two
columns of the set file. These are optional for generic sets.
"""
column_ordinals_sorted = list(self.column_ordinals)
column_ordinals_sorted.sort()
self.output_columns = []
# This is included even if it is None. In that case it is to indicate
# writing the row ordinal instead. This is for generic sets, for which
# the case number is optional.
self.output_columns.append(args.case_column)
if args.outcome_column is not None:
self.output_columns.append(args.outcome_column)
self.output_columns += column_ordinals_sorted
def get_random_ordinals(self, ordinals, count):
"""
Get a set of count random elements from ordinals.
ordinals are a list of data line ordinals from the original file.
count should be an integer.
"""
ordinal_sample = set(random.sample(ordinals, count))
return ordinal_sample
def get_random_ordinals_exclude(self, count, start, end, exclude):
"""
Get a set of count random integers between start and end, inclusive,
but not including any integers in the exclude.
This is without replacement, so a random integer should also not
already be in the result set. This is enforced by the set data type
which does not have duplciates. The set add function doesn't change
the set if it already has the element being added.
count, start and end should be integers.
start should be < end
count should be < (end - start + 1)
exclude should be a set of integers. It may be empty.
"""
ordinals = set()
while len(ordinals) < count:
r = random.randint(start, end)
if not r in exclude:
ordinals.add(r)
return ordinals
def write_ordinals(self, ordinals, file_name):
"""
Write a set of ordinals to a file, in ascending numerical order.
These are typically needed by subsequent machine learning steps, not part
of the data set selection process.
"""
sorted_ordinals = sorted(ordinals)
with open(file_name, 'w', encoding='utf_8') as ordinal_file:
for o in sorted_ordinals:
ordinal_file.write(str(o) + '\n')
def check_line(self, ordinal, fields):
"""
Check a line from the original file, to see if fields from it should be
written for this training set.
output_columns is sorted in ascending order by column ordinal, so the
columns will be written in the same order they are in the original
file, except for the case number column and output column, which if
present are always the first two columns.
"""
if ordinal in self.row_ordinals:
# This line is for this selection set.
fields_to_write = []
for i, o in enumerate(self.output_columns):
if i == 0 and self.output_columns[i] is None:
# This is for a generic set that is not including the case
# column. Write the row ordinal instead.
fields_to_write.append(str(ordinal))
else:
# Write a data column.
# Because we count column ordinals from 1, but list indices
# start at 0.
o1 = o - 1
fields_to_write.append(fields[o1])
# Write the fields to the training set file.
field_str = ','.join(fields_to_write) + '\n'
self.set_file.write(field_str)
# pylint: disable=too-many-instance-attributes
class ValidationSet(SelectionSet):
"""
A class to represent the information for a validation set to be created.
Each validation set has an output file name, output file object and a set
of row ordinals for the lines of the original file for this validation set
and a set of column ordinals for the columns of the original file for this
validation set.
"""
# The subset of row ordinals from the original data file to use for
# sampling when creating a validation set.
available_ordinals = None
# pylint: disable=too-many-arguments
def __init__(self, file_ordinal, original_column_count, args, row_count,
column_set, prefix='validation-set-'):
if ValidationSet.available_ordinals is None:
msg = 'ValidationSet: available_ordinals has not been defined'
raise ValueError(msg)
SelectionSet.__init__(self)
# Define these file items as None so the cleanup function can be
# called to cleanup up any open or created files if a file exception
# occurs part was through the constructor.
self.row_ordinal_file_name = None
self.column_ordinal_file_name = None
self.set_file = None
# Used for output file names and error mesages.
# This is the same ordinal as the associated training set.
self.file_ordinal = file_ordinal
self.row_ordinals = self.get_random_ordinals(
ValidationSet.available_ordinals,
row_count)
# Determine the columns to use for this validation set. If a column set
# was provided, use it. Otherwise use a random set of columns.
self.column_ordinals = None
self.output_columns = None
if column_set is not None:
self.column_ordinals = column_set
self.define_output_columns(args)
else:
exclude_cols = set([args.case_column, args.outcome_column])
self.column_ordinals = self.get_random_ordinals_exclude(
args.column_count, 1,
original_column_count, exclude_cols)
self.define_output_columns(args)
self.file_name = f'{prefix}{self.file_ordinal}.csv'
f = f'{prefix}{self.file_ordinal}-row-ordinals'
self.row_ordinal_file_name = f
try:
self.write_ordinals(self.row_ordinals, self.row_ordinal_file_name)
except OSError as e:
self.cleanup()
raise e
f = f'{prefix}{self.file_ordinal}-column-ordinals'
self.column_ordinal_file_name = f
if self.column_ordinals is not None:
try:
self.write_ordinals(self.column_ordinals,
self.column_ordinal_file_name)
except OSError as e:
self.cleanup()
raise e
# pylint: disable=consider-using-with
try:
self.set_file = open(self.file_name, 'w', encoding='utf_8')
except OSError as e:
self.cleanup()
raise e
def cleanup(self):
"""
Cleanup any files created by this ValidationSet.
Called when the constructor detects a file error creating one of
these files or when the owning TrainingSet contruction failed, in
either case typically due to a file open failure because of too many
open files.
"""
if (self.row_ordinal_file_name is not None and
os.access(self.row_ordinal_file_name, os.R_OK)):
os.remove(self.row_ordinal_file_name)
if (self.column_ordinal_file_name is not None and
os.access(self.column_ordinal_file_name, os.R_OK)):
os.remove(self.column_ordinal_file_name)
if self.set_file is not None:
if not self.set_file.closed:
self.set_file.close()
if os.access(self.file_name, os.R_OK):
os.remove(self.file_name)
def close(self):
"""
Close the selection set file.
To be called once the selection set has been fully processed.
"""
self.set_file.close()
# pylint: disable=too-many-instance-attributes
class TrainingSet(SelectionSet):
"""
A class to represent the information for a training set to be created.
Each training set has an output file name, output file object and a set of
row ordinals for the lines of the original file for this training set and
a set of column ordinals for the columns of the original file for this
training set.
Each training set has its own validation set. The training set
will not choose row ordinals that are in any validation set, its own
validation set or the validation set for another training set,
since the training set row ordinals are sampled from a distinct subset
of the original file row ordinals than the validation sets are sampled
from.
The training set and and its validation set will both use the same columns
from the original file.
"""
# The subset of row ordinals from the original data file to use for
# sampling when creating a training set.
available_ordinals = None
def __init__(self, file_ordinal, original_column_count, args, column_set):
if TrainingSet.available_ordinals is None:
msg = 'TrainingSet: available_ordinals has not been defined'
raise ValueError(msg)
SelectionSet.__init__(self)
# Define these file items as None so the cleanup function can be
# called to cleanup up any open or created files if a file exception
# occurs part was through the constructor.
self.row_ordinal_file_name = None
self.set_file = None
# Used for output file names and error mesages.
self.file_ordinal = file_ordinal
self.validation_set = ValidationSet(self.file_ordinal,
original_column_count, args,
args.validation_row_count,
column_set)
# The training set uses the same columns as the validation set.
self.column_ordinals = self.validation_set.column_ordinals
self.row_ordinals = self.get_random_ordinals(
TrainingSet.available_ordinals,
args.training_row_count)
self.define_output_columns(args)
self.file_name = f'training-set-{file_ordinal}.csv'
f = f'training-set-{file_ordinal}-row-ordinals'
self.row_ordinal_file_name = f
try:
self.write_ordinals(self.row_ordinals, self.row_ordinal_file_name)
except OSError as e:
self.cleanup()
raise e
# pylint: disable=consider-using-with
try:
self.set_file = open(self.file_name, 'w', encoding='utf_8')
except OSError as e:
self.cleanup()
raise e
def cleanup(self):
"""
Cleanup any files created by this TrainingSet, including any by its
associated ValidationSet.
Called when the TrainingSet contruction failed, typically due to
a file open failure because of too many open files.
"""
if (self.row_ordinal_file_name is not None and
os.access(self.row_ordinal_file_name, os.R_OK)):
os.remove(self.row_ordinal_file_name)
if self.set_file is not None:
if not self.set_file.closed:
self.set_file.close()
if os.access(self.file_name, os.R_OK):
os.remove(self.file_name)
self.validation_set.cleanup()
def check_line(self, ordinal, fields):
"""
If doing a validation set for each training set, then check this
training set's validation set if it should write the line.
In either case check this training set if it should write the line.
"""
if self.validation_set is not None:
self.validation_set.check_line(ordinal, fields)
super().check_line(ordinal, fields)
def close(self):
"""
Close the selection set file, for this TraininSet and its
ValidaitonSet.
To be called once the selection set has been fully processed.
"""
self.set_file.close()
self.validation_set.close()
def define_and_get_args(args=None):
"""
Define and get the command line options.
"""
parser = argparse.ArgumentParser()
msg = 'The file name of the original data set'
parser.add_argument('-i', '--original-file', dest='original_file_name',
help=msg, type=str, default=None, required=True)
msg = 'The file name of the Pickle file with the original data file'
msg += ' information.'
parser.add_argument('--odfi', '--original-data-file-info',
dest='original_data_file_info', help=msg, type=str,
default=None, required=True)
msg = 'The number of sets to create, training or generic'
parser.add_argument('--sc', '--set-count', dest='set_count', help=msg,
type=int, required=True)
msg = 'The number of rows to extract for each generic set.'
parser.add_argument('--grc', '--generic-row-count',
dest='generic_row_count', help=msg,
type=int, required=False)
msg = 'The percentage of original file records to use'
msg += ' for sampling training sets. The remaining record to use for'
msg += ' sampling validation sets.'
parser.add_argument('--tp', '--training-percent', dest='training_percent',
help=msg, type=float, required=False)
msg = 'The number of rows to extract for each training set.'
parser.add_argument('--trc', '--training-row-count',
dest='training_row_count', help=msg, type=int,
required=False)
msg = 'The number of rows to extract for each validation set.'
parser.add_argument('--vrc', '--validation-row-count',
dest='validation_row_count', help=msg, type=int,
required=False)
msg = 'The file name of a file with a resticted set of column ordinals'
msg += ' to use'
parser.add_argument('--cs', '--column-set', dest='column_set_file_name',
help=msg, type=str, required=False)
msg = 'The starting number of columns to use from the column set file.'
parser.add_argument('--css', '--column-set-start', dest='column_set_start',
help=msg, type=int, required=False)
msg = 'The number of columns to extract for each validation'
msg += ' and training set or for each generic set.'
parser.add_argument('--cc', '--column-count', dest='column_count',
help=msg, type=int, required=True)
msg = 'The case number column ordinal'
parser.add_argument('--cn', '--case-column', dest='case_column',
help=msg, type=int, required=False)
msg = 'The outcome column ordinal'
parser.add_argument('--oc', '--outcome-column', dest='outcome_column',
help=msg, type=int, required=False)
msg = 'The delimiter of the original file'
parser.add_argument('--del', '--delimiter', dest='delimiter', help=msg,
type=str, default=',', required=False)
args = parser.parse_args()
return args
def check_file_args(args, args_ok):
"""
Check the program arguments that are input file names.
These are needed whether we are creating training/validation sets or
creating generic sets.
"""
if not os.path.isfile(args.original_file_name):
msg = '\nOriginal data set file "{0}" does not exist.\n'
msg = msg.format(args.original_file_name)
print(msg)
args_ok = False
if not os.path.isfile(args.original_data_file_info):
msg = '\nThe orginal data file infoi file "{0}" does not exist.\n'
msg = msg.format(args.original_data_file_info)
print(msg)
args_ok = False
return args_ok
def check_unallowed_arg(set_type, arg_val, arg_name, args_ok):
"""
Check an argument for being specified when it shouldn't be.
set_type is the type of sets being created, ex. generic or
training/validation. For error messages.
arg_val is the argument value. If not None it is considered specified.
Note that this won't work if an argument has a default value.
arg_name is the name of the argument, for error messages.
args_ok is the current argument check state. This is set to False if
the argument was specified.
"""
if arg_val is not None:
msg = 'Creating {} sample sets was specified but {} was'
msg += ' specified with value {}.'
print(msg.format(set_type, arg_name, arg_val))
args_ok = False
return args_ok
def check_required_arg(set_type, arg_val, arg_name, args_ok):
"""
Check an argument for being not specified when it should be.
set_type is the type of sets being created, ex. generic or
training/validation. For error messages.
arg_val is the argument value. If None it is considered unspecified.
Note that this won't work if an argument has a default value.
arg_name is the name of the argument, for error messages.
args_ok is the current argument check state. This is set to False if
the argument was not specified.
"""
if arg_val is None:
msg = 'Creating {} sample sets was specified but {} was'
msg += ' not specified.'
print(msg.format(set_type, arg_name, arg_val))
args_ok = False
return args_ok
def check_generic_args(args, args_ok):
"""
Creating generic sets is mutually exclusive with creating
training/validation sets.
"""
args_ok = check_required_arg('generic', args.generic_row_count,
'generic_row_count', args_ok)
if args.generic_row_count is not None and args.generic_row_count < 1:
msg = 'The generic row count, {0}, is less than 1.'
msg = msg.format(args.generic_row_count)
print(msg)
args_ok = False
args_ok = check_unallowed_arg('generic', args.training_percent,
'training_percent', args_ok)
args_ok = check_unallowed_arg('generic', args.training_row_count,
'training_row_count', args_ok)
args_ok = check_unallowed_arg('generic', args.validation_row_count,
'validation_row_count', args_ok)
args_ok = check_unallowed_arg('generic', args.column_set_file_name,
'column_set_file_name', args_ok)
args_ok = check_unallowed_arg('generic', args.column_set_start,
'column_set_start', args_ok)
return args_ok
def check_training_args(args, args_ok):
"""
Creating training/validation sets is mutually exclusive with creating
generic sets.
"""
args_ok = check_required_arg('training/validation', args.training_percent,
'training_percent', args_ok)
if (args.training_percent is not None and
(args.training_percent <= 0.0 or args.training_percent >= 1.0)):
msg = 'Training percent should between 0 and 1, exclusive, i.e. (0,1).\n'
print(msg)
args_ok = False
args_ok = check_required_arg('training/validation', args.training_row_count,
'training_row_count', args_ok)
if args.training_row_count is not None and args.training_row_count < 1:
msg = 'The training row count, {0}, is less than 1.'
msg = msg.format(args.training_row_count)
print(msg)
args_ok = False
args_ok = check_required_arg('training/validation', args.validation_row_count,
'validation_row_count', args_ok)
if args.validation_row_count is not None and args.validation_row_count < 1:
msg = 'The validation row count, {0}, is less than 1.'
msg = msg.format(args.validation_row_count)
print(msg)
args_ok = False
if args.column_set_file_name is not None and \
not os.path.isfile(args.column_set_file_name):
msg = '\nColumn set file "{0}" does not exist.\n'
msg = msg.format(args.column_set_file_name)
print(msg)
args_ok = False
# The case column and output column are requried for training and
# validation sets but are optional for generic sets. So their values
# are checked later.
args_ok = check_required_arg('training/validation', args.case_column,
'case_column', args_ok)
args_ok = check_required_arg('training/validation', args.outcome_column,
'outcome_column', args_ok)
# The column set file and column set start are optional for training and
# validation sets. If one of those is specified the other must also be
# specified.
if args.column_set_file_name is not None:
if args.column_set_start is None:
msg = 'A column set file was specified, {},'
msg += ' but no column set start was specified'
msg = msg.format(args.column_set_file_name)
print(msg)
args_ok = False
if not os.path.isfile(args.column_set_file_name):
msg = '\nColumn set file "{0}" does not exist.\n'
msg = msg.format(args.column_set_file_name)
print(msg)
args_ok = False
if args.column_set_start is not None:
if args.column_set_file_name is None:
msg = 'A column set start was specified, {},'
msg += ' but no column set file was specified'
msg = msg.format(args.column_set_start)
print(msg)
args_ok = False
if args.column_set_start < 1:
msg = 'The column set start, {}, is less than 1.'
msg = msg.format(args.column_set_start)
print(msg)
args_ok = False
args_ok = check_unallowed_arg('training/validation', args.generic_row_count,
'generic_row_count', args_ok)
return args_ok
def check_args(args):
"""
Perform validity checks on the command line arguments.
"""
args_ok = True
args_ok = check_file_args(args, args_ok)
if args.set_count < 1:
msg = 'The set count, {0}, is less than 1.'
msg = msg.format(args.set_count)
print(msg)
args_ok = False
if args.generic_row_count is not None:
args_ok = check_generic_args(args, args_ok)
else:
args_ok = check_training_args(args, args_ok)
if args.column_count < 1:
msg = 'The column count, {0}, is less than 1.'
msg = msg.format(args.column_count)
print(msg)
args_ok = False
if args.case_column is not None and args.case_column < 1:
msg = 'The case number column ordinal, {0}, is less than 1.'
msg = msg.format(args.case_column)
print(msg)
args_ok = False
if args.outcome_column is not None and args.outcome_column < 1:
msg = 'The outcome column ordinal, {0}, is less than 1.'
msg = msg.format(args.outcome_column)
print(msg)
args_ok = False
if (args.case_column is not None and args.outcome_column is not None and
args.case_column == args.outcome_column):
msg = 'The case number column ordinal and outcome column are the'
msg += ' same, {0}'
msg = msg.format(args.case_column)
print(msg)
args_ok = False
if not args_ok:
sys.exit(1)
return args
def define_and_check_args(args=None):
"""
Define, get and check the command line options.
"""
args = define_and_get_args(args)
check_args(args)
return args
def print_args(args):
"""
For testing and debugging.
"""
print(f'args.original_file_name: {args.original_file_name}')
msg = 'args.original_data_file_info: {0}'
print(msg.format(args.original_data_file_info))
print(f'args.set_count: {args.set_count}')
if args.set_count is not None:
# Print the generic set specific arguments.
print(f'args.generic_row_count: {args.generic_row_count}')
else:
# Print the training/validation set specific arguments.
print(f'args.training_percent: {args.training_percent}')
print(f'args.training_row_count: {args.training_row_count}')
msg = 'args.validation_row_count: {0}'
print(msg.format(args.validation_row_count))
print(f'args.column_set_file_name: {args.column_set_file_name}')
print(f'args.column_set_start: {args.column_set_start}')
print(f'args.column_count: {args.column_count}')
print(f'args.case_column: {args.case_column}')
print(f'args.outcome_column: {args.outcome_column}')
print(f'args.delimiter: {args.delimiter}')
print('')
def check_args_additional(original_column_count, args):
"""
Perform argument checks that require information read from the pickle file
of original file info.
"""
args_ok = True
if (args.case_column is not None and
args.case_column > original_column_count):
msg = 'The case number column ordinal, {0}, is greater than the number'
msg += ' of columns in the original file, {1}.'
msg = msg.format(args.case_column, original_column_count)
print(msg)
args_ok = False
if (args.outcome_column is not None and
args.outcome_column > original_column_count):
msg = 'The output column ordinal, {0}, is greater than the number'
msg += ' of columns in the original file, {1}.'
msg = msg.format(args.outcome_column, original_column_count)
print(msg)
args_ok = False
if not args_ok:
sys.exit(1)
# pylint:disable=too-many-statements
def get_column_set(original_column_count, args):
"""
Get a restricted set of columns to use from a specified file.
The file has one line per column, with 2 values:
A column ordinal.
A value indicating the predictive power ranking of that column.
The columns should appear in descending order by this ranking.
The column with the highest ranking should appear first, etc.
However, this is not checked by this script.
Only the requested number of columns to use (args.column_count) are read.
"""
column_set = []
previous_priority = float('inf')
with open(args.column_set_file_name, 'r', encoding='utf_8') as input_file:
ordinal_base = 1
for (ordinal, line) in enumerate(input_file, ordinal_base):
if ordinal > args.column_count:
break
# Delete trailing newline so it isn't treated as part of the values
# read.
fields = line.rstrip('\n').split(',')
if len(fields) > 2:
msg = 'Line {} of column set file {} has {} fields.'
msg += ' Only 2 are expected.'
msg = msg.format(ordinal, args.column_set_file_name, len(fields))
print(msg)
sys.exit(1)
try:
column = int(fields[0])
except ValueError:
msg = 'Column "{0}" from line {1} of file {2} is not an'
msg += ' integer.'
msg = msg.format(fields[0], ordinal, args.column_set_file_name)
print(msg)
sys.exit(1)
try:
priority = float(fields[1])
except ValueError:
msg = 'Priority "{0}" from line {1} of file {2} is not a float.'
msg = msg.format(fields[1], ordinal, args.column_set_file_name)
print(msg)
sys.exit(1)
if column < 1 or column > original_column_count:
msg = 'Column "{0}" from line {1} of file {2} is out of range.'
msg += ' It must be between 1 and {3}.'
msg = msg.format(fields[0], ordinal, args.column_set_file_name, \
original_column_count)
print(msg)
sys.exit(1)
if column == args.case_column:
msg = 'Column "{0}" from line {1} of file {2} is the same as'
msg += ' the case column {3}.'
msg = msg.format(fields[0], ordinal, args.column_set_file_name, \
args.case_column)
print(msg)
sys.exit(1)
if column == args.outcome_column:
msg = 'Column "{0}" from line {1} of file {2} is the same'
msg += ' as the output column {3}.'
msg = msg.format(fields[0], ordinal, args.column_set_file_name, \
args.outcome_column)
print(msg)
sys.exit(1)
if priority > previous_priority:
msg = 'Priority {} from line {} of column set file {}'
msg += ' is > the priority of {} from the previous line.'
msg = msg.format(priority, ordinal, args.column_set_file_name,
previous_priority)
print(msg)
sys.exit(1)
if column in column_set:
msg = 'Column "{0}" from line {1}'
msg += ' already appeared in file {2}.'
msg = msg.format(fields[0], ordinal, args.column_set_file_name)
print(msg)
sys.exit(1)
column_set.append(column)
previous_priority = priority
return column_set
def define_available_ordinals(original_line_count, args):
"""
Define two disjoint sets of line ordinals from the original file to be
used for sampling to create the training sets and validation sets.
The ordinals for the data lines are shuffled, the first training_percent
are chosen for sampling to create the training sets, and the remaining
data ordinals used for sampling to create the validation sets.
"""