-
Notifications
You must be signed in to change notification settings - Fork 1
/
csv2arff.pl
executable file
·1258 lines (1137 loc) · 41.3 KB
/
csv2arff.pl
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/perl -s
#*************************************************************************
#
# Program: csv2arff
# File: csv2arff.pl
#
# Version: V1.7
# Date: 12.04.21
# Function: Convert CSV file to ARFF format
#
# Copyright: (c) Prof. Andrew C. R. Martin, UCL, 2012-2021
# Author: Prof. Andrew C. R. Martin
# Address: Institute of Structural and Molecular Biology
# Division of Biosciences
# University College
# Gower Street
# London
# WC1E 6BT
# EMail: andrew@bioinf.org.uk
#
#*************************************************************************
#
# This program is not in the public domain, but it may be copied
# according to the conditions laid out in the accompanying file
# COPYING.DOC
#
# The code may be modified as required, but any modifications must be
# documented so that the person responsible can be identified. If
# someone else breaks this code, I don't want to be blamed for code
# that does not work!
#
# The code may not be sold commercially or included as part of a
# commercial product except as described in the file COPYING.DOC.
#
#*************************************************************************
#
# Description:
# ============
#
#*************************************************************************
#
# Usage:
# ======
# Converts a CSV file to ARFF format
#
#*************************************************************************
#
# Revision History:
# =================
# V1.0 26.06.12 Original
# V1.1 29.10.12 Added -write=file, -norm=file and -relax
# -write=file saves the ranges used for normalization
# with -norm in a file
# -norm=file reads the ranges from the file instead
# of working them out from the data
# -relax allows normalized values outside 0...1
# when the actual data are outside the
# range specified in a file read with
# -norm=file
# V1.2 29.11.12 Added -id=field, -idfile=file, -iddiscard=file By: NSAN
# -id=field name of field to be used as id
# with -norm in a file
# -idfile=file used with -id to save records with IDs in
# another ARFF file
# -iddiscard=file used with -id to save discarded IDs
# V1.3 19.11.13 Added -minus and reads DOS files properly
# V1.3.1 04.02.14 Improved usage message
# V1.4 05.10.15 Added -skip to skip records with missing valued
# - the default is now to substitute a ? for missing
# values
# V1.5 15.10.19 Added -over to allow oversampling
# V1.6 16.10.19 Fixed problem with generating headers with -skip
# Fixed output on oversampling
# V1.7 12.04.21 Input file reader removes return characters for
# reading Windows files
#
#*************************************************************************
use strict;
my $input = "";
# Check for -h - help request
UsageDie() if(defined($::h));
# Check for user-specified dataset title
$::title = "CSV_data" if(!defined($::title));
# If we have -inputs=a,b,c on the command line, get inputs from there
# otherwise get the filename that lists the inputs and obtain from there
if(defined($::inputs))
{
@::inputFields = split(/,/, $::inputs);
}
else
{
$input = shift(@ARGV);
@::inputFields = ReadInputFields($input);
}
# 09.01.13 Added error checks By: ACRM
if(!defined($::id) && (defined($::idfile) || defined($::iddiscard)))
{
print STDERR "Error (csv2arff): You must specify -id to use -idfile or -iddiscard\n";
exit 1;
}
if(!defined($::limit) && (defined($::discard) || defined($::iddiscard)))
{
print STDERR "Error (csv2arff): You must specify -limit to use -discard or -iddiscard\n";
exit 1;
}
# 15.10.19 Added error check By: ACRM
if(!defined($::limit) && (defined($::over)))
{
print STDERR "Error (csv2arff): You must specify -limit to use -over\n";
exit 1;
}
# 29.11.12 If we have -id and -idfile, then open the idfile file to By: NSAN
if(defined($::id) && defined($::idfile))
{
if(!open(IDFILE, ">$::idfile"))
{
print STDERR "Error (csv2arff): Unable to open discard file for writing: $::idfile\n";
exit 1;
}
}
# 29.11.12 -id and -iddiscard added
# If we have -limit and -discard (-id and -idfile),
# then open the discard file to store records rejected by -limit By: NSAN
if(defined($::limit) && defined($::discard))
{
if(!open(DISCARDFILE, ">$::discard"))
{
print STDERR "Error (csv2arff): Unable to open discard file for writing: $::discard\n";
exit 1;
}
if(defined($::id) && defined($::iddiscard))
{
if(!open(IDDISCARDFILE, ">$::iddiscard"))
{
print STDERR "Error (csv2arff): Unable to open ID discard file for writing: $::iddiscard\n";
exit 1;
}
}
}
# Set up the output normalized range (for use with -norm)
my $outMinVal = 0;
my $outMaxVal = 1;
if(defined($::minus))
{
$outMinVal = -1;
$outMaxVal = 1;
}
# Get the output field from the command line
my $output = shift(@ARGV);
# Read the data
my ($ndata, %data) = ReadCSV();
# Identify redundant attributes (if -auto defined)
%::redundantFields = FindRedundantFields($ndata, %data);
# Normalize data (if -norm defined)
NormalizeData($ndata, $output, $outMinVal, $outMaxVal, %data);
# Limit the maximum count of any output class (if -limit defined)
@::rejectRecords = LimitData($ndata, $output, $::limit, %data);
# If -limit and -over
@::overSample = OversampleData($ndata, $output, $::limit, %data, $::over);
# Create array of allowed output classes changing * to _other_
@::allowedClasses = (defined($::class))?split(/\,/,$::class):();
foreach my $ac (@::allowedClasses){$ac = "_other_" if ($ac eq "*");}
# Write the results
WriteARFF($output, $ndata, $::title, %data);
WriteOverSampledARFF($output, $ndata, $::title, %data);
# 29.11.12 Close the idfile file if we have one By: NSAN
if(defined($::id) && defined($::idfile))
{
close IDFILE;
}
# 29.11.12 Close the discard file if we have one By: NSAN
if(defined($::limit) && defined($::discard))
{
close DISCARDFILE;
if(defined($::id) && defined($::iddiscard))
{
close IDDISCARDFILE;
}
}
#*************************************************************************
# 29.10.12 Original By: ACRM
sub ReadNormRanges
{
my ($file) = @_;
my %ranges = ();
if(open(RANGEFILE, $file))
{
while(<RANGEFILE>)
{
chomp;
my ($attribute, $minVal, $maxVal) = split;
$ranges{$attribute}[0] = $minVal;
$ranges{$attribute}[1] = $maxVal;
}
close RANGEFILE;
}
else
{
print STDERR "Error (csv2arff): Unable to read normalization file: '$file'\n";
exit 1;
}
return(%ranges);
}
#*************************************************************************
# 26.06.12 Original By: ACRM
# 29.10.12 Added code to read ranges from a file
# 19.11.13 Added code to allow output range to be specified
sub NormalizeData
{
my($ndata, $output, $outMinVal, $outMaxVal, %data) = @_;
my %ranges = ();
if(defined($::norm))
{
print STDERR "Normalizing data..." if(defined($::v));
# If -norm has been called with a filename, read the ranges
# from this file
if($::norm ne 1)
{
# Check that -write hasn't also been specified
if(defined($::write))
{
UsageDie();
}
%ranges = ReadNormRanges($::norm);
}
else # We are calculating ranges, see if we need to write them
{
if(defined($::write))
{
if(!open(RANGEFILE, ">$::write"))
{
print STDERR "Error (csv2arff): Can't open file specified with -write for writing: $::write\n";
exit 1;
}
}
}
# Step through the attribues checking if they are ones that we
# say are of interest
foreach my $attrib (keys %data)
{
if(inArray($attrib, @::inputFields))
{
my ($minVal, $maxVal);
my $nan;
if($::norm == 1)
{
# Now go through all the values finding a minimum and max
# If we find something that isn't a number then jump out
$minVal = $data{$attrib}[0];
$maxVal = $data{$attrib}[0];
$nan = 0;
for(my $i=0; $i<$ndata; $i++)
{
my $value = $data{$attrib}[$i];
if(!IsValidNumber($value) && ($value ne ""))
{
$nan = 1;
last;
}
if($value < $minVal)
{
$minVal = $value;
}
elsif($value > $maxVal)
{
$maxVal = $value;
}
}
if(defined($::write))
{
print RANGEFILE "$attrib $minVal $maxVal\n";
}
}
else
{
# Get the min and max values as defined in a file
# If either min or max is invalid or the range is
# zero, then set the not-a-number flag
if(defined($ranges{$attrib}[0]))
{
$minVal = $ranges{$attrib}[0];
$maxVal = $ranges{$attrib}[1];
if((!IsValidNumber($minVal) && ($minVal ne "")) ||
(!IsValidNumber($maxVal) && ($maxVal ne "")) ||
($minVal == $maxVal))
{
$nan = 1;
}
}
else
{
$nan = 1;
}
}
# If we only had valid numbers, then normalize to range 0-1
if(!$nan)
{
my $range = $maxVal - $minVal;
my $outRange = $outMaxVal - $outMinVal;
for(my $i=0; $i<$ndata; $i++)
{
my $value = $data{$attrib}[$i];
if($value ne "")
{
if($range > 0)
{
# Out = outMin + (outRange * ((in - inMin)/inRange))
my $newval = $outMinVal + ($outRange * ($value - $minVal) / $range);
# When ranges have been read from a file,
# the normalized number might be outside
# the 0...1 range. Unless -relax is
# specified, this forces the range to
# be 0...1
if(!defined($::relax))
{
if($newval > $outMaxVal)
{
$newval = $outMaxVal;
}
elsif($newval < $outMinVal)
{
$newval = $outMinVal;
}
}
$data{$attrib}[$i] = $newval;
}
}
}
}
}
}
if(defined($::write))
{
close RANGEFILE;
}
print STDERR "done\n" if(defined($::v));
}
}
#*************************************************************************
sub LimitData
{
my($ndata, $output, $limit, %data) = @_;
my @reject = ();
if(defined($::limit))
{
print STDERR "Limiting dataset size..." if(defined($::v));
my %classCounts = ();
# Count how many of each output class there is
for(my $i=0; $i<$ndata; $i++)
{
my $class = $data{$output}[$i];
if(defined($classCounts{$class}))
{
$classCounts{$class}++;
}
else
{
$classCounts{$class}=1;
}
}
# Start off assuming we reject everything
for (my $i=0; $i<$ndata; $i++)
{
$reject[$i] = 1;
}
# Step through the data, randomly marking for keeping if this
# class has too many items, or definitely for keeping if there
# aren't enough.
my %kept = ();
foreach my $class (keys %classCounts)
{
# Initialize counter of how many examples have been kept
if(!defined($kept{$class}))
{
$kept{$class} = 0;
}
# While we haven't got enough examples in this class
while(($kept{$class} < $::limit) &&
($kept{$class} <= $classCounts{$class}))
{
# Run though the data looking for examples of this class
for(my $i=0; $i<$ndata; $i++)
{
# See if it's the class of interest
my $thisClass = $data{$output}[$i];
if($thisClass eq $class)
{
# If we have too many of this class...
my $count = $classCounts{$thisClass};
if($count > $::limit)
{
# If it's currently marked for rejection
if($reject[$i])
{
# Based on random number we can choose to keep it
my $rnum = Random($count);
if($rnum < $limit)
{
$reject[$i] = 0;
# Update the number kept - if it's now enough
# jump out of the loop
$kept{$class}++;
if($kept{$class} >= $::limit)
{
last;
}
}
}
}
else # Not enough of this class so keep automatically
{
$reject[$i] = 0;
$kept{$class}++;
}
}
}
}
}
print STDERR "done\n" if(defined($::v));
}
return(@reject);
}
#*************************************************************************
sub Random
{
my($limit) = @_;
return(int(rand($limit)));
}
#*************************************************************************
sub FindRedundantFields
{
my($ndata, %data) = @_;
my %redundantFields = ();
my $nRedundant = 0;
if(defined($::auto))
{
print STDERR "Finding redundant attributes..." if(defined($::v));
# Step through the attribues checking if they are ones that we
# say are of interest
foreach my $attrib (keys %data)
{
if(inArray($attrib, @::inputFields))
{
# Now check if it's redundant - i.e. all values are the
# same
# Store them in a hash
my %values = ();
for(my $i=0; $i<$ndata; $i++)
{
$values{$data{$attrib}[$i]} = 1;
}
# If the hash has only one key then the column is redundant
if(int(keys %values) == 1)
{
$redundantFields{$attrib} = 1;
$nRedundant++;
}
}
}
print STDERR "done\n" if(defined($::v));
if($nRedundant)
{
if($nRedundant > 1)
{
print STDERR "The following redundant attributes were discarded:\n";
}
else
{
print STDERR "The following redundant attribute was discarded:\n";
}
foreach my $attrib (keys %redundantFields)
{
print STDERR " $attrib\n";
}
}
}
return(%redundantFields);
}
#*************************************************************************
# 29.11.12 Call to PrintLineId() added By: NSAN
sub WriteARFF
{
my ($output, $nData, $title, %data) = @_;
my @attributes = ();
my @isBoolean = ();
if(!inArray($output, (keys %data)))
{
print STDERR "Error (csv2arff): Specified output field ($output) does not exist\n";
exit 1;
}
print STDERR "Writing ARFF file..." if(defined($::v));
# First write the ARFF header
$title =~ s/\s/\_/g;
PrintLine(3, "\@relation $title\n\n");
# Print valid input attributes
foreach my $key (sort keys %data)
{
if(inArray($key, @::inputFields) && !defined($::redundantFields{$key}))
{
# Determine input attribute type
my ($attribType, $boolean) = FindAttribType(0, @{$data{$key}});
PrintLine(3, "\@attribute $key $attribType\n");
push @attributes, $key;
push @isBoolean, $boolean;
}
}
# Determine output attribute type
my ($attribType, $boolean) = FindAttribType(1, @{$data{$output}});
PrintLine(3, "\@attribute $output $attribType\n\n");
my $outIsBoolean = $boolean;
# Now write the actual data
PrintLine(3, "\@data\n");
for(my $i=0; $i<$nData; $i++)
{
my $outputString = "";
my $valid = 1;
# Input attributes
my $attribCount = 0;
foreach my $attrib (@attributes)
{
my $datum = $data{$attrib}[$i];
if(($datum eq "")||($datum eq '?')) # Check the line is complete
{
if(defined($::skip))
{
$valid = 0;
last;
}
else
{
$datum = '?';
}
}
else
{ # Convert to Boolean if needed
if(!defined($::ni) && $isBoolean[$attribCount])
{
$datum = (($datum == 1)?"TRUE":"FALSE");
}
}
# Append to the output string
$outputString .= $datum . ",";
$attribCount++;
}
# Output value
my $datum = $data{$output}[$i];
if(int(@::allowedClasses))
{
if(!inArray($datum, @::allowedClasses))
{
if(inArray("_other_", @::allowedClasses))
{
$datum = "_other_";
}
else
{
$valid = 0;
}
}
}
# If this is an allowed output attribute (or we weren't checking)
if($valid)
{
if($datum eq "")
{
$valid = 0;
}
else
{
# Convert to Boolean if needed
if(!defined($::no) && $outIsBoolean)
{
$datum = (($datum == 1)?"TRUE":"FALSE");
}
# Append to the output string
$outputString .= $datum . "\n";
}
}
# Print results if valid
if($valid)
{
# If we are not limiting the output data or this is a record that
# has not been rejected
# 29.11.12 Added calls to PrintLineId() to print IDs before to
# a separate file with each entry $i as $data{$::id}[$i] By: NSAN
if(defined($::limit))
{
if(!$::rejectRecords[$i])
{
PrintLine(1, $outputString);
PrintLineId(1, $data{$::id}[$i].",".$outputString);
}
else
{
PrintLine(2, $outputString);
PrintLineId(2, $data{$::id}[$i].",".$outputString);
}
}
else
{
PrintLine(1, $outputString);
PrintLineId(1, $data{$::id}[$i].",".$outputString);
}
}
}
print STDERR "done\n" if(defined($::v));
}
#*************************************************************************
sub PrintLine
{
my($destination, $content) = @_;
if($destination&1)
{
print $content;
}
if(defined($::limit) && defined($::discard) && ($destination&2))
{
print DISCARDFILE $content;
}
}
#*************************************************************************
# 29.11.12 Print IDs before each entry By: NSAN
# 09.01.13 Corrections to logic in checking whether to print By: ACRM
sub PrintLineId
{
my($destination, $content) = @_;
if(defined($::id))
{
if(($destination&1) && defined($::idfile))
{
print IDFILE $content;
}
if(defined($::limit) && defined($::iddiscard) && ($destination&2))
{
print IDDISCARDFILE $content;
}
}
}
#*************************************************************************
sub IsValidNumber
{
my($value) = @_;
if($value =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
{
return(1);
}
return(0);
}
#*************************************************************************
sub FindAttribType
{
my ($isOutputAttrib, @data) = @_;
my %values;
# Store the observed values in a hash
foreach my $datum (@data)
{
if((($datum ne '') && ($datum ne '?')) ||
!defined($::skip))
{
$values{$datum} = 1;
}
}
# See if any of the observed values is non-numeric
my $numeric = 1;
foreach my $value (keys %values)
{
# Test if it's a valid number
if(!IsValidNumber($value) && ($value ne ""))
{
$numeric = 0;
last;
}
}
# If there is a non-numeric value then build the list of strings
if(!$numeric)
{
my $retString = "";
# If it's the output and we have defined some allowed classes
if($isOutputAttrib && int(@::allowedClasses))
{
foreach my $value (@::allowedClasses)
{
if($retString eq "")
{
$retString = "{";
}
else
{
$retString .= ",";
}
$retString .= $value;
}
$retString .= "}";
}
else
{
foreach my $value (sort keys %values)
{
if($retString eq "")
{
$retString = "{";
}
else
{
$retString .= ",";
}
$retString .= $value;
}
$retString .= "}";
}
# If it's boolean but only TRUE or FALSE is seen, change to both
if(($retString eq "{TRUE}") || ($retString eq "{FALSE}"))
{
$retString = "{TRUE,FALSE}";
}
if(($retString eq "{true}") || ($retString eq "{false}"))
{
$retString = "{true,false}";
}
# If there is only one value, add a dummy one
if(!$retString =~ /\,/)
{
$retString =~ s/\}/\,_dummy_\}/;
}
return($retString, 0);
}
else # It's numeric, but if the only values are 1 and 0 (or 1 and -1) then it's boolean
{
my @valArray = (keys %values);
if(int(@valArray) == 2)
{
if(((($valArray[0] == 0) || ($valArray[0] == (-1))) && ($valArray[1] == 1)) ||
((($valArray[1] == 0) || ($valArray[1] == (-1))) && ($valArray[0] == 1)))
{
# If it's the output and we haven't defined -no
# or it's an input and we haven't defined -ni
if(($isOutputAttrib && !defined($::no)) ||
(!$isOutputAttrib && !defined($::ni)))
{
return("{TRUE,FALSE}", 1);
}
}
}
elsif(int(@valArray) == 1)
{
if(($valArray[0] == 0) || ($valArray[0] == 1))
{
# If it's the output and we haven't defined -no
# or it's an input and we haven't defined -ni
if(($isOutputAttrib && !defined($::no)) ||
(!$isOutputAttrib && !defined($::ni)))
{
return("{TRUE,FALSE}", 1);
}
}
}
}
return("numeric", 0);
}
#*************************************************************************
sub inArray
{
my($element, @TheArray) = @_;
if (grep {$_ eq $element} @TheArray)
{
return(1);
}
return(0);
}
#*************************************************************************
sub ReadCSV
{
print STDERR "Reading data..." if(defined($::v));
$_ = <>;
chomp;
s/\r//g; # 19.11.13 Deal with DOS files
my @fieldNames = split(/\s*\,\s*/);
my $nFields = int(@fieldNames);
# Remove whitespace from field names
foreach my $fieldName (@fieldNames)
{
$fieldName =~ s/\s/\_/g;
}
my $count = 0;
while(<>)
{
chomp;
s/^\s+//;
s/\r//; # 19.11.13 Deal with DOS files
if(length)
{
my @fields = split(/\s*\,\s*/);
if(int(@fields) != $nFields)
{
print STDERR "Row discarded as it contained the wrong number of fields:\n $_\n";
}
else
{
for(my $fieldNum=0; $fieldNum<int(@fields); $fieldNum++)
{
$data{$fieldNames[$fieldNum]}[$count] = $fields[$fieldNum];
}
$count++;
}
}
}
print STDERR "done\n" if(defined($::v));
return($count, %data);
}
#*************************************************************************
# 12.04.21 Remove return characters for Windows files
sub ReadInputFields
{
my($input) = @_;
my @fields = ();
if(open(FILE, $input))
{
while(<FILE>)
{
chomp;
s/^\s+//;
s/\r//;
if(length)
{
push @fields, $_;
}
}
close FILE;
}
else
{
print STDERR "Can't open file with list of input fields - file not found: $input\n";
exit 1;
}
return(@fields);
}
#*************************************************************************
sub OversampleData
{
my($ndata, $output, $limit, %data, $over) = @_;
my @overSample = ();
if(defined($::limit) && defined($::over))
{
my %classCounts = ();
# Count how many of each output class there is
for(my $i=0; $i<$ndata; $i++)
{
my $class = $data{$output}[$i];
if(defined($classCounts{$class}))
{
$classCounts{$class}++;
}
else
{
$classCounts{$class}=1;
}
}
# Start off assuming we aren't using anything for oversampling
for (my $i=0; $i<$ndata; $i++)
{
$overSample[$i] = 0;
}
# Step through each class
foreach my $class (keys %classCounts)
{
my $kept = $classCounts{$class};
my $count = $classCounts{$class};
my $thisLimit = $limit;
$thisLimit = 2*$count if($limit > 2*$count);
my $resampling = ($kept < $thisLimit)?1:0;
print STDERR "Oversampling dataset $class..." if(defined($::v) && $resampling);
# While we don't have enough of this class
while($kept < $thisLimit)
{
# Run though the data looking for examples of this class
for(my $i=0; $i<$ndata; $i++)
{
# See if it's the class of interest
my $thisClass = $data{$output}[$i];
if($thisClass eq $class)
{
# If it's not yet chosen for over-sampling
if(!$overSample[$i])
{
# Based on random number we can choose to keep it
# my $rnum = Random($count);
my $rnum = Random($thisLimit);
if($rnum < ($thisLimit-$count))
{
$overSample[$i] = 1;
# Update the number kept - if it's now enough
# jump out of the loop
$kept++;
if($kept >= $thisLimit)
{
last;
}
}
}
}
}
}
print STDERR "done\n" if(defined($::v) && $resampling);
}
}
return(@overSample);
}
#*************************************************************************
# 15.10.19 Original By: ACRM
sub WriteOverSampledARFF
{
my ($output, $nData, $title, %data) = @_;