Analyzing ADM AGB models

With the introduction of ADM Gradient Boosting, we now support tree-based models in ADM as an alternative to the traditional Bayesian approach. In prediction studio, there is some information on the predictors, the model performance et cetera. However, it is also possible to export the trees themselves to analyze them further. This example demonstrates some of the info you can extract yourself, including a visualisation of the actual trees - which also allows you to check the exact ‘path’ a prediction used through each individual tree.

On a gradient boosting model page in prediction studio, you can download an export of the model under the ‘actions’ button in the top right. We’ve also shipped an example file of a pre-built tree in the data folder, and a ‘dataset’ to automatically import it from the internet. That is what we will be using for this example.

Imports

[2]:
from pdstools import datasets
from pdstools.adm import ADMTrees

Importing your own model export

To import your own model, simply feed the path to the ADMTrees class. There are no additional parameters.

[3]:
# ADMTrees("path/to/model_download.json")

For this example we will use the shipped example dataset, which you can simply import with the following line:

[4]:
Trees = datasets.sample_trees()

Exploring the ADMTrees class

The raw export has quite a lot of information stored in it, which is not all easily accessible. For example, looking at the ‘properties’ attribute, we can see the configuration of the model.

[5]:
Trees.properties
[5]:
{'factoryKey': {'configPartition': {'partition': {'pyClassName': 'Data-Decision-Request-Customer',
    'pyPurpose': 'WebClickthroughAGB'}},
  'modelPartition': {'partition': {}}},
 'configuration': {'_serialClass': 'com.pega.decision.adm.client.config.GradientBoostModelRuleConfiguration',
  '_serialVersionNumber': 2,
  'configurationId': {'configurationName': 'WebClickthroughAGB',
   'appliesToClass': 'Data-Decision-Request-Customer',
   'isPredictiveModel': False},
  'ruleSet': {'ruleSetName': 'CDHSample-Artifacts',
   'ruleSetVersion': '01-01-01'},
  'predictors': [{'name': 'Account.DaysSinceOpened', 'type': 'numeric'},
   {'name': 'Account.CurrentDateInt', 'type': 'numeric'},
   {'name': 'Customer.IsCustomerActive', 'type': 'symbolic'},
   {'name': 'Account.YTDPayments', 'type': 'numeric'},
   {'name': 'Customer.HealthMatter', 'type': 'symbolic'},
   {'name': 'Customer.LastReviewedDate', 'type': 'numeric'},
   {'name': 'Account.YTDBrokenPromises', 'type': 'numeric'},
   {'name': 'Customer.NetWealth', 'type': 'numeric'},
   {'name': 'Customer.MilitaryService', 'type': 'symbolic'},
   {'name': 'Account.DelinquencyAmount', 'type': 'numeric'},
   {'name': 'Customer.IsPrimary', 'type': 'symbolic'},
   {'name': 'Account.Role', 'type': 'symbolic'},
   {'name': 'Customer.NextReviewDate', 'type': 'symbolic'},
   {'name': 'Account.type', 'type': 'numeric'},
   {'name': 'Param.JourneyStage', 'type': 'symbolic'},
   {'name': 'Param.DaysinCurrentStage', 'type': 'numeric'},
   {'name': 'Account.InArrears', 'type': 'symbolic'},
   {'name': 'Account.PaymentNetwork', 'type': 'symbolic'},
   {'name': 'Account.AverageYearlyBalance', 'type': 'numeric'},
   {'name': 'Customer.AnnualIncome', 'type': 'numeric'},
   {'name': 'Account.YTDOverLimit', 'type': 'numeric'},
   {'name': 'Account.BonusMet', 'type': 'symbolic'},
   {'name': 'Account.CreditLine', 'type': 'numeric'},
   {'name': 'Customer.LanguagePreference', 'type': 'symbolic'},
   {'name': 'Param.Journey', 'type': 'symbolic'},
   {'name': 'Customer.RelationshipLengthDays', 'type': 'numeric'},
   {'name': 'Customer.ReviewDate', 'type': 'numeric'},
   {'name': 'Account.CurrentValue', 'type': 'numeric'},
   {'name': 'Account.Appl', 'type': 'symbolic'},
   {'name': 'Account.AccountSubType', 'type': 'symbolic'},
   {'name': 'Customer.BalanceTransaction', 'type': 'numeric'},
   {'name': 'Account.BehaviorScore', 'type': 'numeric'},
   {'name': 'Param.PriorStageInJourney', 'type': 'symbolic'},
   {'name': 'Customer.ResidentialStatus', 'type': 'symbolic'},
   {'name': 'Account.YTDDisputes', 'type': 'numeric'},
   {'name': 'Account.ProductType', 'type': 'symbolic'},
   {'name': 'Account.Active', 'type': 'symbolic'},
   {'name': 'Account.MarketSegmentID', 'type': 'numeric'},
   {'name': 'Account.CreditLineAvailable', 'type': 'numeric'},
   {'name': 'Customer.EmailOptIn', 'type': 'symbolic'},
   {'name': 'Account.LoanToValueRatio', 'type': 'numeric'},
   {'name': 'Account.YTDForeignTxnFee', 'type': 'numeric'},
   {'name': 'Customer.NoOfDependents', 'type': 'numeric'},
   {'name': 'Account.CollectionStatus', 'type': 'symbolic'},
   {'name': 'Account.AccountDescription', 'type': 'symbolic'},
   {'name': 'Account.OpenDateTime', 'type': 'numeric'},
   {'name': 'Customer.Bankruptcy', 'type': 'symbolic'},
   {'name': 'Customer.SMSOptIn', 'type': 'symbolic'},
   {'name': 'Customer.Incarceration', 'type': 'symbolic'},
   {'name': 'Customer.HasActivePaymentPlan', 'type': 'symbolic'},
   {'name': 'Account.OwnershipType', 'type': 'symbolic'},
   {'name': 'Customer.Deceased', 'type': 'symbolic'},
   {'name': 'Account.AccountType', 'type': 'symbolic'},
   {'name': 'Account.YTDInArrears', 'type': 'numeric'},
   {'name': 'Customer.Age', 'type': 'numeric'},
   {'name': 'Account.CyclesPastDue', 'type': 'numeric'},
   {'name': 'Account.RateType', 'type': 'symbolic'},
   {'name': 'Param.LastJourneyStage', 'type': 'symbolic'},
   {'name': 'Account.MaturityDate', 'type': 'numeric'},
   {'name': 'Account.NumDaysPastDue', 'type': 'numeric'},
   {'name': 'Customer.PushNotificationOptIn', 'type': 'symbolic'},
   {'name': 'Customer.NaturalDisaster', 'type': 'symbolic'},
   {'name': 'Account.AccountBalance', 'type': 'numeric'},
   {'name': 'Account.RewardType', 'type': 'symbolic'},
   {'name': 'Account.Rate', 'type': 'numeric'},
   {'name': 'Customer.pyCountryCode', 'type': 'symbolic'},
   {'name': 'Account.TotalDisputes', 'type': 'numeric'},
   {'name': 'Account.BrokenPromiseCount', 'type': 'numeric'},
   {'name': 'Customer.InHardship', 'type': 'symbolic'},
   {'name': 'Account.BonusWindowOpen', 'type': 'symbolic'},
   {'name': 'Account.YTDLatePayment', 'type': 'numeric'},
   {'name': 'Account.Status', 'type': 'symbolic'},
   {'name': 'Account.YTDInterestPaid', 'type': 'numeric'},
   {'name': 'Customer.DownloadedMobileApp', 'type': 'symbolic'},
   {'name': 'Account.UnpaidPrincipal', 'type': 'numeric'},
   {'name': 'Customer.InArrears', 'type': 'symbolic'},
   {'name': 'Account.InCollections', 'type': 'symbolic'},
   {'name': 'Account.AvgMonthlyBalance', 'type': 'numeric'},
   {'name': 'pyDirection', 'type': 'symbolic'},
   {'name': 'pyName', 'type': 'symbolic'},
   {'name': 'pyChannel', 'type': 'symbolic'},
   {'name': 'pyIssue', 'type': 'symbolic'},
   {'name': 'pyGroup', 'type': 'symbolic'}],
  'ihSummaryPredictors': [{'id': 'pyIHSummary',
    'appliesTo': 'Data-pxStrategyResult'}],
  'parameters': {'_serialClass': 'com.pega.decision.adm.client.config.GradientBoostModelParameters',
   '_serialVersionNumber': 1,
   'positiveOutcomes': ['Clicked'],
   'negativeOutcomes': ['NoResponse'],
   'isHdsEnabled': False,
   'hdsPositiveRecordingPercentage': 100.0,
   'hdsNegativeRecordingPercentage': 100.0,
   'isGlobalSamplingEnabled': False,
   'globalSamplingPercentage': 0.0,
   'dataAnalysisCount': 5000,
   'usesIHSummaries': True,
   'learningRateEta': 0.3,
   'regularizationLambda': 1.0,
   'complexityThresholdGamma': 0.0,
   'maxTrees': 50,
   'maxTreeDepth': 9,
   'minChildWeight': 1.0},
  'contextKeys': ['pyDirection', 'pyGroup', 'pyName', 'pyChannel', 'pyIssue']},
 'position': {'PID': '{"configPartition":{"partition":{"pyClassName":"Data-Decision-Request-Customer","pyPurpose":"WebClickthroughAGB"}},"modelPartition":{"partition":{}}}',
  'POSITION_MAP': {'f89812c0-01ce-11ed-e6d7-a46c4bbea146': 71566,
   '6865ff30-0180-11ed-d6d7-a18841614e4f': 40},
  'CRT_EVENTS_COUNT': 1,
  'DLT_EVENTS_COUNT': 0}}

