-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathautoRuntime.js
1435 lines (1225 loc) · 56 KB
/
autoRuntime.js
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
/**
* autoRuntime.js v1.0.0
* Copyright (c) 2020 by SAP SE
*/
/**
* 'define' is a function which implements the Asynchronous Module Definition API.
* If it is not already here, use amdefine module that provide it's own
* implementation to use in Node.js:
* - Browser environment : define() implementation comes from require.js
* - Node.js environment : define() implementation comes from amdefine
* --> See readme.txt > Requirements
*/
if (typeof define !== 'function') { var define = require('amdefine')(module); }
define(['./dateCoder'], function(dateCoder) {
"use strict";
/**
* Constructor of the base class for Robust Regresion and XGBoost js engines
*
* @param {object} modelDef The model definition built from the JSON export of the model
* @param {object} scoringTarget The name of the target variable
* @param {object} targetType The type of the target variable (integer, number, string, ...)
* @param {object} modelType The model type (regression, binaryClass or multiClass)
*/
function AutoEngine(modelDef, scoringTarget, targetType, modelType) {
this._model = modelDef;
this._scoringTarget = scoringTarget;
this._targetType = targetType;
this._modelType = modelType;
}
AutoEngine.prototype.Constants = {
CONTINUOUS_INFLUENCER: "continuous",
NOMINAL_INFLUENCER: "nominal",
ORDINAL_INFLUENCER: "ordinal",
STORAGE_TYPE_INTEGER: "integer",
STORAGE_TYPE_STRING: "string",
STORAGE_TYPE_NUMBER: "number",
STORAGE_TYPE_DATE: "date",
STORAGE_TYPE_DATETIME: "datetime",
INFINITY: "INF",
MINUS_INFINITY: "-INF",
BINARY_CLASSIFICATION: "binaryClass",
MULTI_CLASSIFICATION: "multiClass",
REGRESSION: "regression",
OBJECTIVE_TWEEDIE: "reg:tweedie"
};
/**
* Engine default options
*/
AutoEngine.prototype.DefaultOptions = {
"interactions": false
};
AutoEngine.prototype._getOption = function(options, option) {
var optionValue = this.DefaultOptions[option];
if (optionValue === undefined) {
throw new Error(`Unknown engine option '${option}'`);
}
if (options != null && options[option] != null) {
optionValue = options[option];
}
return optionValue;
};
/**
* Returns the information about the contribution normalization.
* It must be implemented in subclasses.
*
* @return {object} An object containing the information about the contribution normalization
* This object must contain both properties 'mean' and 'stdDev'
*/
AutoEngine.prototype._getContributionNormalization = function() {
throw new Error("_getContributionNormalization implementation is missing.");
};
/**
* Returns the information about the centered contribution normalization.
*
* @return {object} An object containing the information about the centered contribution normalization
* This object must contain both properties 'mean' and 'stdDev'
*/
AutoEngine.prototype._getCenteredContributionNormalization = function() {
throw new Error("_getCenteredContributionNormalization implementation is missing.");
};
/**
* getScore must be implemented in subclasses
*/
AutoEngine.prototype.getScore = function(selectedInfluencers) {
throw new Error("getScore implementation is missing.");
};
/**
* Returns a the normalized contribution value.
*
* @param {number} contributionValue The native contribution value
*
* @return {number} The normalized contribution value
*/
AutoEngine.prototype._getNormalizedContribution = function(influencer, variable, contributionValue, decisionClassIndex) {
// We need both: overall centered stddev and per variable contribution mean
var contributionNormalization = this._getCenteredContributionNormalization();
if ((contributionNormalization == null || contributionNormalization.stdDev == null)) {
throw new Error("Error while trying to compute the normalized contribution: overall 'stdDev' properties are missing.");
}
var varStats = influencer.contribStats;
if ((varStats == null) || (varStats.mean == null)) {
throw new Error("Error while trying to compute the normalized contribution: no 'mean' properties for " + variable + ".");
}
return (contributionValue - varStats.mean) / contributionNormalization.stdDev;
};
/**
* Builds a contribution object containing the influencer name and its contribution value.
*
* @param {string} variable The influencer name
* @param {number} contribution The native contribution value
* @param {array} interactions An array that contains the interactions with all other influencers (AutoGB only)
*/
AutoEngine.prototype._buildContribution = function(influencer, variable, contribution, interactions, decisionClassIndex) {
let contributionObject = {
"influencerName": variable,
"influencerContribution": contribution,
"normalizedContribution": this._getNormalizedContribution(influencer, variable, contribution, decisionClassIndex)
};
if (interactions) {
contributionObject.interactions = interactions;
}
return contributionObject;
};
/**
* Applies a transformation to an influencer value.
*
* @param {string} transformation The transformation to apply
* @param {string} measureValue The influencer value to which to apply the transformation
*
* @return {integer} The transformation result
*/
AutoEngine.prototype._applyTransformationOnValue = function(transformation, measureValue) {
if (transformation == null) {
// No transformation
return measureValue;
}
var date = new Date(measureValue);
return dateCoder.applyTransformation(date, transformation);
};
/**
* Determines if a given value is in a condition range.
*
* @param {object} condition The condition
* @param {number} measureValue The value to evaluate
*
* @return {boolean} True if the value is in the condition range, False otherwise
*/
AutoEngine.prototype._isInRange = function(condition, measureValue) {
var rangeMin = condition.min === this.Constants.MINUS_INFINITY ? -Infinity : condition.min;
var rangeMax = condition.max === this.Constants.INFINITY ? Infinity : condition.max;
if (measureValue > rangeMin && measureValue < rangeMax) {
return true;
}
if (condition.minIncluded && measureValue === rangeMin) {
return true;
}
if (condition.maxIncluded && measureValue === rangeMax) {
return true;
}
return false;
};
/**
* Find the matching condition for a given value.
*
* @param {array} conditions An array of conditions
* @param {number} measureValue The measure value
*
* @return {object} matching condition
*/
AutoEngine.prototype._findMeasureCondition = function(conditions, measureValue) {
for (var i = 0; i < conditions.length; i++) {
var condition = conditions[i];
if (condition.category !== null && this._isInRange(condition, measureValue)) {
return condition;
}
}
};
/**
* Converts a string value to an integer or a number (float) depending on the influencer type.
*
* @param {Object} influencer The influencer definition
* @param {string} inputValue A string value
*
* @return {number} The converted value as an integer or a number
*/
AutoEngine.prototype._convertFromString = function(influencer, inputValue) {
var convertedValue = null;
switch (influencer.storageType) {
case this.Constants.STORAGE_TYPE_INTEGER:
convertedValue = parseInt(inputValue);
break;
case this.Constants.STORAGE_TYPE_NUMBER:
convertedValue = parseFloat(inputValue);
break;
}
// Check NaN
if (isNaN(convertedValue)) {
// invalid integer/number = missing value
convertedValue = null;
}
return convertedValue;
};
/**
* Converts a string to a number or an integer depending on the influencer storage.
* If the input value is not a string, we consider it has already the right type.
*
* @param {object} influencer The influencer definition
* @param {object} inputValue The value to convert as a string or any other type
*
* @return {number} The converted value as an integer or a number
*/
AutoEngine.prototype._convertValue = function(influencer, inputValue) {
var outputValue = inputValue;
if (typeof inputValue === "string") {
var localInputValue = inputValue.trim();
if (influencer.missingString != null && localInputValue === influencer.missingString) {
// input value is empty
outputValue = null;
} else {
switch (influencer.storageType) {
case this.Constants.STORAGE_TYPE_INTEGER:
case this.Constants.STORAGE_TYPE_NUMBER:
outputValue = this._convertFromString(influencer, localInputValue);
break;
default: // string, date, datetime
outputValue = localInputValue;
}
}
}
return outputValue;
};
/**
* Extracts influencer nominal values from the influencer encoding description.
*
* @param {Object} influencer The influencer definition
*
* @return {array} An array of nominal values
*/
AutoEngine.prototype._getCategoriesFromNominal = function(influencer) {
if (influencer.valueType !== this.Constants.NOMINAL_INFLUENCER) {
throw new Error("[_getCategoriesFromNominal]: The influencer value type is " + influencer.valueType + " while a nominal influencer is expected.");
}
var allCategories = influencer.encoding.reduce(function(finalCategories, currentGroup) {
if (currentGroup.categories != null) {
currentGroup.categories.forEach(function(category) {
finalCategories.push(category);
});
} else if (currentGroup.category != null) {
finalCategories.push(currentGroup.category);
}
return finalCategories;
}, [] /* initial empty array */ );
// By default the sort() method sorts the array with the items casted to strings
if (influencer.storageType === this.Constants.STORAGE_TYPE_INTEGER) {
return allCategories.sort(function(a, b) { return a - b; });
} else {
return allCategories.sort();
}
};
/**
* Extracts ordinal integer values from the influencer definition.
*
* @param {object} influencer The influencer definition
*
* @return {array} An array of ordinal values
*/
AutoEngine.prototype._getCategoriesFromOrdinalInteger = function(influencer) {
if (influencer.valueType !== this.Constants.ORDINAL_INFLUENCER) {
throw new Error("[_getCategoriesFromOrdinalInteger]: The influencer value type is " + influencer.valueType + " while an ordinal influencer is expected.");
}
var that = this;
var allValues = influencer.encoding.reduce(function(finalValues, range) {
var minValue = null;
var maxValue = null;
if (range.min === that.Constants.MINUS_INFINITY && range.max !== that.Constants.INFINITY && range.maxIncluded === true) {
minValue = parseInt(range.max);
maxValue = minValue;
} else if (range.min !== that.Constants.MINUS_INFINITY && range.minIncluded === true && range.max === that.Constants.INFINITY) {
minValue = parseInt(range.min);
maxValue = minValue;
} else if (range.min !== that.Constants.MINUS_INFINITY || range.max !== that.Constants.INFINITY) {
minValue = parseInt(range.min);
if (range.minIncluded === false) {
minValue++;
}
maxValue = parseInt(range.max);
if (range.maxIncluded === false) {
maxValue--;
}
}
if (minValue != null && maxValue != null) {
for (var value = minValue; value <= maxValue; value++) {
if (!finalValues.includes(value)) {
finalValues.push(value);
}
}
}
return finalValues;
}, [] /* initial empty array */ );
// By default the sort() method sorts the array with the items casted to strings
return allValues.sort(function(a, b) { return a - b; });
};
/**
* Returns an object which contains some information about the model like
* the model type, the target name and the target type.
*
* @return {Object} An object containing the model information
*/
AutoEngine.prototype.getModelInfo = function() {
return {
"modelType": this._modelType,
"target": this._scoringTarget,
"targetType": this._targetType
};
};
/**
* Returns an array containing one item per influencer.
* Each item contains the following properties:
* - variable = the name of the influencer, i.e. the variable name
* - valueType = the value type, i.e. "nominal", "ordinale" or "continuous"
* - storageType = the storage type, i.e. "string", "integer", "number"
* - values = the list of distinct values from the training dataset for nominal and ordinal values
* @param {bool} ignoreDecomposition if true, derived influencers are not present in the returned array (only source influence is represented)
* @return {array} An array containing all the model influencers
*/
AutoEngine.prototype.getInfluencers = function(ignoreDecomposition=true) {
var influencers = [];
var influencerMap = {};
for (var i = 0; i < this._model.influencers.length; i++) {
var influencer = this._model.influencers[i];
if (ignoreDecomposition) {
if (influencerMap[influencer.variable]) {
// Ignore data decomposition and return one single influencer for a given date variable
continue;
}
}
var influencerDef = {
"variable": influencer.variable,
"valueType": influencer.valueType,
"storageType": influencer.storageType
};
switch (influencer.valueType) {
case this.Constants.NOMINAL_INFLUENCER:
influencerDef.values = this._getCategoriesFromNominal(influencer);
break;
case this.Constants.ORDINAL_INFLUENCER:
if (influencer.storageType === this.Constants.STORAGE_TYPE_INTEGER) {
influencerDef.values = this._getCategoriesFromOrdinalInteger(influencer);
}
break;
}
influencers.push(influencerDef);
influencerMap[influencer.variable] = influencerDef;
}
return influencers;
};
/**
* Constructor for the Robust Regression js engine.
*
* @param {object} scoringEquation The scoring equation built from the JSON export of the model
*/
function K2REngine(scoringEquation) {
AutoEngine.call(
this,
scoringEquation,
scoringEquation.equation[0].variable,
scoringEquation.equation[0].outputType,
'regression');
}
K2REngine.prototype = Object.create(AutoEngine.prototype);
/**
* Returns the information about the contribution normalization.
* (this one should not be used anymore)
*
* @return {object} An object containing the information about the contribution normalization
* This object must contain both properties 'mean' and 'stdDev'
*/
K2REngine.prototype._getContributionNormalization = function() {
return this._model.contributionNormalization;
};
/**
* Returns the information about the centered contribution normalization.
*
* @return {object} An object containing the information about the centered contribution normalization
* This object must contain both properties 'mean' and 'stdDev'
*/
K2REngine.prototype._getCenteredContributionNormalization = function() {
return this._model.centeredContributionNormalization;
};
/**
* Return the statistics of one variable contribution.
*
* @return {object} An object containing the statistics if the variable contributions
* This object must contain both properties 'mean' and 'stdDev'
*/
K2REngine.prototype._getVariableContribStats = function(variable) {
return this._model.influencers[variable].contribStats;
};
/**
* Applies the condition formula to a value.
*
* @param {oject} condition The condition object from the influencer encoding
* @param {number} value The value to which to apply the condition formula
*
* @return {number} The resulting number
*/
K2REngine.prototype._executeMeasureFormula = function(condition, value) {
if (!Number.isFinite(value))
return condition.intercept;
var tmpRes = condition.slope * value + condition.intercept;
if (condition.formula == "1.0/(1.0+exp(-(slope*x+intercept)))")
return 1.0 / (1.0 + Math.exp(-tmpRes));
if (condition.formula == "1.0/(exp(-(slope*x+intercept)))")
return 1.0 / Math.exp(-tmpRes);
if (condition.formula == "slope*x+intercept")
return tmpRes;
return null;
};
/**
* Checks if a value matches a given category.
*
* @param {string|array} category The category or an array of categories
* @param {string} dimensionValue The dimension value
*
* @return {boolean} True if the value matches the given categories
*/
K2REngine.prototype._existDimensionValue = function(category, dimensionValue) {
return dimensionValue === category ||
Array.isArray(category) &&
category.some(function(categoryValue) { return categoryValue === dimensionValue; });
};
/**
* Gets the measure contribution.
*
* @param {object} influencer The influencer definition
* @param {number} measureValue The measure value
*
* @return {number} The measure contribution
*/
K2REngine.prototype._getMeasureContribution = function(influencer, measureValue) {
if (influencer.transformation != "AsIs")
measureValue = this._applyTransformationOnValue(influencer.transformation, measureValue);
// if measureValue is null or undefined, return default value
if (measureValue === undefined || measureValue === null) {
return influencer.missingValue;
}
var conditions = influencer.encoding;
var measureCondition = this._findMeasureCondition(conditions, measureValue);
if (!measureCondition) {
return influencer.defaultValue;
}
return this._executeMeasureFormula(measureCondition, measureValue);
};
/**
* Gets the dimension contribution.
*
* @param {object} influencer The influecer object
* @param {string} dimensionValue The dimension value
*
* @return {number} The dimension contribution.
*/
K2REngine.prototype._getDimensionContribution = function(influencer, dimensionValue) {
// if dimensionValue is null or empty string or undefined, return missing value
if (dimensionValue === undefined || dimensionValue === null || dimensionValue === "") {
return influencer.missingValue;
}
var conditions = influencer.encoding;
for (var i = 0; i < conditions.length; i++) {
var condition = conditions[i];
if (this._existDimensionValue(condition.categories, dimensionValue)) {
return condition.encodedValue;
}
}
// No match = return the default value
return influencer.defaultValue;
};
/**
* Builds a map containing the influencers, with the influencer name as key.
*
* @param {array} selectedInfluencers The variable values as an array of objects { "variable": <variable name>, "value": <var value> }
*
* @return {object} The scoring equation map
*/
K2REngine.prototype._buildSelectedInfluencersMap = function(selectedInfluencers) {
return selectedInfluencers.reduce(function(selectedInfluencersMap, selectedInfluencer) {
selectedInfluencersMap[selectedInfluencer.variable] = selectedInfluencer;
return selectedInfluencersMap;
}, {});
};
/**
* Gets the score for a given observation.
*
* @param {array} selectedInfluencers The selected influencers as an array of objects containing the properties "variable" and "value"
*
* @return {Object} The score object
*/
K2REngine.prototype.getScore = function(selectedInfluencers) {
var selectedInfluencersMap = this._buildSelectedInfluencersMap(selectedInfluencers);
// build contribution array
var that = this;
var score = 0;
var contributionArray = this._model.influencers.map(function(influencer) {
var contributionValue;
var selectedInfluencer = selectedInfluencersMap[influencer.variable];
if (selectedInfluencer == null) {
// The model influencer is not part of the current case
contributionValue = influencer.missingValue;
} else {
var inputValue = that._convertValue(influencer, selectedInfluencer.value);
switch (influencer.valueType) {
case that.Constants.CONTINUOUS_INFLUENCER:
case that.Constants.ORDINAL_INFLUENCER:
contributionValue = that._getMeasureContribution(influencer, inputValue);
break;
case that.Constants.NOMINAL_INFLUENCER:
contributionValue = that._getDimensionContribution(influencer, inputValue);
break;
default:
throw new Error("Unknown Influencer Type: " + influencer.valueType);
}
}
score += contributionValue;
var influencerName = influencer.variable;
if (influencer.storageType == that.Constants.STORAGE_TYPE_DATE || influencer.storageType == that.Constants.STORAGE_TYPE_DATETIME) {
influencerName += dateCoder.getTransformationSuffix(influencer.transformation);
}
return that._buildContribution(influencer, influencerName, contributionValue, null);
});
// update score based on target condition
var targetEquation = this._model.equation.find(function(targetEquation) { return targetEquation.variable === that._scoringTarget; });
var targetCondition = this._findMeasureCondition(targetEquation.transformations, score);
var finalScore = this._executeMeasureFormula(targetCondition, score);
if (targetEquation.outputType === this.Constants.STORAGE_TYPE_INTEGER) {
/*
* To convert the score to an integer, we want the same
* behavior as the Kernel which uses a static cast that
* removes the decimal part of a number.
*/
finalScore = Math.trunc(finalScore);
}
return {
"score": finalScore,
"contributionArray": contributionArray
};
};
/**
* Constructor for the XGBoost js engine
*
* @param {object} modelDefinition The XGboost model defintion built from the JSON export of the model
*/
function KGBEngine(modelDefinition) {
AutoEngine.call(
this,
modelDefinition,
modelDefinition.info.target.variable,
modelDefinition.info.target.storage,
modelDefinition.info.modelType);
// Build a map from the feature name (F0, F1, ...) to the influencer definition
this._features = modelDefinition.influencers.reduce(function(featureMap, influencer) {
featureMap[influencer.encodedVariable] = influencer;
return featureMap;
}, { /* empty map as initial accumulator */ });
/*
* Build a map from the variable name to a list of influencer definitions:
* - in case of a date, one influencer for each data component (Year, DayOfMonth, etc)
* - a single influencer otherwise
*/
this._influencerByVariable = modelDefinition.influencers.reduce(function(influencerByVar, influencer) {
if (influencerByVar[influencer.variable] == null) {
influencerByVar[influencer.variable] = [];
}
influencerByVar[influencer.variable].push(influencer);
return influencerByVar;
}, { /* empty map as initial accumulator */ });
}
KGBEngine.prototype = Object.create(AutoEngine.prototype);
KGBEngine.prototype.KgbConstants = {
// LEAF PROPERTIES
LEAF_VALUE: 0,
LEAF_COVER: 1,
LEAF_PROP_COUNT: 2,
// NODE_PROPERTIES
NODE_FEATURE: 0,
NODE_THRESHOLD: 1,
NODE_YES_PATH: 2,
NODE_NO_PATH: 3,
NODE_MISSING: 4,
NODE_COVER: 5,
NODE_PROP_COUNT: 6
};
/**
* Returns the information about the contribution normalization.
*
* @return {object} An object containing the information about the contribution normalization
* This object must contain both properties 'mean' and 'stdDev'
*/
KGBEngine.prototype._getContributionNormalization = function() {
return this._model.info.contributionNormalization;
};
/**
* Returns the information about the centered contribution normalization.
*
* @return {object} An object containing the information about the centered contribution normalization
* This object must contain both properties 'mean' and 'stdDev'
*/
KGBEngine.prototype._getCenteredContributionNormalization = function() {
return this._model.info.centeredContributionNormalization;
};
/**
* Gets an array of initial score for each class.
*
* @return {array} An array containing the base score for each class
*/
KGBEngine.prototype._getInitialScores = function() {
var numberOfClasses = this._model.info.numberOfClasses;
var initialScoreByClass = new Array(numberOfClasses);
for (var classIndex = 0; classIndex < numberOfClasses; classIndex++) {
initialScoreByClass[classIndex] = this._model.info.baseScore;
}
return initialScoreByClass;
};
/**
* Gets the regression score from the xgboost native score.
*
* @param {array} predictionByClass An array containing a single element as the xgboost native score
*
* @return {object} An object containing the regression result as a 'score' property
*/
KGBEngine.prototype._getRegressionScore = function(predictionByClass) {
// Regression = one single class
var score = predictionByClass[0];
if (this._model.info.objective == this.Constants.OBJECTIVE_TWEEDIE) {
score = Math.exp(score);
}
if (this._model.info.target.scaling) {
score = score * this._model.info.target.scaling.stdDev + this._model.info.target.scaling.mean;
}
if (this._model.info.target.storage === this.Constants.STORAGE_TYPE_INTEGER) {
score = Math.round(score);
}
return {
"score": score
};
};
/**
* Gets the binary classification prediction from the xgboost native score.
*
* @param {array} predictionByClass An array containing a single element as the xgboost native score
*
* @return {object} An object containing the binary classification result as 'proba', 'decision' and 'score' properties
*/
KGBEngine.prototype._getBinaryClassificationDecision = function(predictionByClass) {
// Binary classification = one single class
var prediction = predictionByClass[0];
var proba = 1 / (1 + Math.exp(-prediction));
return {
"proba": proba,
"decision": proba > this._model.info.binaryDecisionThreshold ? this._model.info.target.positiveClass : this._model.info.target.negativeClass,
"score": prediction
};
};
/**
* Gets the multi classification prediction from the xgboost native score.
*
* @param {array} predictionByClass An array containing the xgboost native score for each class
*
* @return {object} An object containing the binary classification result as 'proba', 'decision' and 'classIndex' properties
*/
KGBEngine.prototype._getMultiClassificationDecision = function(predictionByClass) {
// Compute Math.exp(<pred class 0>) + ... + Math.exp(<pred class N>)
var predictionExpSum = predictionByClass.reduce(function(acc, value) { return acc + Math.exp(value); }, 0);
// Get the decision class index from the maximum probability
var prediction = {
"proba": 0,
"decision": null,
"classIndex": 0,
};
predictionByClass.forEach(function(value, index) {
var currentProba = Math.exp(value) / predictionExpSum;
if (currentProba > prediction.proba) {
prediction.proba = currentProba;
prediction.classIndex = index;
}
});
// Get the decision class itself from the index
prediction.decision = this._model.info.target.categories[prediction.classIndex].key;
return prediction;
};
/**
* Gets the cover property for a given tree node
*
* @param {array} nodes An array of tree nodes
* @param {integer} nodeIndex The index of he node from which to get the cover information
*
* @return {number} THe cover of the specified tree node
*/
KGBEngine.prototype._getCover = function(nodes, nodeIndex) {
var node = nodes[nodeIndex];
if (this._isLeaf(node)) {
return node[this.KgbConstants.LEAF_COVER];
} else {
return node[this.KgbConstants.NODE_COVER];
}
};
/**
* Checks if a given node is a leaf.
*
* @param {object} node The specified node
*
* @return {boolean} True if the node is a leaf, False otherwise
*/
KGBEngine.prototype._isLeaf = function(node) {
return (node.length === this.KgbConstants.LEAF_PROP_COUNT);
};
KGBEngine.prototype._treeShapUnwindPath = function(uniquePath, pathDepth, pathIndex) {
var nextOnePortion = uniquePath[pathDepth].weight;
var pathElement = uniquePath[pathIndex];
for (var i = pathDepth - 1; i >= 0; i--) {
if (pathElement.oneFraction != 0) {
var prevPathWeight = uniquePath[i].weight;
uniquePath[i].weight = (nextOnePortion * (pathDepth + 1)) / ((i + 1) * pathElement.oneFraction);
nextOnePortion = prevPathWeight - uniquePath[i].weight * pathElement.zeroFraction * (pathDepth - i) / (pathDepth + 1);
} else {
uniquePath[i].weight = (uniquePath[i].weight * (pathDepth + 1)) / (pathElement.zeroFraction * (pathDepth - i));
}
}
for (i = pathIndex; i < pathDepth; i++) {
uniquePath[i].parentSplitFeature = uniquePath[i + 1].parentSplitFeature;
uniquePath[i].zeroFraction = uniquePath[i + 1].zeroFraction;
uniquePath[i].oneFraction = uniquePath[i + 1].oneFraction;
}
};
KGBEngine.prototype._treeShapUnwoundPathSum = function(uniquePath, uniqueDepth, pathIndex) {
var nextOnePortion = uniquePath[uniqueDepth].weight;
var pathElement = uniquePath[pathIndex];
var total = 0;
for (var i = uniqueDepth - 1; i >= 0; i--) {
if (pathElement.oneFraction != 0) {
var tmp = (nextOnePortion * (uniqueDepth + 1)) / ((i + 1) * pathElement.oneFraction);
total += tmp;
nextOnePortion = uniquePath[i].weight - tmp * pathElement.zeroFraction * (uniqueDepth - i) / (uniqueDepth + 1);
} else {
total += (uniquePath[i].weight / pathElement.zeroFraction) / ((uniqueDepth - i) / (uniqueDepth + 1));
}
}
return total;
};
// we use a different permutation weighting for Shapley-Taylor interactions as if the total number of features was one larger
KGBEngine.prototype._treeShapUnwoundPathSumInteractions = function(uniquePath, uniqueDepth, pathIndex) {
var nextOnePortion = uniquePath[uniqueDepth].weight;
var pathElement = uniquePath[pathIndex];
var total = 0;
for (var i = uniqueDepth - 1; i >= 0; i--) {
if (pathElement.oneFraction != 0) {
var tmp = (nextOnePortion * (uniqueDepth - i)) / ((i + 1) * pathElement.oneFraction);
total += tmp;
nextOnePortion = uniquePath[i].weight - tmp * pathElement.zeroFraction;
} else {
total += uniquePath[i].weight / pathElement.zeroFraction;
}
}
return 2 * total;
};
KGBEngine.prototype._treeShapExtend = function(uniquePath, pathDepth, zeroFraction, oneFraction, parentSplitFeature) {
var itemsToRemove = uniquePath.length - pathDepth;
if (itemsToRemove > 0) {
uniquePath.splice(pathDepth);
}
uniquePath.push({
"parentSplitFeature": parentSplitFeature,
"zeroFraction": zeroFraction,
"oneFraction": oneFraction,
"weight": pathDepth == 0 ? 1 : 0
});
for (var i = pathDepth - 1; i >= 0; i--) {
uniquePath[i + 1].weight += oneFraction * uniquePath[i].weight * (i + 1) / (pathDepth + 1);
uniquePath[i].weight = zeroFraction * uniquePath[i].weight * (pathDepth - i) / (pathDepth + 1);
}
};
KGBEngine.prototype._copyPathElements = function(pathElements) {
return pathElements.map(function(pathElement) {
return {
"parentSplitFeature": pathElement.parentSplitFeature,
"zeroFraction": pathElement.zeroFraction,
"oneFraction": pathElement.oneFraction,
"weight": pathElement.weight
};
});
};
/**
* Recusrsive function to update shap values from a given decision tree
* Input parameters 'condition', 'conditionFeature' and 'conditionFraction' are
* used when calculating interactions only. In the other case, their value is
* always the same acrosss recursive calls:
* - condition = 0
* - conditionFeature = null
* - conditionFraction = 1
*/
KGBEngine.prototype._treeShapRecurse = function(
row, shapValues, nodes, nodeIndex, parentUniquePath, pathDepth,
zeroFraction, oneFraction, parentSplitFeature,
condition, conditionFeature, conditionFraction) {
var node = nodes[nodeIndex];
var localUniquePath = this._copyPathElements(parentUniquePath);
if (condition === 0 || conditionFeature !== parentSplitFeature) {
this._treeShapExtend(localUniquePath, pathDepth, zeroFraction, oneFraction, parentSplitFeature);
}
if (this._isLeaf(node)) {
for (var i = 1; i <= pathDepth; i++) {
if (condition === 0) {
var weight = this._treeShapUnwoundPathSum(localUniquePath, pathDepth, i);
} else {
var weight = this._treeShapUnwoundPathSumInteractions(localUniquePath, pathDepth, i);
}
var pathElement = localUniquePath[i];
shapValues[pathElement.parentSplitFeature] += weight * (pathElement.oneFraction - pathElement.zeroFraction) * node[this.KgbConstants.LEAF_VALUE] * conditionFraction;
}
} else {
var hotIndex = this._getHotIndex(node, row);
var coldIndex = hotIndex === node[this.KgbConstants.NODE_YES_PATH] ? node[this.KgbConstants.NODE_NO_PATH] : node[this.KgbConstants.NODE_YES_PATH];
var nodeCover = this._getCover(nodes, nodeIndex);
var hotZeroFraction = this._getCover(nodes, hotIndex) / nodeCover;
var coldZeroFraction = this._getCover(nodes, coldIndex) / nodeCover;
var incomingZeroFraction = 1;
var incomingOneFraction = 1;
var splitFeature = node[this.KgbConstants.NODE_FEATURE];
var splitPathIndex = 0;
for (; splitPathIndex <= pathDepth; splitPathIndex++) {
if (localUniquePath[splitPathIndex].parentSplitFeature === splitFeature) {
break;
}
}
if (splitPathIndex != pathDepth + 1) {
incomingZeroFraction = localUniquePath[splitPathIndex].zeroFraction;
incomingOneFraction = localUniquePath[splitPathIndex].oneFraction;
this._treeShapUnwindPath(localUniquePath, pathDepth, splitPathIndex);
pathDepth -= 1;
}
var hotConditionFraction = conditionFraction;
var coldConditionFraction = conditionFraction;
if (condition > 0 && splitFeature == conditionFeature) {
coldConditionFraction = 0;
pathDepth -= 1;
} else if (condition < 0 && splitFeature == conditionFeature) {
hotConditionFraction *= hotZeroFraction;
coldConditionFraction *= coldZeroFraction;
pathDepth -= 1;
}
this._treeShapRecurse(