-
Notifications
You must be signed in to change notification settings - Fork 120
/
WEASEL.java
1753 lines (1478 loc) · 56.3 KB
/
WEASEL.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 tsml.classifiers.dictionary_based;
import com.carrotsearch.hppc.*;
import com.carrotsearch.hppc.cursors.DoubleIntCursor;
import com.carrotsearch.hppc.cursors.IntCursor;
import com.carrotsearch.hppc.cursors.LongDoubleCursor;
import com.carrotsearch.hppc.cursors.LongIntCursor;
import de.bwaldvogel.liblinear.*;
import edu.emory.mathcs.jtransforms.fft.DoubleFFT_1D;
import evaluation.evaluators.CrossValidationEvaluator;
import evaluation.storage.ClassifierResults;
import experiments.data.DatasetLoading;
import tsml.classifiers.EnhancedAbstractClassifier;
import utilities.ClassifierTools;
import weka.classifiers.Classifier;
import weka.core.*;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* WEASEL Classifier
*
* @author Patrick Schaefer
*
*/
public class WEASEL extends EnhancedAbstractClassifier implements TechnicalInformationHandler {
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(TechnicalInformation.Type.ARTICLE);
result.setValue(TechnicalInformation.Field.AUTHOR, "P. Schaefer, U. Leser");
result.setValue(TechnicalInformation.Field.TITLE, "Fast and Accurate Time Series Classification with WEASEL");
result.setValue(TechnicalInformation.Field.JOURNAL, "CIKM");
result.setValue(TechnicalInformation.Field.YEAR, "2017");
return result;
}
public WEASELModel classifier;
// WEASEL model parameters
protected final int maxS = 4;
protected int minF = 4;
protected int maxF = 6;
protected static boolean[] NORMALIZATION = new boolean[]{true, false};
// chi-squared test
public static double chi = 0.1;
public static int limit = 1000;
// default liblinear parameters
public static double bias = 1;
public static double p = 0.1;
public static int iterations = 5000;
public static double c = 1;
public static SolverType solverType = SolverType.L2R_LR_DUAL;
//private double trainAcc = -1;
public static int MIN_WINDOW_LENGTH = 2;
public static int MAX_WINDOW_LENGTH = 350;
// ten-fold cross validation
private int folds = 10;
@Override
public ClassifierResults getTrainResults() {
return trainResults;
}
public static class WEASELModel {
public WEASELModel(){}
public WEASELModel(
boolean normed,
int features,
WEASELTransform model,
de.bwaldvogel.liblinear.Model linearModel
) {
this.normed = normed;
this.features = features;
this.weasel = model;
this.linearModel = linearModel;
}
public boolean normed;
// the best number of Fourier values to be used
public int features;
// the trained WEASEL transformation
public WEASELTransform weasel;
// the trained liblinear classifier
public de.bwaldvogel.liblinear.Model linearModel;
}
/**
*
*/
public WEASEL() {
super(CANNOT_ESTIMATE_OWN_PERFORMANCE);
}
public WEASEL(int s) {
super(CANNOT_ESTIMATE_OWN_PERFORMANCE);
setSeed(seed);
}
@Override
public String getParameters() {
StringBuilder sb = new StringBuilder();
sb.append(super.getParameters());
sb.append(",maxF,").append(maxF).append(",minF,").append(minF);
return sb.toString();
}
protected int getMax(Instances samples, int maxWindowSize) {
int max = 0;
for (Instance inst : samples) {
max = Math.max(instanceLength(inst), max);
}
return Math.min(maxWindowSize,max);
}
public int[] getWindowLengths(final Instances samples, boolean norm) {
int min = norm && MIN_WINDOW_LENGTH<=2? Math.max(3,MIN_WINDOW_LENGTH) : MIN_WINDOW_LENGTH;
int max = getMax(samples, MAX_WINDOW_LENGTH);
int[] wLengths = new int[max - min + 1];
int a = 0;
for (int w = min; w <= max; w+=1, a++) {
wLengths[a] = w;
}
return Arrays.copyOfRange(wLengths, 0, a);
}
protected static double[] getLabels(final WEASELTransform.BagOfBigrams[] bagOfPatternsTestSamples) {
double[] labels = new double[bagOfPatternsTestSamples.length];
for (int i = 0; i < bagOfPatternsTestSamples.length; i++) {
labels[i] = bagOfPatternsTestSamples[i].label;
}
return labels;
}
protected static Problem initLibLinearProblem(
final WEASELTransform.BagOfBigrams[] bob,
final WEASELTransform.Dictionary dict,
final double bias) {
Linear.resetRandom();
Linear.disableDebugOutput();
Problem problem = new Problem();
problem.bias = bias;
problem.y = getLabels(bob);
final FeatureNode[][] features = initLibLinear(bob, dict);
problem.n = dict.size() + 1;
problem.l = features.length;
problem.x = features;
return problem;
}
protected static FeatureNode[][] initLibLinear(
final WEASELTransform.BagOfBigrams[] bob,
final WEASELTransform.Dictionary dict) {
FeatureNode[][] featuresTrain = new FeatureNode[bob.length][];
for (int j = 0; j < bob.length; j++) {
WEASELTransform.BagOfBigrams bop = bob[j];
ArrayList<FeatureNode> features = new ArrayList<>(bop.bob.size());
for (LongIntCursor word : bop.bob) {
if (word.value > 0) {
features.add(new FeatureNode(dict.getWordChi(word.key), (word.value)));
}
}
FeatureNode[] featuresArray = features.toArray(new FeatureNode[]{});
Arrays.sort(featuresArray, new Comparator<FeatureNode>() {
public int compare(FeatureNode o1, FeatureNode o2) {
return Integer.compare(o1.index, o2.index);
}
});
featuresTrain[j] = featuresArray;
}
return featuresTrain;
}
private static void swap(int[] array, int idxA, int idxB) {
int temp = array[idxA];
array[idxA] = array[idxB];
array[idxB] = temp;
}
@SuppressWarnings("static-access")
protected static int trainLibLinear(
final Problem prob, final SolverType solverType, double c,
int iter, double p, int nr_fold) {
final Parameter param = new Parameter(solverType, c, iter, p);
ThreadLocal<Random> myRandom = new ThreadLocal<>();
myRandom.set(new Random(1));
Random random = myRandom.get();
int k;
final int l = prob.l;
final int[] perm = new int[l];
if (nr_fold > l) {
nr_fold = l;
}
final int[] fold_start = new int[nr_fold + 1];
for (k = 0; k < l; k++) {
perm[k] = k;
}
for (k = 0; k < l; k++) {
int j = k + random.nextInt(l - k);
swap(perm, k, j);
}
for (k = 0; k <= nr_fold; k++) {
fold_start[k] = k * l / nr_fold;
}
final AtomicInteger correct = new AtomicInteger(0);
final int fold = nr_fold;
Linear myLinear = new Linear();
myLinear.disableDebugOutput();
myLinear.resetRandom(); // reset random component of liblinear for reproducibility
for (int i = 0; i < fold; i++) {
int begin = fold_start[i];
int end = fold_start[i + 1];
int j, kk;
Problem subprob = new Problem();
subprob.bias = prob.bias;
subprob.n = prob.n;
subprob.l = l - (end - begin);
subprob.x = new Feature[subprob.l][];
subprob.y = new double[subprob.l];
kk = 0;
for (j = 0; j < begin; j++) {
subprob.x[kk] = prob.x[perm[j]];
subprob.y[kk] = prob.y[perm[j]];
++kk;
}
for (j = end; j < l; j++) {
subprob.x[kk] = prob.x[perm[j]];
subprob.y[kk] = prob.y[perm[j]];
++kk;
}
de.bwaldvogel.liblinear.Model submodel = myLinear.train(subprob, param);
for (j = begin; j < end; j++) {
correct.addAndGet(prob.y[perm[j]] == myLinear.predict(submodel, prob.x[perm[j]]) ? 1 : 0);
}
}
return correct.get();
}
@Override
public void buildClassifier(final Instances samples) throws Exception {
long t1=System.nanoTime();
if (samples.classIndex() != samples.numAttributes()-1)
throw new Exception("WEASEL_BuildClassifier: Class attribute not set as last attribute in dataset");
try {
int maxCorrect = -1;
int bestF = -1;
boolean bestNorm = false;
optimize:
for (final boolean mean : NORMALIZATION) {
int[] windowLengths = getWindowLengths(samples, mean);
WEASELTransform model = new WEASELTransform(maxF, maxS, windowLengths, mean);
int[][][] words = model.createWords(samples);
for (int f = minF; f <= maxF; f += 2) {
model.dict.reset();
final WEASELTransform.BagOfBigrams[] bop = new WEASELTransform.BagOfBigrams[samples.size()];
final int ff = f;
for (int w = 0; w < model.windowLengths.length; w++) {
WEASELTransform.BagOfBigrams[] bobForOneWindow = fitOneWindow(
samples,
model.windowLengths, mean,
words[w], ff, w);
mergeBobs(bop, bobForOneWindow);
}
// train liblinear
final Problem problem = initLibLinearProblem(bop, model.dict, bias);
int correct = trainLibLinear(problem, solverType, c, iterations, p, folds);
if (correct > maxCorrect) {
maxCorrect = correct;
bestF = f;
bestNorm = mean;
}
if (correct == samples.numInstances()) {
break optimize;
}
}
}
// obtain the final matrix
int[] windowLengths = getWindowLengths(samples, bestNorm);
WEASELTransform model = new WEASELTransform(maxF, maxS, windowLengths, bestNorm);
final WEASELTransform.BagOfBigrams[] bop = new WEASELTransform.BagOfBigrams[samples.size()];
for (int w = 0; w < model.windowLengths.length; w++) {
int[][] words = model.createWords(samples, w);
WEASELTransform.BagOfBigrams[] bobForOneWindow = fitOneWindow(
samples,
model.windowLengths, bestNorm,
words, bestF, w);
mergeBobs(bop, bobForOneWindow);
}
// train liblinear
Problem problem = initLibLinearProblem(bop, model.dict, bias);
de.bwaldvogel.liblinear.Model linearModel = Linear.train(problem, new Parameter(solverType, c, iterations, p));
this.classifier = new WEASELModel(
bestNorm,
bestF,
model,
linearModel
);
} catch (Exception e) {
e.printStackTrace();
}
if(getEstimateOwnPerformance()){
int numFolds=setNumberOfFolds(samples);
CrossValidationEvaluator cv = new CrossValidationEvaluator();
if (seedClassifier) {
cv.setSeed(seed);
}
cv.setNumFolds(numFolds);
WEASEL weasel = new WEASEL();
trainResults=cv.crossValidateWithStats(weasel,samples);
}
//NOTE TODO : prior to refactor, the estimate time was being included in the build time
//measurement. I have retained that here for continuity, shout at jamesl otherwise
long t2=System.nanoTime();
trainResults.setEstimatorName(getClassifierName());
trainResults.setParas(classifierName);
trainResults.setBuildTime(t2-t1);
trainResults.setParas(getParameters());
}
private WEASELTransform.BagOfBigrams[] fitOneWindow(
Instances samples,
int[] windowLengths, boolean mean,
int[][] word, int f, int w) {
WEASELTransform modelForWindow = new WEASELTransform(f, maxS, windowLengths, mean);
WEASELTransform.BagOfBigrams[] bopForWindow = modelForWindow.createBagOfPatterns(word, samples, w, f);
modelForWindow.trainChiSquared(bopForWindow, chi);
return bopForWindow;
}
private synchronized void mergeBobs(
WEASELTransform.BagOfBigrams[] bop,
WEASELTransform.BagOfBigrams[] bopForWindow) {
for (int i = 0; i < bop.length; i++) {
if (bop[i]==null) {
bop[i] = bopForWindow[i];
}
else {
bop[i].bob.putAll(bopForWindow[i].bob);
}
}
}
@Override
public double classifyInstance(Instance instance) throws Exception {
// iterate each sample to classify
final WEASELTransform.BagOfBigrams[] bagTest = new WEASELTransform.BagOfBigrams[1];
for (int w = 0; w < classifier.weasel.windowLengths.length; w++) {
int[] wordsTest = classifier.weasel.createWords(instance, w);
WEASELTransform.BagOfBigrams[] bopForWindow =
new WEASELTransform.BagOfBigrams[]{classifier.weasel.createBagOfPatterns(wordsTest, instance, w, classifier.features)};
classifier.weasel.dict.filterChiSquared(bopForWindow);
mergeBobs(bagTest, bopForWindow);
}
FeatureNode[][] features = initLibLinear(bagTest, classifier.weasel.dict);
return Linear.predict(classifier.linearModel, features[0]);
}
@Override
public double[] distributionForInstance(Instance instance) throws Exception {
double[] classHist = new double[instance.numClasses()];
// iterate each sample to classify
final WEASELTransform.BagOfBigrams[] bagTest = new WEASELTransform.BagOfBigrams[1];
for (int w = 0; w < classifier.weasel.windowLengths.length; w++) {
int[] wordsTest = classifier.weasel.createWords(instance, w);
WEASELTransform.BagOfBigrams[] bopForWindow =
new WEASELTransform.BagOfBigrams[]{classifier.weasel.createBagOfPatterns(wordsTest, instance, w, classifier.features)};
classifier.weasel.dict.filterChiSquared(bopForWindow);
mergeBobs(bagTest, bopForWindow);
}
FeatureNode[][] features = initLibLinear(bagTest, classifier.weasel.dict);
double[] probabilities = new double[classifier.linearModel.getNrClass()];
Linear.predictProbability(classifier.linearModel, features[0], probabilities);
// TODO do we have to remap classes to indices???
for (int i = 0; i < classifier.linearModel.getLabels().length; i++) {
classHist[classifier.linearModel.getLabels()[i]] = probabilities[i];
}
return classHist;
}
@Override
public Capabilities getCapabilities() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* @return data of passed instance in a double array with the class value removed if present
*/
protected static double[] toArrayNoClass(Instance inst) {
int length = inst.numAttributes();
if (inst.classIndex() >= 0)
--length;
double[] data = new double[length];
for (int i=0, j=0; i < inst.numAttributes(); ++i)
if (inst.classIndex() != i)
data[j++] = inst.value(i);
return data;
}
protected static int instanceLength(Instance inst) {
int length = inst.numAttributes();
if (inst.classIndex() >= 0)
--length;
return length;
}
protected static int binlog(int bits) {
int log = 0;
if ((bits & 0xffff0000) != 0) {
bits >>>= 16;
log = 16;
}
if (bits >= 256) {
bits >>>= 8;
log += 8;
}
if (bits >= 16) {
bits >>>= 4;
log += 4;
}
if (bits >= 4) {
bits >>>= 2;
log += 2;
}
return log + (bits >>> 1);
}
/**
* WEASEL classifier to be used with known parameters, for boss with parameter search, use BOSSEnsemble.
*
* Current implementation of BitWord as of 07/11/2016 only supports alphabetsize of 4, which is the expected value
* as defined in the paper
*
* Params:
*
* @author Patrick Schaefer
*/
public static class WEASELTransform {
public int alphabetSize;
public int maxF;
public int[] windowLengths;
public boolean normMean;
public SFASupervised[] signature;
public Dictionary dict;
/**
* The WEASEL-model: a histogram of SFA word and bi-gram frequencies
*/
public static class BagOfBigrams {
public LongIntHashMap bob;
public Double label;
public BagOfBigrams(int size, Double label) {
this.bob = new LongIntHashMap(size);
this.label = label;
}
}
/**
* A dictionary that maps each SFA word to an integer.
* <p>
* Condenses the SFA word space.
*/
public static class Dictionary {
public LongIntHashMap dictChi;
public Dictionary() {
this.dictChi = new LongIntHashMap();
}
public void reset() {
this.dictChi = new LongIntHashMap();
}
public int getWordChi(long word) {
int index = 0;
if ((index = this.dictChi.indexOf(word)) > -1) {
return this.dictChi.indexGet(index);
} else {
int newWord = this.dictChi.size() + 1;
this.dictChi.put(word, newWord);
return newWord;
}
}
public int size() {
return this.dictChi.size();
}
public void filterChiSquared(final BagOfBigrams[] bagOfPatterns) {
for (int j = 0; j < bagOfPatterns.length; j++) {
LongIntHashMap oldMap = bagOfPatterns[j].bob;
bagOfPatterns[j].bob = new LongIntHashMap();
for (LongIntCursor word : oldMap) {
if (this.dictChi.containsKey(word.key) && word.value > 0) {
bagOfPatterns[j].bob.put(word.key, word.value);
}
}
}
}
}
public WEASELTransform( int maxF, int maxS,
int[] windowLengths, boolean normMean) {
this.maxF = maxF;
this.alphabetSize = maxS;
this.windowLengths = windowLengths;
this.normMean = normMean;
this.dict = new Dictionary();
this.signature = new SFASupervised[windowLengths.length];
}
/**
* Create SFA words and bigrams for all samples
*
* @param samples
* @return
*/
public int[][][] createWords(final Instances samples) {
// create bag of words for each window queryLength
final int[][][] words = new int[this.windowLengths.length][samples.numInstances()][];
for (int w = 0; w < this.windowLengths.length; w++) {
words[w] = createWords(samples, w);
};
return words;
}
/**
* Create SFA words and bigrams for a single sample
*
* @param sample
* @return
*/
public int[][] createWords(final Instance sample) {
// create bag of words for each window queryLength
final int[][] words = new int[this.windowLengths.length][];
for (int w = 0; w < windowLengths.length; w++) {
words[w] = createWords(sample, w);
};
return words;
}
/**
* Create SFA words and bigrams for all samples
*
* @param samples
* @return
*/
protected int[][] createWords(final Instances samples, final int index) {
// SFA quantization
if (this.signature[index] == null) {
this.signature[index] = new SFASupervised();
this.signature[index].fitWindowing(
samples, this.windowLengths[index], this.maxF, this.alphabetSize, this.normMean);
}
// create words
final int[][] words = new int[samples.numInstances()][];
for (int i = 0; i < samples.numInstances(); i++) {
words[i] = createWords(samples.get(i), index);
}
return words;
}
/**
* Create SFA words and bigrams for a single sample
*
* @param sample
* @return
*/
private int[] createWords(final Instance sample, final int index) {
// create words
if (instanceLength(sample) >= this.windowLengths[index]) {
return this.signature[index].transformWindowingInt(sample, this.maxF);
} else {
return new int[]{};
}
}
/**
* Implementation based on:
* https://github.com/scikit-learn/scikit-learn/blob/c957249/sklearn/feature_selection/univariate_selection.py#L170
*/
public void trainChiSquared(final BagOfBigrams[] bob, double p_limit) {
// Chi2 Test
LongIntHashMap featureCount = new LongIntHashMap(bob[0].bob.size());
DoubleIntHashMap classProb = new DoubleIntHashMap(10);
DoubleObjectHashMap<LongIntHashMap> observed = new DoubleObjectHashMap<>();
// count number of samples with this word
for (BagOfBigrams bagOfPattern : bob) {
double label = bagOfPattern.label;
int index = -1;
LongIntHashMap obs = null;
if ((index = observed.indexOf(label)) > -1) {
obs = observed.indexGet(index);
} else {
obs = new LongIntHashMap();
observed.put(label, obs);
}
for (LongIntCursor word : bagOfPattern.bob) {
if (word.value > 0) {
featureCount.putOrAdd(word.key, 1,1); //word.value, word.value);
// count observations per class for this feature
obs.putOrAdd(word.key, 1,1); //word.value, word.value);
}
}
}
// samples per class
for (BagOfBigrams bagOfPattern : bob) {
double label = bagOfPattern.label;
classProb.putOrAdd(label, 1, 1);
}
// p_value-squared: observed minus expected occurrence
LongDoubleHashMap chiSquareSum = new LongDoubleHashMap(featureCount.size());
for (DoubleIntCursor prob : classProb) {
double p = ((double)prob.value) / bob.length;
LongIntHashMap obs = observed.get(prob.key);
for (LongIntCursor feature : featureCount) {
double expected = p * feature.value;
double chi = obs.get(feature.key) - expected;
double newChi = chi * chi / expected;
if (newChi > 0) {
// build the sum among p_value-values of all classes
chiSquareSum.putOrAdd(feature.key, newChi, newChi);
}
}
}
LongHashSet chiSquare = new LongHashSet(featureCount.size());
ArrayList<PValueKey> values = new ArrayList<PValueKey>(featureCount.size());
for (LongDoubleCursor feature : chiSquareSum) {
double newChi = feature.value;
double pvalue = Statistics.chiSquaredProbability(newChi, classProb.keys().size()-1);
if (pvalue <= p_limit) {
chiSquare.add(feature.key);
values.add(new PValueKey(pvalue, feature.key));
}
}
// limit number of features per window size to avoid excessive features
if (values.size() > limit) {
// sort by p_value-squared value
Collections.sort(values, new Comparator<PValueKey>() {
@Override
public int compare(PValueKey o1, PValueKey o2) {
int comp = Double.compare(o1.pvalue, o2.pvalue);
if (comp != 0) { // tie breaker
return comp;
}
return Long.compare(o1.key, o2.key);
}
});
chiSquare.clear();
// use 100 unigrams and 100 bigrams
int countUnigram = 0;
int countBigram = 0;
for (int i = 0; i < values.size(); i++) {
// bigram?
long val = values.get(i).key;
if (val > (1l << 32) && countBigram < limit) {
chiSquare.add(val);
countBigram++;
}
// unigram?
else if (val < (1l << 32) && countUnigram < limit){
chiSquare.add(val);
countUnigram++;
}
if (countUnigram >= limit && countBigram >= limit) {
break;
}
}
}
// remove values
for (int j = 0; j < bob.length; j++) {
LongIntHashMap oldMap = bob[j].bob;
bob[j].bob = new LongIntHashMap();
for (LongIntCursor cursor : oldMap) {
if (chiSquare.contains(cursor.key)) {
bob[j].bob.put(cursor.key, cursor.value);
}
}
oldMap.clear();
}
}
static class PValueKey {
public double pvalue;
public long key;
public PValueKey(double pvalue, long key) {
this.pvalue = pvalue;
this.key = key;
}
@Override
public String toString() {
return "" + this.pvalue + ":" + this.key;
}
}
/**
* Create words and bi-grams for all window lengths
*/
public BagOfBigrams createBagOfPatterns(
final int[] words,
final Instance sample,
final int w, // index of used windowSize
final int wordLength) {
BagOfBigrams bagOfPatterns = new BagOfBigrams(words.length * 2, sample.classValue());
final byte usedBits = (byte) binlog(this.alphabetSize);
final long mask = (1L << (usedBits * wordLength)) - 1L;
int highestBit = binlog(Integer.highestOneBit(MAX_WINDOW_LENGTH))+1;
// create subsequences
for (int offset = 0; offset < words.length; offset++) {
long word = (words[offset] & mask) << highestBit | (long) w;
bagOfPatterns.bob.putOrAdd(word, 1, 1);
// add 2 grams
if (offset - this.windowLengths[w] >= 0) {
long prevWord = (words[offset - this.windowLengths[w]] & mask);
if (prevWord != 0) {
long newWord = (prevWord << 32 | word);
bagOfPatterns.bob.putOrAdd(newWord, 1, 1);
}
}
}
return bagOfPatterns;
}
/**
* Create words and bi-grams for all window lengths
*/
public BagOfBigrams[] createBagOfPatterns(
final int[][] wordsForWindowLength,
final Instances samples,
final int w, // index of used windowSize
final int wordLength) {
BagOfBigrams[] bagOfPatterns = new BagOfBigrams[samples.size()];
final byte usedBits = (byte) binlog(this.alphabetSize);
final long mask = (1L << (usedBits * wordLength)) - 1L;
int highestBit = binlog(Integer.highestOneBit(MAX_WINDOW_LENGTH))+1;
// iterate all samples
// and create a bag of pattern
for (int j = 0; j < samples.size(); j++) {
bagOfPatterns[j] = new BagOfBigrams(wordsForWindowLength[j].length * 2, samples.get(j).classValue());
// create subsequences
for (int offset = 0; offset < wordsForWindowLength[j].length; offset++) {
long word = (wordsForWindowLength[j][offset] & mask) << highestBit | (long) w;
bagOfPatterns[j].bob.putOrAdd(word, 1, 1);
// add 2 grams
if (offset - this.windowLengths[w] >= 0) {
long prevWord = (wordsForWindowLength[j][offset - this.windowLengths[w]] & mask);
if (prevWord != 0) {
long newWord = (prevWord << 32 | word);
bagOfPatterns[j].bob.putOrAdd(newWord, 1, 1);
}
}
}
}
return bagOfPatterns;
}
}
/**
* SFA using the ANOVA F-statistic to determine the best Fourier coefficients
* (those that best separate between class labels) as opposed to using the first
* ones.
*/
public static class SFASupervised {
// distribution of Fourier values
public transient ArrayList<ValueLabel>[] orderLine;
public int[] bestValues;
public int alphabetSize = 256;
public byte neededBits = (byte) binlog(this.alphabetSize);
public int wordLength = 0;
public boolean initialized = false;
public int maxWordLength;
// The Momentary Fourier Transform
public MFT transformation;
// use binning / bucketing
public double[][] bins;
public SFASupervised() {
}
@SuppressWarnings("unchecked")
private void init(int l, int alphabetSize) {
this.wordLength = l;
this.maxWordLength = l;
this.alphabetSize = alphabetSize;
this.initialized = true;
// l-dimensional bins
this.alphabetSize = alphabetSize;
this.neededBits = (byte) binlog(alphabetSize);
this.bins = new double[l][alphabetSize - 1];
for (double[] row : this.bins) {
Arrays.fill(row, Double.MAX_VALUE);
}
this.orderLine = new ArrayList[l];
for (int i = 0; i < this.orderLine.length; i++) {
this.orderLine[i] = new ArrayList<>();
}
}
class ValueLabel {
public double value;
public double label;
public ValueLabel(double key, Double label) {
this.value = key;
this.label = label != null? label : 0;
}
@Override
public String toString() {
return "" + this.value + ":" + this.label;
}
}
/**
* Extracts sliding windows from the time series and trains SFA based on the sliding windows.
* At the end of this call, the quantization bins are set.
*
* @param timeSeries A set of samples
* @param windowLength The queryLength of each sliding window
* @param wordLength the SFA word-queryLength
* @param symbols the SFA alphabet size
* @param normMean if set, the mean is subtracted from each sliding window
*/
public void fitWindowing(Instances timeSeries, int windowLength, int wordLength, int symbols, boolean normMean) {
this.transformation = new MFT(windowLength, normMean);
ArrayList<double[]> sa = new ArrayList<>(timeSeries.numInstances());
ArrayList<Double> labels = new ArrayList<>(timeSeries.numInstances());
for (Instance t : timeSeries) {
for (double[] data : getDisjointSequences(t, windowLength, normMean)) {
sa.add(data);
labels.add(t.classValue());
}
}
double[][] allSamples = new double[sa.size()][];
double[] allLabels = new double[sa.size()];
for (int i = 0; i < sa.size(); i++) {
allSamples[i] = sa.get(i);
allLabels[i] = labels.get(i);
}
fitTransform(allSamples, allLabels, wordLength, symbols, normMean);
}
/**
* Extracts disjoint subsequences
*/
public double[][] getDisjointSequences(Instance t, int windowSize, boolean normMean) {
// extract subsequences
int amount = instanceLength(t) / windowSize;
double[][] subsequences = new double[amount][windowSize];
double[] data = toArrayNoClass(t);
for (int i = 0; i < amount; i++) {
double[] subsequenceData = new double[windowSize];
System.arraycopy(data, i * windowSize, subsequenceData, 0, windowSize);
subsequences[i] = z_norm(subsequenceData, normMean);
}
return subsequences;
}
public double[] z_norm(double[] data, boolean normMean) {
double mean = 0.0;
double stddev = 0;
// get mean +stddev values
double var = 0;
for (double value : data) {
mean += value;
var += value * value;
}
mean /= (double) data.length;
double norm = 1.0 / ((double) data.length);
double buf = norm * var - mean * mean;
if (buf > 0) {
stddev = Math.sqrt(buf);
}