Most of this information is not particularly useful - but for example, you can find the maximum numbef of trees, the maximum depth of the trees and the outcome to label mapping. Information about the predictors is also stored here, which is extracted in the ‘predictors’ attribute.

[6]:
Trees.predictors
[6]:
{'Account.DaysSinceOpened': 'numeric',
 'Account.CurrentDateInt': 'numeric',
 'Customer.IsCustomerActive': 'symbolic',
 'Account.YTDPayments': 'numeric',
 'Customer.HealthMatter': 'symbolic',
 'Customer.LastReviewedDate': 'numeric',
 'Account.YTDBrokenPromises': 'numeric',
 'Customer.NetWealth': 'numeric',
 'Customer.MilitaryService': 'symbolic',
 'Account.DelinquencyAmount': 'numeric',
 'Customer.IsPrimary': 'symbolic',
 'Account.Role': 'symbolic',
 'Customer.NextReviewDate': 'symbolic',
 'Account.type': 'numeric',
 'Param.JourneyStage': 'symbolic',
 'Param.DaysinCurrentStage': 'numeric',
 'Account.InArrears': 'symbolic',
 'Account.PaymentNetwork': 'symbolic',
 'Account.AverageYearlyBalance': 'numeric',
 'Customer.AnnualIncome': 'numeric',
 'Account.YTDOverLimit': 'numeric',
 'Account.BonusMet': 'symbolic',
 'Account.CreditLine': 'numeric',
 'Customer.LanguagePreference': 'symbolic',
 'Param.Journey': 'symbolic',
 'Customer.RelationshipLengthDays': 'numeric',
 'Customer.ReviewDate': 'numeric',
 'Account.CurrentValue': 'numeric',
 'Account.Appl': 'symbolic',
 'Account.AccountSubType': 'symbolic',
 'Customer.BalanceTransaction': 'numeric',
 'Account.BehaviorScore': 'numeric',
 'Param.PriorStageInJourney': 'symbolic',
 'Customer.ResidentialStatus': 'symbolic',
 'Account.YTDDisputes': 'numeric',
 'Account.ProductType': 'symbolic',
 'Account.Active': 'symbolic',
 'Account.MarketSegmentID': 'numeric',
 'Account.CreditLineAvailable': 'numeric',
 'Customer.EmailOptIn': 'symbolic',
 'Account.LoanToValueRatio': 'numeric',
 'Account.YTDForeignTxnFee': 'numeric',
 'Customer.NoOfDependents': 'numeric',
 'Account.CollectionStatus': 'symbolic',
 'Account.AccountDescription': 'symbolic',
 'Account.OpenDateTime': 'numeric',
 'Customer.Bankruptcy': 'symbolic',
 'Customer.SMSOptIn': 'symbolic',
 'Customer.Incarceration': 'symbolic',
 'Customer.HasActivePaymentPlan': 'symbolic',
 'Account.OwnershipType': 'symbolic',
 'Customer.Deceased': 'symbolic',
 'Account.AccountType': 'symbolic',
 'Account.YTDInArrears': 'numeric',
 'Customer.Age': 'numeric',
 'Account.CyclesPastDue': 'numeric',
 'Account.RateType': 'symbolic',
 'Param.LastJourneyStage': 'symbolic',
 'Account.MaturityDate': 'numeric',
 'Account.NumDaysPastDue': 'numeric',
 'Customer.PushNotificationOptIn': 'symbolic',
 'Customer.NaturalDisaster': 'symbolic',
 'Account.AccountBalance': 'numeric',
 'Account.RewardType': 'symbolic',
 'Account.Rate': 'numeric',
 'Customer.pyCountryCode': 'symbolic',
 'Account.TotalDisputes': 'numeric',
 'Account.BrokenPromiseCount': 'numeric',
 'Customer.InHardship': 'symbolic',
 'Account.BonusWindowOpen': 'symbolic',
 'Account.YTDLatePayment': 'numeric',
 'Account.Status': 'symbolic',
 'Account.YTDInterestPaid': 'numeric',
 'Customer.DownloadedMobileApp': 'symbolic',
 'Account.UnpaidPrincipal': 'numeric',
 'Customer.InArrears': 'symbolic',
 'Account.InCollections': 'symbolic',
 'Account.AvgMonthlyBalance': 'numeric',
 'pyDirection': 'symbolic',
 'pyName': 'symbolic',
 'pyChannel': 'symbolic',
 'pyIssue': 'symbolic',
 'pyGroup': 'symbolic'}

