-
Notifications
You must be signed in to change notification settings - Fork 119
/
InstanceTools.java
1183 lines (974 loc) · 39.9 KB
/
InstanceTools.java
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
/*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The UEA TSML toolbox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package utilities;
import java.io.File;
import java.io.FileWriter;
import java.util.*;
//import scala.tools.nsc.Global;
import utilities.class_counts.ClassCounts;
import utilities.class_counts.TreeSetClassCounts;
import utilities.generic_storage.Pair;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.DistanceFunction;
import weka.core.Instance;
import weka.core.Instances;
/**
*
* @author Aaron
*/
public class InstanceTools {
public static double[] countClasses(Instances data) {
return countClasses(data, data.numClasses());
}
public static double[] countClasses(List<? extends Instance> data, int numClasses) {
double[] distribution = new double[numClasses];
for(Instance instance : data) {
final int classValue = (int) instance.classValue();
distribution[classValue] += instance.weight();
}
return distribution;
}
public static Map<Instance, Integer> indexInstances(Instances instances) {
Map<Instance, Integer> instanceIntegerMap = new HashMap<>(instances.size(), 1);
for(int i = 0; i < instances.size(); i++) {
instanceIntegerMap.put(instances.get(i), i);
}
return instanceIntegerMap;
}
public static void setClassMissing(Instances data) {
for(Instance instance : data) {
instance.setClassMissing();
}
}
public static Pair<Instance, Double> findMinDistance(Instances data, Instance inst, DistanceFunction dist){
double min = dist.distance(data.get(0), inst);
Instance minI = data.get(0);
for (int i = 1; i < data.numInstances(); i++) {
double temp = dist.distance(data.get(i), inst);
if(temp < min){
min = temp;
minI = data.get(i);
}
}
return new Pair(minI, min);
}
public static int[] deleteClassValues(Instances d){
int[] classVals=new int[d.numInstances()];
for(int i=0;i<d.numInstances();i++){
classVals[i]=(int)d.instance(i).classValue();
d.instance(i).setMissing(d.instance(i).classIndex());
}
return classVals;
}
/**
* By Aaron:
* Public method to calculate the class distributions of a dataset. Main
* purpose is for computing shapelet qualities.
*
* @param data the input data set that the class distributions are to be
* derived from
* @return a TreeMap<Double, Integer> in the form of <Class Value,
* Frequency>
*/
public static Map<Double, Integer> createClassDistributions(Instances data)
{
Map<Double, Integer> classDistribution = new TreeMap<>();
ListIterator<Instance> it = data.listIterator();
double classValue;
while (it.hasNext())
{
classValue = it.next().classValue();
Integer val = classDistribution.get(classValue);
val = (val != null) ? val + 1 : 1;
classDistribution.put(classValue, val);
}
return classDistribution;
}
/**
* by Tony
* Public method to calculate the class distributions of a dataset.
*/
public static double[] findClassDistributions(Instances data)
{
double[] dist=new double[data.numClasses()];
for(Instance d:data)
dist[(int)d.classValue()]++;
for(int i=0;i<dist.length;i++)
dist[i]/=data.numInstances();
return dist;
}
/**
* by James...
* Public method to calculate the class distributions given a list of class labels and the number of classes.
* Mostly to use with the data classifierresults/results analysis tools keep
*/
public static double[] findClassDistributions(ArrayList<Double> classLabels, int numClasses)
{
double[] dist=new double[numClasses];
for(double d:classLabels)
dist[(int)d]++;
for(int i=0;i<dist.length;i++)
dist[i]/=classLabels.size();
return dist;
}
public static Map<Double, Instances> createClassInstancesMap(Instances data)
{
Map<Double, Instances> instancesMap = new TreeMap<>();
ListIterator<Instance> it = data.listIterator();
double classValue;
while (it.hasNext())
{
Instance inst = it.next();
classValue = inst.classValue();
Instances val = instancesMap.get(classValue);
if(val == null)
val = new Instances(data, 0);
val.add(inst);
instancesMap.put(classValue, val);
}
return instancesMap;
}
/**
* Modified from Aaron's shapelet resampling code in development.ReasamplingExperiments. Used to resample
* train and test instances while maintaining original train/test class distributions
*
* @param train Input training instances
* @param test Input test instances
* @param seed Used to create reproducible folds by using a consistent seed value
* @return Instances[] with two elements; [0] is the output training instances, [1] output test instances
*/
public static Instances[] resampleTrainAndTestInstances(Instances train, Instances test, long seed){
if(seed==0){ //For consistency, I have made this clone the data. Its not necessary generally, but not doing it
// introduced a bug in diagnostics elsewhere
Instances newTrain = new Instances(train);
Instances newTest = new Instances(test);
return new Instances[]{newTrain,newTest};
}
Instances all = new Instances(train);
all.addAll(test);
ClassCounts trainDistribution = new TreeSetClassCounts(train);
Map<Double, Instances> classBins = createClassInstancesMap(all);
Random r = new Random(seed);
//empty instances.
Instances outputTrain = new Instances(all, 0);
Instances outputTest = new Instances(all, 0);
Iterator<Double> keys = classBins.keySet().iterator();
while(keys.hasNext()){
double classVal = keys.next();
int occurences = trainDistribution.get(classVal);
Instances bin = classBins.get(classVal);
bin.randomize(r); //randomise the bin.
outputTrain.addAll(bin.subList(0,occurences));//copy the first portion of the bin into the train set
outputTest.addAll(bin.subList(occurences, bin.size()));//copy the remaining portion of the bin into the test set.
}
return new Instances[]{outputTrain,outputTest};
}
/**
*
* @param all full data set
* @param seed random seed so that the split can be exactly duplicated
* @param propInTrain proportion of data for training
* @return
*/
public static Instances[] resampleInstances(Instances all, long seed, double propInTrain){
ClassCounts classDist = new TreeSetClassCounts(all);
Map<Double, Instances> classBins = createClassInstancesMap(all);
Random r = new Random(seed);
//empty instances.
Instances outputTrain = new Instances(all, 0);
Instances outputTest = new Instances(all, 0);
Iterator<Double> keys = classBins.keySet().iterator();
while(keys.hasNext()){ //For each class value
double classVal = keys.next();
//Get the number of this class to put in train and test
int classCount = classDist.get(classVal);
int occurences=(int)(classCount*propInTrain);
Instances bin = classBins.get(classVal);
bin.randomize(r); //randomise the instances in this class.
outputTrain.addAll(bin.subList(0,occurences));//copy the first portion of the bin into the train set
outputTest.addAll(bin.subList(occurences, bin.size()));//copy the remaining portion of the bin into the test set.
}
return new Instances[]{outputTrain,outputTest};
}
public static Instances resample(Instances series, double trainProportion, Random random) {
int newSize = (int)(series.numInstances()*trainProportion);
Instances newData = new Instances(series, newSize);
Instances temp = new Instances(series);
while (newData.numInstances() < newSize) {
newData.add(temp.remove(random.nextInt(temp.numInstances())));
}
return newData;
}
//converts a 2d array into a weka Instances.
public static Instances toWekaInstances(double[][] data) {
Instances wekaInstances = null;
if (data.length <= 0) {
return wekaInstances;
}
int dimRows = data.length;
int dimColumns = data[0].length;
// create a list of attributes features + label
ArrayList<Attribute> attributes = new ArrayList<>(dimColumns);
for (int i = 0; i < dimColumns; i++) {
attributes.add(new Attribute("attr" + String.valueOf(i + 1)));
}
// add the attributes
wekaInstances = new Instances("", attributes, dimRows);
// add the values
for (int i = 0; i < dimRows; i++) {
double[] instanceValues = new double[dimColumns];
for (int j = 0; j < dimColumns; j++) {
instanceValues[j] = data[i][j];
}
wekaInstances.add(new DenseInstance(1.0, instanceValues));
}
return wekaInstances;
}
//converts a 2d array into a weka Instances, setting the last attribute to be the class value.
public static Instances toWekaInstancesWithClass(double[][] data) {
Instances wekaInstances = toWekaInstances(data);
wekaInstances.setClassIndex(wekaInstances.numAttributes()-1);
return wekaInstances;
}
//converts a 2d array into a weka Instances, appending the ith classlabel onto the ith row of data for each instance
public static Instances toWekaInstances(double[][] data, double[] classLabels) {
//todo error checking if really wanted. all utils need it at some point
double[][] newData = new double[data.length][];
for (int i = 0; i < data.length; i++) {
newData[i] = new double[data[i].length + 1];
int j = 0;
for ( ; j < data[i].length; j++)
newData[i][j] = data[i][j];
newData[i][j] = classLabels[i];
}
return toWekaInstancesWithClass(newData);
}
//converts a weka Instances into a 2d array - removing class val at the end.
public static double[][] fromWekaInstancesArray(Instances ds, boolean removeLastVal) {
int numFeatures = ds.numAttributes() - (removeLastVal ? 1 : 0);
int numInstances = ds.numInstances();
double[][] data = new double[numInstances][numFeatures];
for (int i = 0; i < numInstances; i++) {
for (int j = 0; j < numFeatures; j++) {
data[i][j] = ds.get(i).value(j);
}
}
return data;
}
//converts a weka Instances into a 2d array.
public static ArrayList<ArrayList<Double>> fromWekaInstancesList(Instances ds) {
int numFeatures = ds.numAttributes()-1; //no classValue
int numInstances = ds.numInstances();
//Logging.println("Converting " + numInstances + " instances and " + numFeatures + " features.", LogLevel.DEBUGGING_LOG);
ArrayList<ArrayList<Double>> data = new ArrayList<>(numInstances);
ArrayList<Double> temp;
for (int i = 0; i < numInstances; i++) {
temp = new ArrayList<>(numFeatures);
for (int j = 0; j < numFeatures; j++) {
temp.add(ds.get(i).value(j));
}
data.add(temp);
}
return data;
}
//this is for Grabockas train/test set combo matrix. removes the need for appending.
public static double[][] create2DMatrixFromInstances(Instances train, Instances test) {
double [][] data = new double[train.numInstances() + test.numInstances()][train.numAttributes()];
for(int i=0; i<train.numInstances(); i++)
{
for(int j=0; j<train.numAttributes(); j++)
{
data[i][j] = train.get(i).value(j);
}
}
int index=0;
for(int i=train.numInstances(); i<train.numInstances()+test.numInstances(); i++)
{
for(int j=0; j<test.numAttributes(); j++)
{
data[i][j] = test.get(index).value(j);
}
++index;
}
return data;
}
// utility method for creating ARFF from UCR file without writing output, just returns Instances
public static Instances convertFromUCRtoARFF(String inputFilePath) throws Exception{
return convertFromUCRtoARFF(inputFilePath, null, null);
}
// writes output and returns Instances too
public static Instances convertFromUCRtoARFF(String inputFilePath, String outputRelationName, String fullOutputPath) throws Exception{
File input = new File(inputFilePath);
if(!input.exists()){
throw new Exception("Error converting to ARFF - input file not found: "+input.getAbsolutePath());
}
// get instance length
Scanner scan = new Scanner(input);
scan.useDelimiter("\n");
String firstIns = scan.next();
int numAtts = firstIns.split(",").length;
// create attribute list
ArrayList<Attribute> attList = new ArrayList<>();
for(int i = 0; i < numAtts-1; i++){
attList.add(new Attribute("att"+i));
}
attList.add(new Attribute("classVal"));
// create Instances object
Instances output;
if(outputRelationName==null){
output = new Instances("temp", attList, numAtts);
}else{
output = new Instances(outputRelationName, attList, numAtts);
}
output.setClassIndex(numAtts-1);
// populate Instances
String[] nextIns;
DenseInstance d;
scan = new Scanner(input);
scan.useDelimiter("\n");
while(scan.hasNext()){
nextIns = scan.next().split(",");
d = new DenseInstance(numAtts);
for(int a = 0; a < numAtts-1; a++){
d.setValue(a, Double.parseDouble(nextIns[a+1]));
}
d.setValue(numAtts-1, Double.parseDouble(nextIns[0]));
output.add(d);
}
// if null, don't write. Else, write output ARFF here
if(fullOutputPath!=null){
System.out.println(fullOutputPath.substring(fullOutputPath.length()-5, fullOutputPath.length()));
if(!fullOutputPath.substring(fullOutputPath.length()-5, fullOutputPath.length()).equalsIgnoreCase(".ARFF")){
fullOutputPath += ".ARFF";
}
new File(fullOutputPath).getParentFile().mkdirs();
FileWriter out = new FileWriter(fullOutputPath);
out.append(output.toString());
out.close();
}
return output;
}
public static void removeConstantTrainAttributes(Instances train, Instances test){
int i=0;
while(i<train.numAttributes()-1){ //Dont test class
// Test if constant
int j=1;
while(j<train.numInstances() && train.instance(j-1).value(i)==train.instance(j).value(i))
j++;
if(j==train.numInstances()){
// Remove from train
train.deleteAttributeAt(i);
test.deleteAttributeAt(i);
// Remove from test
}else{
i++;
}
}
}
/**
*
* @param ins Instances object
* @return true if there are any missing values (including class value)
*/
public static boolean hasMissing(Instances ins){
for(Instance in:ins)
if(in.hasMissingValue())
return true;
return false;
}
/**
* Deletes the attributes by *shifted* index, i.e. the positions are *not* the
* original positions in the data
* @param test
* @param features
*/
public static void removeConstantAttributes(Instances test, int[] features){
for(int del:features)
test.deleteAttributeAt(del);
}
//Returns the *shifted* indexes, so just deleting them should work
public static int[] removeConstantTrainAttributes(Instances train){
int i=0;
LinkedList<Integer> list= new LinkedList<>();
int count=0;
while(i<train.numAttributes()-1){ //Dont test class
// Test if constant
int j=1;
while(j<train.numInstances() && train.instance(j-1).value(i)==train.instance(j).value(i))
j++;
if(j==train.numInstances()){
// Remove from train
train.deleteAttributeAt(i);
list.add(i);
// Remove from test
}else{
i++;
}
count++;
}
int[] del=new int[list.size()];
count=0;
for(Integer in:list){
del[count++]=in;
}
return del;
}
/**
* Removes attributes deemed redundant. These are either
* 1. All one value (i.e. constant)
* 2. Some odd test to count the number different to the one before.
* I think this is meant to count the number of different values?
* It would be good to delete attributes that are identical to other attributes.
* @param train instances from which to remove redundant attributes
* @return array of indexes of attributes remove
*/
//Returns the *shifted* indexes, so just deleting them should work
//Removes all constant attributes or attributes with just a single value
public static int[] removeRedundantTrainAttributes(Instances train){
int i=0;
int minNumDifferent=2;
boolean remove=false;
LinkedList<Integer> list= new LinkedList<>();
int count=0;
while(i<train.numAttributes()-1){ //Dont test class
remove=false;
// Test if constant
int j=1;
if(train.instance(j-1).value(i)==train.instance(j).value(i))
while(j<train.numInstances() && train.instance(j-1).value(i)==train.instance(j).value(i))
j++;
if(j==train.numInstances())
remove=true;
else{
//Test pairwise similarity?
//I think this is meant to test how many different values there are. If so, it should be
//done with a HashSet of doubles. This counts how many values are identical to their predecessor
count =0;
for(j=1;j<train.numInstances();j++){
if(train.instance(j-1).value(i)==train.instance(j).value(i))
count++;
}
if(train.numInstances()-count<minNumDifferent+1)
remove=true;
}
if(remove){
// Remove from data
train.deleteAttributeAt(i);
list.add(i);
}else{
i++;
}
// count++;
}
int[] del=new int[list.size()];
count=0;
for(Integer in:list){
del[count++]=in;
}
return del;
}
//be careful using this function.
//this wants to create a proportional sub sample
//but if you're sampling size is too small you could create a dodgy dataset.
public static Instances subSample(Instances data, int amount, int seed){
if(amount < data.numClasses()) System.out.println("Error: too few instances compared to classes.");
Map<Double, Instances> classBins = createClassInstancesMap(data);
ClassCounts trainDistribution = new TreeSetClassCounts(data);
Random r = new Random(seed);
//empty instances.
Instances output = new Instances(data, 0);
Iterator<Double> keys = classBins.keySet().iterator();
while(keys.hasNext()){
double classVal = keys.next();
int occurences = trainDistribution.get(classVal);
float proportion = (float) occurences / (float) data.numInstances();
int numInstances = (int) (proportion * amount);
Instances bin = classBins.get(classVal);
bin.randomize(r); //randomise the bin.
output.addAll(bin.subList(0,numInstances));//copy the first portion of the bin into the train set
}
return output;
}
public static Instances subSampleFixedProportion(Instances data, double proportion, long seed){
Map<Double, Instances> classBins = createClassInstancesMap(data);
ClassCounts trainDistribution = new TreeSetClassCounts(data);
Random r = new Random(seed);
//empty instances.
Instances output = new Instances(data, 0);
Iterator<Double> keys = trainDistribution.keySet().iterator();
while(keys.hasNext()){
double classVal = keys.next();
int occurences = trainDistribution.get(classVal);
int numInstances = (int) (proportion * occurences);
Instances bin = classBins.get(classVal);
bin.randomize(r); //randomise the bin.
output.addAll(bin.subList(0,numInstances));//copy the first portion of the bin into the train set
}
return output;
}
//use in conjunction with subSampleFixedProportion.
//Instances subSample = InstanceTools.subSampleFixedProportion(train, proportion, fold);
public static double calculateSubSampleProportion(Instances train, int min){
int small_sf = InstanceTools.findSmallestClassAmount(train);
double proportion = 1;
if (small_sf>min){
proportion = (double)min/(double)small_sf;
if (proportion < 0.1)
proportion = 0.1;
}
return proportion;
}
public static int findSmallestClassAmount(Instances data){
ClassCounts trainDistribution = new TreeSetClassCounts(data);
//find the smallest represented class.
Iterator<Double> keys = trainDistribution.keySet().iterator();
int small_sf = Integer.MAX_VALUE;
int occurences;
double key;
while(keys.hasNext()){
key = keys.next();
occurences = trainDistribution.get(key);
if(occurences < small_sf)
small_sf = occurences;
}
return small_sf;
}
public static int indexOf(Instances dataset, Instance find){
int index = -1;
for(int i=0; i<dataset.numInstances(); i++){
Instance in = dataset.get(i);
boolean match = true;
for(int j=0; j<in.numAttributes();j++){
if(in.value(j) != find.value(j))
match = false;
}
if(match){
index = i;
break;
}
}
return index;
}
public static int indexOf2(Instances dataset, Instance find){
int index = -1;
for(int i=0; i< dataset.numInstances(); i++){
if(dataset.instance(i).toString(0).contains(find.toString(0))){
index = i;
break;
}
}
return index;
}
//similar to concatinate, but interweaves the attributes.
//all of att_0 in each instance, then att_1 etc.
public static Instances mergeInstances(String dataset, Instances[] inst, String[] dimChars){
ArrayList<Attribute> atts = new ArrayList<>();
String name;
Instances firstInst = inst[0];
int dimensions = inst.length;
int length = (firstInst.numAttributes()-1)*dimensions;
for (int i = 0; i < length; i++) {
name = dataset + "_" + dimChars[i%dimensions] + "_" + (i/dimensions);
atts.add(new Attribute(name));
}
//clone the class values over.
//Could be from x,y,z doesn't matter.
Attribute target = firstInst.attribute(firstInst.classIndex());
ArrayList<String> vals = new ArrayList<>(target.numValues());
for (int i = 0; i < target.numValues(); i++) {
vals.add(target.value(i));
}
atts.add(new Attribute(firstInst.attribute(firstInst.classIndex()).name(), vals));
//same number of xInstances
Instances result = new Instances(dataset + "_merged", atts, firstInst.numInstances());
int size = result.numAttributes()-1;
for(int i=0; i< firstInst.numInstances(); i++){
result.add(new DenseInstance(size+1));
for(int j=0; j<size;){
for(int k=0; k< dimensions; k++){
result.instance(i).setValue(j,inst[k].get(i).value(j/dimensions)); j++;
}
}
}
for (int j = 0; j < result.numInstances(); j++) {
//we always want to write the true ClassValue here. Irrelevant of binarised or not.
result.instance(j).setValue(size, firstInst.get(j).classValue());
}
return result;
}
public static void deleteClassAttribute(Instances data){
if (data.classIndex() >= 0){
int clsIndex = data.classIndex();
data.setClassIndex(-1);
data.deleteAttributeAt(clsIndex);
}
}
public static List<Instances> instancesByClass(Instances instances) {
List<Instances> instancesByClass = new ArrayList<>();
int numClasses = instances.get(0).numClasses();
for(int i = 0; i < numClasses; i++) {
instancesByClass.add(new Instances(instances,0));
}
for(Instance instance : instances) {
instancesByClass.get((int) instance.classValue()).add(instance);
}
return instancesByClass;
}
public static List<List<Integer>> indexByClass(Instances instances) {
List<List<Integer>> instancesByClass = new ArrayList<>();
int numClasses = instances.get(0).numClasses();
for(int i = 0; i < numClasses; i++) {
instancesByClass.add(new ArrayList());
}
for(int i = 0; i < instances.size(); i++) {
instancesByClass.get((int) instances.get(i).classValue()).add(i);
}
return instancesByClass;
}
public static double[] classCounts(Instances instances) {
double[] counts = new double[instances.numClasses()];
for(Instance instance : instances) {
counts[(int) instance.classValue()]++;
}
return counts;
}
public static double[] classDistribution(Instances instances) {
double[] distribution = new double[instances.numClasses()];
for(Instance instance : instances) {
distribution[(int) instance.classValue()]++;
}
ArrayUtilities.normalise(distribution);
return distribution;
}
/**
* Concatenate features into a new Instances. Check is made that the class
* values are the same
* @param a
* @param b
* @return
*/
public static Instances concatenateInstances(Instances a, Instances b){
if(a.numInstances()!=b.numInstances())
throw new RuntimeException(" ERROR in concatenate Instances, number of cases unequal");
for(int i=0;i<a.numInstances();i++){
if(a.instance(i).classValue()!=b.instance(i).classValue())
throw new RuntimeException(" ERROR in concatenate Instances, class labels not alligned in case "+i+" class in a ="+a.instance(i).classValue()+" and in b equals "+b.instance(i).classValue());
}
//4. Merge them all together
Instances combo=new Instances(a);
combo.setClassIndex(-1);
combo.deleteAttributeAt(combo.numAttributes()-1);
combo=Instances.mergeInstances(combo,b);
combo.setClassIndex(combo.numAttributes()-1);
return combo;
}
public static Map<Double, Instances> byClass(Instances instances) {
Map<Double, Instances> map = new HashMap<>();
for(Instance instance : instances) {
map.computeIfAbsent(instance.classValue(), k -> new Instances(instances, 0)).add(instance);
}
return map;
}
public static Instance reverseSeries(Instance inst){
Instance newInst = new DenseInstance(inst);
for (int i = 0; i < inst.numAttributes()-1; i++){
newInst.setValue(i, inst.value(inst.numAttributes()-i-2));
}
return newInst;
}
public static Instance shiftSeries(Instance inst, int shift){
Instance newInst = new DenseInstance(inst);
if (shift < 0){
shift = Math.abs(shift);
for (int i = 0; i < inst.numAttributes()-shift-1; i++){
newInst.setValue(i, inst.value(i+shift));
}
for (int i = inst.numAttributes()-shift-1; i < inst.numAttributes()-1; i++){
newInst.setValue(i, 0);
}
}
else if (shift > 0){
for (int i = 0; i < shift; i++){
newInst.setValue(i, 0);
}
for (int i = shift; i < inst.numAttributes()-1; i++){
newInst.setValue(i, inst.value(i-shift));
}
}
return newInst;
}
public static Instance randomlyAddToSeriesValues(Instance inst, Random rand, int minAdd, int maxAdd, int maxValue){
Instance newInst = new DenseInstance(inst);
for (int i = 0; i < inst.numAttributes()-1; i++){
int n = rand.nextInt(maxAdd+1-minAdd)+minAdd;
double newVal = inst.value(i)+n;
if (newVal > maxValue) newVal = maxValue;
newInst.setValue(i, newVal);
}
return newInst;
}
public static Instance randomlySubtractFromSeriesValues(Instance inst, Random rand, int minSubtract, int maxSubtract, int minValue){
Instance newInst = new DenseInstance(inst);
for (int i = 0; i < inst.numAttributes()-1; i++){
int n = rand.nextInt(maxSubtract+1-maxSubtract)+maxSubtract;
double newVal = inst.value(i)-n;
if (newVal < minValue) newVal = minValue;
newInst.setValue(i, newVal);
}
return newInst;
}
public static Instance randomlyAlterSeries(Instance inst, Random rand){
Instance newInst = new DenseInstance(inst);
if (rand.nextBoolean()){
newInst = reverseSeries(newInst);
}
int shift = rand.nextInt(240)-120;
newInst = shiftSeries(newInst, shift);
if (rand.nextBoolean()){
newInst = randomlyAddToSeriesValues(newInst, rand, 0, 5, Integer.MAX_VALUE);
}
else{
newInst = randomlySubtractFromSeriesValues(newInst, rand, 0, 5, 0);
}
return newInst;
}
public static Instances shortenInstances(Instances data, double proportionRemaining, boolean normalise){
if (proportionRemaining > 1 || proportionRemaining <= 0){
throw new RuntimeException("Remaining series length propotion must be greater than 0 and less than or equal to 1");
}
else if (data.classIndex() != data.numAttributes()-1){
throw new RuntimeException("Dataset class attribute must be the final attribute");
}
Instances shortenedData = new Instances(data);
if (proportionRemaining == 1) return shortenedData;
int newSize = (int)Math.round((data.numAttributes()-1) * proportionRemaining);
if (newSize == 0) newSize = 1;
if (normalise) {
Instances tempData = truncateInstances(data, data.numAttributes()-1, newSize);
tempData = zNormaliseWithClass(tempData);
for (int i = 0; i < data.numInstances(); i++){
for (int n = 0; n < tempData.numAttributes()-1; n++){
shortenedData.get(i).setValue(n, tempData.get(i).value(n));
}
}
}
for (int i = 0; i < data.numInstances(); i++){
for (int n = data.numAttributes()-2; n >= newSize; n--){
//shortenedData.get(i).setMissing(n);
shortenedData.get(i).setValue(n, 0);
}
}
return shortenedData;
}
public static Instances truncateInstances(Instances data, int fullLength, int newLength){
Instances newData = new Instances(data);
for (int i = 0; i < fullLength - newLength; i++){
newData.deleteAttributeAt(newLength);
}
return newData;
}
public static Instances truncateInstances(Instances data, double proportionRemaining){
if (proportionRemaining == 1) return data;
int newSize = (int)Math.round((data.numAttributes()-1) * proportionRemaining);
if (newSize == 0) newSize = 1;
return truncateInstances(data, data.numAttributes()-1, newSize);
}
public static Instance truncateInstance(Instance inst, int fullLength, int newLength){
Instance newInst = new DenseInstance(inst);
for (int i = 0; i < fullLength - newLength; i++){
newInst.deleteAttributeAt(newLength);
}
return newInst;
}
public static Instances zNormaliseWithClass(Instances data) {
Instances newData = new Instances(data, 0);
for (int i = 0; i < data.numInstances(); i++){
newData.add(zNormaliseWithClass(data.get(i)));
}
return newData;
}
public static Instance zNormaliseWithClass(Instance inst){
Instance newInst = new DenseInstance(inst);
newInst.setDataset(inst.dataset());
double meanSum = 0;
int length = newInst.numAttributes()-1;
if (length < 2) return newInst;
for (int i = 0; i < length; i++){
meanSum += newInst.value(i);
}
double mean = meanSum / length;
double squareSum = 0;
for (int i = 0; i < length; i++){
double temp = newInst.value(i) - mean;
squareSum += temp * temp;
}
double stdev = Math.sqrt(squareSum/(length-1));
if (stdev == 0){
stdev = 1;