Naturally, the raw trees are stored here too. They are stored in the ‘model’ attribute, in a list with each tree in json format. Let’s look at a single tree.

[7]:
Trees.model[18]
[7]:
{'score': -0.04167241398182543,
 'gain': 4.903114150998753,
 'split': 'IH.MISSING.MISSING.Churned.pyHistoricalOutcomeCount < 1.0',
 'left': {'score': 0.0015912192864844406,
  'gain': 4.921074965276381,
  'split': 'IH.SMS.Outbound.Accept.pxLastGroupID is Missing',
  'left': {'score': 0.08708304261596726, 'gain': 0.0},
  'right': {'score': -0.19378256055857698, 'gain': 0.0}},
 'right': {'score': -0.07898210064649579,
  'gain': 2.609510949104644,
  'split': 'IH.SMS.Outbound.Accept.pyHistoricalOutcomeCount < 1.0',
  'left': {'score': -0.050025939043392705,
   'gain': 5.284463037230109,
   'split': 'pyName in { PremierChecking }',
   'left': {'score': 0.3483628622864736, 'gain': 0.0},
   'right': {'score': -0.08596541739325182, 'gain': 0.0}},
  'right': {'score': 0.22697292002283817, 'gain': 0.0}}}

Each node has a ‘score’: the contribution to the final score, over all trees. Non-leaf nodes naturally have splits, which are expressed as a string. These can be inequality, equality or set splits. For example, we may see a split on Age being smaller than 42, but also pyName being one of {P1, P2, P3, P4, P6}. If this split evaluates to True, we follow the tree to the left node. Naturally, if it evaluates to False we follow to the right node. Lastly, each split also has a gain. This describes how well that split discriminates by splitting to the left and right nodes.

Later we will revisit this tree structure, because for visualisation we need to slightly reformat it. But first, by nature of a boosting algorithm, looking at a single tree does not provide enough information to fully understand the model. For this, there are some properties of the ADMTrees class to look across trees. To start, we can call TreeStats to get an overview of the contribution of each tree to the final model.

[8]:
Trees.tree_stats.sample(5)
[8]:
shape: (5, 6)
treeIDscoredepthnsplitsgainsmeangains
i64f64i64i64list[f64]f64
37-0.01986456[31.009571, 0.889962, … 5.163168]8.823649
48-0.021955829[2.122656, 0.322753, … 1.956834]1.816619
46-0.020755821[1.330695, 0.457804, … 0.268738]1.353757
34-0.019938730[0.081435, 2.467707, … 2.298523]2.280002
26-0.020984931[1.641452, 3.552476, … 5.603293]3.817874

In TreeStats, the index is the ‘ID’ of the tree, based on its position in the order of the ‘model’ attribute. The score corresponds to the score of the top-level node of that tree, and the ‘depth’ and ‘nsplits’ describe how deep the tree is, and how many splits are performed in total. For each split, the gain is added to the list in the ‘gains’ column. The mean of all splits in a tree is computed in the ‘meangains’ column.

Some info about individual trees is also stored in attributes, such as the splits and gains for each tree.

[9]:
print(Trees.splits_per_tree[18])
print(Trees.gains_per_tree[18])
['IH.MISSING.MISSING.Churned.pyHistoricalOutcomeCount < 1.0', 'IH.SMS.Outbound.Accept.pxLastGroupID is Missing', 'IH.SMS.Outbound.Accept.pyHistoricalOutcomeCount < 1.0', 'pyName in { PremierChecking }']
[4.903114150998753, 4.921074965276381, 2.609510949104644, 5.284463037230109]
/home/runner/work/pega-datascientist-tools/pega-datascientist-tools/python/pdstools/adm/ADMTrees.py:624: DataOrientationWarning:

Row orientation inferred during DataFrame construction. Explicitly specify the orientation by passing `orient="row"` to silence this warning.

/home/runner/work/pega-datascientist-tools/pega-datascientist-tools/python/pdstools/adm/ADMTrees.py:627: MapWithoutReturnDtypeWarning:

Calling `map_elements` without specifying `return_dtype` can lead to unpredictable results. Specify `return_dtype` to silence this warning.

Variables

Now, if we are interested in the contribution and distribution of the splits per variable, we can look at the raw data in the groupedGainsPerSplit attribute, which returns a DataFrame, grouped by the split. In the ‘gains’ column you see a list of all of the gains produced by this split, and the ‘n’ column says how often this split is performed.

[10]:
Trees.grouped_gains_per_split
sys:1: MapWithoutReturnDtypeWarning:

Calling `map_elements` without specifying `return_dtype` can lead to unpredictable results. Specify `return_dtype` to silence this warning.

sys:1: MapWithoutReturnDtypeWarning:

Calling `map_elements` without specifying `return_dtype` can lead to unpredictable results. Specify `return_dtype` to silence this warning.

[10]:
shape: (379, 7)
splitpredictorgainsmeansignvaluesn
strstrlist[list[f64]]f64strobjectu32
"pyName in { AutoUsed48Months, …"pyName"[[177.064524, 95.262737, … 6.283781]]58.111616"in"{'GetAPersonalizedRateQuoteToday', 'AutoNew60Months', 'MasterCardWorld', 'AutoUsed48Months', 'UFixedRateMortgage', 'FirstMortgage30yr', 'IdentityTheftProtection', 'CreditMonitoringService', 'SignupForRewardsCard', 'IncreaseYourCreditLine', 'MasterCardGold', 'PremiumBanking', 'MoneyMarketSavingsAccount', 'UPlusProductBundles', 'HomeOwners', 'PremierChecking', 'Earn2xRewardsPoints', 'ProsAndConsOfFixedRate', 'CompleteYourCardApplicationToday', 'AutoNew84Months', 'AutoUsed84Months', 'SuperSaver', 'PlatinumRewardsCard', 'BasicChecking', 'StudentChoice', 'FirstMortgageFloat', 'IndividualRetirementAccountsIRA', 'FirstMortgageSevenOneARM', 'VisaGold', 'UPlusGold', 'AutoUsed36Months', 'FirstMortgage', 'FirstMortgageFiveOneARM', 'AMEXPersonal', 'PaymentProtection'}1
"pyName in { AutoUsed48Months, …"pyName"[[1102.556954, 153.075758, … 2.770062]]144.75059"in"{'GetAPersonalizedRateQuoteToday', 'AutoNew60Months', 'MasterCardWorld', 'AutoUsed48Months', 'UFixedRateMortgage', 'FirstMortgage30yr', 'IdentityTheftProtection', 'CreditMonitoringService', 'SignupForRewardsCard', 'IncreaseYourCreditLine', 'MasterCardGold', 'PremiumBanking', 'UPlusProductBundles', 'HomeOwners', 'Earn2xRewardsPoints', 'ProsAndConsOfFixedRate', 'CompleteYourCardApplicationToday', 'AutoNew84Months', 'AutoUsed84Months', 'SuperSaver', 'PlatinumRewardsCard', 'StudentChoice', 'FirstMortgageFloat', 'IndividualRetirementAccountsIRA', 'FirstMortgageSevenOneARM', 'VisaGold', 'UPlusGold', 'AutoUsed36Months', 'FirstMortgage', 'FirstMortgageFiveOneARM', 'AMEXPersonal', 'PaymentProtection'}1
"pyName in { UPlusGold }""pyName"[[3.648124, 5.092834, … 1.945262]]3.336998"in"{'UPlusGold'}1
"pyName in { AutoUsed48Months, …"pyName"[[1.687369, 3.857415, … 2.235231]]1.985773"in"{'AutoNew60Months', 'MasterCardWorld', 'AutoUsed48Months', 'FirstMortgage30yr', 'IncreaseYourCreditLine', 'MasterCardGold', 'PremiumBanking', 'UPlusProductBundles', 'HomeOwners', 'Earn2xRewardsPoints', 'CompleteYourCardApplicationToday', 'AutoNew84Months', 'AutoUsed84Months', 'SuperSaver', 'PlatinumRewardsCard', 'StudentChoice', 'FirstMortgageFloat', 'FirstMortgageSevenOneARM', 'VisaGold', 'UPlusGold', 'AutoUsed36Months', 'FirstMortgage', 'FirstMortgageFiveOneARM', 'AMEXPersonal'}1
"IH.Web.Inbound.Rejected.pxLast…"IH.Web.Inbound.Rejected.pxLast…[[5.216521, 9.372519, 4.885585]]6.491542"<"{'0.9332044675925926'}1
"Customer.NetWealth < 19845.0""Customer.NetWealth"[[1.250128]]1.250128"<"{'19845.0'}1
"Customer.NetWealth < 7557.0""Customer.NetWealth"[[0.180002]]0.180002"<"{'7557.0'}1
"Customer.RelationshipLengthDay…"Customer.RelationshipLengthDay…[[2.206005]]2.206005"<"{'1122.0'}1
"Customer.NetWealth < 18233.0""Customer.NetWealth"[[0.460809]]0.460809"<"{'18233.0'}1
"IH.Web.Inbound.Accepted.pxLast…"IH.Web.Inbound.Accepted.pxLast…[[1.215137]]1.215137"<"{'0.9332240277777778'}1

Raw data is sometimes useful, but it’s better to visualise. For this, simply call plotSplitsPerVariable(), which will produce a plot of the distribution of splits for each variable. Here, the orange line denotes the number of times the given split is performed, while the blue boxes display the distribution of gains corresponding to that split. By suppling a set of predictors as the ‘subset’ argument, not all predictors are plotted. For readability’s sake, we’ve filtered only on a few specific splits.

Note 1: Given that the gains can differ drastically between splits, some plots may not be very useful as-is. However, since they are Plotly plots they are interactive: hover over the data to see the raw numbers, and select a region within the plot to zoom in. Note 2: For categorical splits especially, the axis labels are typically not very readable. Even while hovering, there may be too much information. This is simply by nature of these splits. In this case, it may be more useful to look at the raw data in the groupedGainsPerSplit dataframe.

[11]:
preds = ['Customer.Age', 'Customer.LanguagePreference', 'pyName']
Trees.plot_splits_per_variable(subset=preds);

Visualising the trees

With the provided tree structures, it is also possible to visualise each tree individually. While of course each individual tree is used for scoring and thus one tree is on average only 1/50th of the total contribution, this still provides useful information of the inner workings of the algorithm. In the background, we transform the raw tree structure to a node and edges-based json structure, where each node gets an ID, and their child and parent nodes are linked

[12]:
Trees.get_tree_representation(18)
[12]:
{1: {'score': -0.04167241398182543,
  'gain': 4.903114150998753,
  'split': 'IH.MISSING.MISSING.Churned.pyHistoricalOutcomeCount < 1.0',
  'left_child': 2,
  'right_child': 5},
 2: {'score': 0.0015912192864844406,
  'parent_node': 1,
  'gain': 4.921074965276381,
  'split': 'IH.SMS.Outbound.Accept.pxLastGroupID is Missing',
  'left_child': 3,
  'right_child': 4},
 3: {'score': 0.08708304261596726, 'parent_node': 2, 'gain': 0.0},
 4: {'score': -0.19378256055857698, 'parent_node': 2, 'gain': 0.0},
 5: {'score': -0.07898210064649579,
  'parent_node': 1,
  'gain': 2.609510949104644,
  'split': 'IH.SMS.Outbound.Accept.pyHistoricalOutcomeCount < 1.0',
  'left_child': 6,
  'right_child': 9},
 6: {'score': -0.050025939043392705,
  'parent_node': 5,
  'gain': 5.284463037230109,
  'split': 'pyName in { PremierChecking }',
  'left_child': 7,
  'right_child': 8},
 7: {'score': 0.3483628622864736, 'parent_node': 6, 'gain': 0.0},
 8: {'score': -0.08596541739325182, 'parent_node': 6, 'gain': 0.0},
 9: {'score': 0.22697292002283817, 'parent_node': 5, 'gain': 0.0}}

Then, we can visualise the tree as such:

[13]:
Trees.plot_tree(18);
../_images/articles_AGBModelVisualisation_25_0.png

Plot prediction path

With this tree, of course we can also show how a tree would score a set of input data ‘x’. Simply pass a dictionary with variable:value pairs to plotTree’s “highlighted” parameter, and that path is highlighted:

[14]:
Trees.plot_tree(18, highlighted = {"IH.MISSING.MISSING.Churned.pyHistoricalOutcomeCount":2, "IH.SMS.Outbound.Accept.pyHistoricalOutcomeCount":0, "pyName": 'PremierChecking'});
../_images/articles_AGBModelVisualisation_27_0.png

Of course that also works if we define x first and then feed that as the highlighted parameter.

[15]:
x = {"IH.MISSING.MISSING.Churned.pyHistoricalOutcomeCount":2, "IH.SMS.Outbound.Accept.pyHistoricalOutcomeCount":0, "pyName": 'NotPremierChecking'}
Trees.plot_tree(18, highlighted=x);
../_images/articles_AGBModelVisualisation_29_0.png

Thus far we’ve only look at tree 18, but of course we can plot different trees as well. This is also where these visualisations aren’t always as useful, because the trees can get quite large and hard to read:

[16]:
Trees.plot_tree(30);
../_images/articles_AGBModelVisualisation_31_0.png

Note it is possible to export these trees by calling functions on the raw model, such as ‘write_png’ or ‘write_pdf’:

Trees.plotTree(4, highlighted=x).write_png('Tree.png')
Trees.plotTree(4, highlighted=x).write_pdf('Tree.pdf')

Random input data

For this demo, I want to generate some random input parameters, so a quick function to do that is this:

[17]:
def sampleX(trees):
    from random import sample

    x = {}
    for variable, values in trees.all_values_per_split.items():
        if len(values) == 1:
            if "true" in values or "false" in values:
                values = {"true", "false"}
            if isinstance(list(values)[0], str):
                try:
                    float(list(values)[0])
                except:
                    values = values.union({"Other"})
        x[variable] = sample(list(values), 1)[0]
    return x


randomX = sampleX(Trees)

Replicating scores

Lastly, with a given x and each scoring tree both stored, we can replicate the score the models would give to that customer by simply letting each tree predict a score. By calling ‘getAllVisitedNodes’, we get an overview of all visited nodes, each split that was performed and the scores contributed by each individual tree. By default this is sorted by their scores. This also gives us an idea of the relative ‘importance’ of each tree for the final prediction.

[18]:
scores = Trees.get_all_visited_nodes(randomX)
scores
[18]:
shape: (50, 4)
treeIDvisited_nodesscoresplits
i64list[i64]f64str
0[1, 2, … 7]-0.598675"[{'pyName in { AutoUsed48Month…
1[1, 21, 23]-0.464293"[{'pyGroup in { DepositAccount…
2[1, 2, … 15]-0.402499"[{'pyName in { AutoUsed48Month…
3[1, 11, … 23]-0.355028"[{'pyName in { PremierChecking…
4[1, 2, … 32]-0.23541"[{'pyName in { AutoUsed48Month…
45[1, 2, … 14]-0.066687"[{'pyName in { AutoUsed48Month…
46[1, 2]-0.069158"[{'IH.SMS.Outbound.NoResponse.…
47[1, 11, … 22]0.061456"[{'pyName in { AutoUsed48Month…
48[1, 23, … 35]0.244166"[{'pyName in { AutoUsed48Month…
49[1, 53, … 63]-0.240372"[{'Customer.NetWealth < 18233.…

Now, to get to the final score we simply sum up the scores, and then normalize them to a range between 0 and 1:

[19]:
import math

1 / (1 + math.exp(-scores["score"].sum()))
[19]:
0.007776050412656205

And to simplify this even further, simply call the ‘score’ function to get the final score.

[20]:
Trees.score(randomX)
[20]:
0.007776050412656205

Finally, we can also plot the contribution of each tree towards the final propensity of the prediction. Simply call the plotContributionPerTree function with a given x. This shows, for each individual tree, the scores, the cumulative mean of those scores and the running propensity. Here you can clearly see that the average score is quite negative, so as we would expect the final propensity is also quite low.

[21]:
Trees.plot_contribution_per_tree(randomX);

These are the current features of the ADMTrees class. As always, if you have suggestions, please do not hesitate to open a GitHub issue or pull request!