View on TensorFlow.org | Run in Google Colab | View on GitHub | Download notebook |

## Introduction

Decision Forests (DF) are a large family of Machine Learning algorithms for supervised classification, regression and ranking. As the name suggests, DFs use decision trees as a building block. Today, the two most popular DF training algorithms are Random Forests and Gradient Boosted Decision Trees. Both algorithms are ensemble techniques that use multiple decision trees, but differ on how they do it.

TensorFlow Decision Forests (TF-DF) is a library for the training, evaluation, interpretation and inference of Decision Forest models.

In this tutorial, you will learn how to:

- Train a binary classification Random Forest on a dataset containing numerical, categorical and missing features.
- Evaluate the model on a test dataset.
- Prepare the model for TensorFlow Serving.
- Examine the overall structure of the model and the importance of each feature.
- Re-train the model with a different learning algorithm (Gradient Boosted Decision Trees).
- Use a different set of input features.
- Change the hyperparameters of the model.
- Preprocess the features.
- Train a model for regression.
- Train a model for ranking.

Detailed documentation is available in the user manual. The example directory contains other end-to-end examples.

## Installing TensorFlow Decision Forests

Install TF-DF by running the following cell.

`pip install tensorflow_decision_forests`

Install Wurlitzer to display the detailed training logs. This is only needed in colabs.

`pip install wurlitzer`

## Importing libraries

```
import tensorflow_decision_forests as tfdf
import os
import numpy as np
import pandas as pd
import tensorflow as tf
import math
try:
from wurlitzer import sys_pipes
except:
from colabtools.googlelog import CaptureLog as sys_pipes
from IPython.core.magic import register_line_magic
from IPython.display import Javascript
```

The hidden code cell limits the output height in colab.

```
# Check the version of TensorFlow Decision Forests
print("Found TensorFlow Decision Forests v" + tfdf.__version__)
```

Found TensorFlow Decision Forests v0.1.6

## Training a Random Forest model

In this section, we train, evaluate, analyse and export a binary classification Random Forest trained on the Palmer's Penguins dataset.

### Load the dataset and convert it in a tf.Dataset

This dataset is very small (300 examples) and stored as a .csv-like file. Therefore, use Pandas to load it.

Let's assemble the dataset into a csv file (i.e. add the header), and load it:

```
# Download the dataset
!wget -q https://storage.googleapis.com/download.tensorflow.org/data/palmer_penguins/penguins.csv -O /tmp/penguins.csv
# Load a dataset into a Pandas Dataframe.
dataset_df = pd.read_csv("/tmp/penguins.csv")
# Display the first 3 examples.
dataset_df.head(3)
```

The dataset contains a mix of numerical (e.g. `bill_depth_mm`

), categorical
(e.g. `island`

) and missing features. TF-DF supports all these feature types natively (differently than NN based models), therefore there is no need for preprocessing in the form of one-hot encoding, normalization or extra `is_present`

feature.

Labels are a bit different: Keras metrics expect integers. The label (`species`

) is stored as a string, so let's convert it into an integer.

```
# Encode the categorical label into an integer.
#
# Details:
# This stage is necessary if your classification label is represented as a
# string. Note: Keras expected classification labels to be integers.
# Name of the label column.
label = "species"
classes = dataset_df[label].unique().tolist()
print(f"Label classes: {classes}")
dataset_df[label] = dataset_df[label].map(classes.index)
```

Label classes: ['Adelie', 'Gentoo', 'Chinstrap']

Next split the dataset into training and testing:

```
# Split the dataset into a training and a testing dataset.
def split_dataset(dataset, test_ratio=0.30):
"""Splits a panda dataframe in two."""
test_indices = np.random.rand(len(dataset)) < test_ratio
return dataset[~test_indices], dataset[test_indices]
train_ds_pd, test_ds_pd = split_dataset(dataset_df)
print("{} examples in training, {} examples for testing.".format(
len(train_ds_pd), len(test_ds_pd)))
```

241 examples in training, 103 examples for testing.

And finally, convert the pandas dataframe (`pd.Dataframe`

) into tensorflow datasets (`tf.data.Dataset`

):

```
train_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_ds_pd, label=label)
test_ds = tfdf.keras.pd_dataframe_to_tf_dataset(test_ds_pd, label=label)
```

**Notes:** `pd_dataframe_to_tf_dataset`

could have converted the label to integer for you.

And, if you wanted to create the `tf.data.Dataset`

yourself, there is a couple of things to remember:

- The learning algorithms work with a one-epoch dataset and without shuffling.
- The batch size does not impact the training algorithm, but a small value might slow down reading the dataset.

### Train the model

```
%set_cell_height 300
# Specify the model.
model_1 = tfdf.keras.RandomForestModel()
# Optionally, add evaluation metrics.
model_1.compile(
metrics=["accuracy"])
# Train the model.
# "sys_pipes" is optional. It enables the display of the training logs.
with sys_pipes():
model_1.fit(x=train_ds)
```

<IPython.core.display.Javascript object> 2021-06-16 11:15:17.366494: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:176] None of the MLIR Optimization Passes are enabled (registered 2) 2021-06-16 11:15:17.368571: I tensorflow/core/platform/profile_utils/cpu_utils.cc:114] CPU Frequency: 2000175000 Hz 4/4 [==============================] - 3s 1ms/step [INFO kernel.cc:746] Start Yggdrasil model training [INFO kernel.cc:747] Collect training examples [INFO kernel.cc:392] Number of batches: 4 [INFO kernel.cc:393] Number of examples: 241 [INFO kernel.cc:769] Dataset: Number of records: 241 Number of columns: 8 Number of columns by type: NUMERICAL: 5 (62.5%) CATEGORICAL: 3 (37.5%) Columns: NUMERICAL: 5 (62.5%) 0: "bill_depth_mm" NUMERICAL num-nas:1 (0.414938%) mean:17.2271 min:13.1 max:21.5 sd:2.01345 1: "bill_length_mm" NUMERICAL num-nas:1 (0.414938%) mean:43.5587 min:32.1 max:59.6 sd:5.33806 2: "body_mass_g" NUMERICAL num-nas:1 (0.414938%) mean:4164.38 min:2700 max:6050 sd:783.775 3: "flipper_length_mm" NUMERICAL num-nas:1 (0.414938%) mean:200.321 min:178 max:231 sd:13.4865 6: "year" NUMERICAL mean:2008.05 min:2007 max:2009 sd:0.810967 CATEGORICAL: 3 (37.5%) 4: "island" CATEGORICAL has-dict vocab-size:4 zero-ood-items most-frequent:"Biscoe" 112 (46.473%) 5: "sex" CATEGORICAL num-nas:8 (3.3195%) has-dict vocab-size:3 zero-ood-items most-frequent:"female" 120 (51.5021%) 7: "__LABEL" CATEGORICAL integerized vocab-size:4 no-ood-item Terminology: nas: Number of non-available (i.e. missing) values. ood: Out of dictionary. manually-defined: Attribute which type is manually defined by the user i.e. the type was not automatically inferred. tokenized: The attribute value is obtained through tokenization. has-dict: The attribute is attached to a string dictionary e.g. a categorical attribute stored as a string. vocab-size: Number of unique values. [INFO kernel.cc:772] Configure learner [INFO kernel.cc:797] Training config: learner: "RANDOM_FOREST" features: "bill_depth_mm" features: "bill_length_mm" features: "body_mass_g" features: "flipper_length_mm" features: "island" features: "sex" features: "year" label: "__LABEL" task: CLASSIFICATION [yggdrasil_decision_forests.model.random_forest.proto.random_forest_config] { num_trees: 300 decision_tree { max_depth: 16 min_examples: 5 in_split_min_examples_check: true missing_value_policy: GLOBAL_IMPUTATION allow_na_conditions: false categorical_set_greedy_forward { sampling: 0.1 max_num_items: -1 min_item_frequency: 1 } growing_strategy_local { } categorical { cart { } } num_candidate_attributes_ratio: -1 axis_aligned_split { } internal { sorting_strategy: PRESORTED } } winner_take_all_inference: true compute_oob_performances: true compute_oob_variable_importances: false adapt_bootstrap_size_ratio_for_maximum_training_duration: false } [INFO kernel.cc:800] Deployment config: [INFO kernel.cc:837] Train model [INFO random_forest.cc:303] Training random forest on 241 example(s) and 7 feature(s). [INFO random_forest.cc:578] Training of tree 1/300 (tree index:0) done accuracy:0.930233 logloss:2.51467 [INFO random_forest.cc:578] Training of tree 11/300 (tree index:11) done accuracy:0.954167 logloss:0.372422 [INFO random_forest.cc:578] Training of tree 21/300 (tree index:21) done accuracy:0.979253 logloss:0.219489 [INFO random_forest.cc:578] Training of tree 31/300 (tree index:29) done accuracy:0.983402 logloss:0.223161 [INFO random_forest.cc:578] Training of tree 41/300 (tree index:40) done accuracy:0.983402 logloss:0.226764 [INFO random_forest.cc:578] Training of tree 51/300 (tree index:50) done accuracy:0.983402 logloss:0.224177 [INFO random_forest.cc:578] Training of tree 61/300 (tree index:62) done accuracy:0.987552 logloss:0.220807 [INFO random_forest.cc:578] Training of tree 71/300 (tree index:71) done accuracy:0.987552 logloss:0.220629 [INFO random_forest.cc:578] Training of tree 81/300 (tree index:80) done accuracy:0.987552 logloss:0.221598 [INFO random_forest.cc:578] Training of tree 91/300 (tree index:91) done accuracy:0.987552 logloss:0.220145 [INFO random_forest.cc:578] Training of tree 101/300 (tree index:99) done accuracy:0.987552 logloss:0.222572 [INFO random_forest.cc:578] Training of tree 111/300 (tree index:109) done accuracy:0.991701 logloss:0.221798 [INFO random_forest.cc:578] Training of tree 121/300 (tree index:120) done accuracy:0.987552 logloss:0.22368 [INFO random_forest.cc:578] Training of tree 131/300 (tree index:131) done accuracy:0.991701 logloss:0.221948 [INFO random_forest.cc:578] Training of tree 141/300 (tree index:139) done accuracy:0.991701 logloss:0.221793 [INFO random_forest.cc:578] Training of tree 151/300 (tree index:151) done accuracy:0.991701 logloss:0.21972 [INFO random_forest.cc:578] Training of tree 162/300 (tree index:161) done accuracy:0.991701 logloss:0.220273 [INFO random_forest.cc:578] Training of tree 172/300 (tree index:171) done accuracy:0.987552 logloss:0.219791 [INFO random_forest.cc:578] Training of tree 182/300 (tree index:181) done accuracy:0.987552 logloss:0.219373 [INFO random_forest.cc:578] Training of tree 192/300 (tree index:191) done accuracy:0.987552 logloss:0.219834 [INFO random_forest.cc:578] Training of tree 202/300 (tree index:201) done accuracy:0.987552 logloss:0.219216 [INFO random_forest.cc:578] Training of tree 212/300 (tree index:211) done accuracy:0.987552 logloss:0.0881386 [INFO random_forest.cc:578] Training of tree 222/300 (tree index:221) done accuracy:0.987552 logloss:0.0878226 [INFO random_forest.cc:578] Training of tree 232/300 (tree index:231) done accuracy:0.983402 logloss:0.0884495 [INFO random_forest.cc:578] Training of tree 242/300 (tree index:242) done accuracy:0.983402 logloss:0.0886758 [INFO random_forest.cc:578] Training of tree 252/300 (tree index:252) done accuracy:0.983402 logloss:0.0884062 [INFO random_forest.cc:578] Training of tree 262/300 (tree index:261) done accuracy:0.983402 logloss:0.0887074 [INFO random_forest.cc:578] Training of tree 272/300 (tree index:272) done accuracy:0.983402 logloss:0.0887917 [INFO random_forest.cc:578] Training of tree 283/300 (tree index:282) done accuracy:0.983402 logloss:0.0882363 [INFO random_forest.cc:578] Training of tree 293/300 (tree index:293) done accuracy:0.983402 logloss:0.0894863 [INFO random_forest.cc:578] Training of tree 300/300 (tree index:299) done accuracy:0.983402 logloss:0.0892339 [INFO random_forest.cc:645] Final OOB metrics: accuracy:0.983402 logloss:0.0892339 [INFO kernel.cc:856] Export model in log directory: /tmp/tmp0gk4mbp1 [INFO kernel.cc:864] Save model in resources [INFO kernel.cc:929] Loading model from path [INFO decision_forest.cc:590] Model loaded with 300 root(s), 4324 node(s), and 7 input feature(s). [INFO abstract_model.cc:876] Engine "RandomForestGeneric" built [INFO kernel.cc:797] Use fast generic engine

### Remarks

- No input features are specified. Therefore, all the columns will be used as
input features except for the label. The feature used by the model are shown
in the training logs and in the
`model.summary()`

. - DFs consume natively numerical, categorical, categorical-set features and missing-values. Numerical features do not need to be normalized. Categorical string values do not need to be encoded in a dictionary.
- No training hyper-parameters are specified. Therefore the default hyper-parameters will be used. Default hyper-parameters provide reasonable results in most situations.
- Calling
`compile`

on the model before the`fit`

is optional. Compile can be used to provide extra evaluation metrics. - Training algorithms do not need validation datasets. If a validation dataset is provided, it will only be used to show metrics.

## Evaluate the model

Let's evaluate our model on the test dataset.

```
evaluation = model_1.evaluate(test_ds, return_dict=True)
print()
for name, value in evaluation.items():
print(f"{name}: {value:.4f}")
```

2/2 [==============================] - 0s 3ms/step - loss: 0.0000e+00 - accuracy: 0.9709 loss: 0.0000 accuracy: 0.9709

**Remark:** The test accuracy (0.86514) is close to the Out-of-bag accuracy
(0.8672) shown in the training logs.

See the **Model Self Evaluation** section below for more evaluation methods.

## Prepare this model for TensorFlow Serving.

Export the model to the SavedModel format for later re-use e.g. TensorFlow Serving.

```
model_1.save("/tmp/my_saved_model")
```

INFO:tensorflow:Assets written to: /tmp/my_saved_model/assets INFO:tensorflow:Assets written to: /tmp/my_saved_model/assets

## Plot the model

Plotting a decision tree and following the first branches helps learning about decision forests. In some cases, plotting a model can even be used for debugging.

Because of the difference in the way they are trained, some models are more interresting to plan than others. Because of the noise injected during training and the depth of the trees, plotting Random Forest is less informative than plotting a CART or the first tree of a Gradient Boosted Tree.

Never the less, let's plot the first tree of our Random Forest model:

```
tfdf.model_plotter.plot_model_in_colab(model_1, tree_idx=0, max_depth=3)
```

The root node on the left contains the first condition (`bill_depth_mm >= 16.55`

), number of examples (240) and label distribution (the red-blue-green bar).

Examples that evaluates true to `bill_depth_mm >= 16.55`

are branched to the green path. The other ones are branched to the red path.

The deeper the node, the more `pure`

they become i.e. the label distribution is biased toward a subset of classes.

## Model tructure and feature importance

The overall structure of the model is show with `.summary()`

. You will see:

**Type**: The learning algorithm used to train the model (`Random Forest`

in our case).**Task**: The problem solved by the model (`Classification`

in our case).**Input Features**: The input features of the model.**Variable Importance**: Different measures of the importance of each feature for the model.**Out-of-bag evaluation**: The out-of-bag evaluation of the model. This is a cheap and efficient alternative to cross-validation.**Number of {trees, nodes} and other metrics**: Statistics about the structure of the decisions forests.

**Remark:** The summary's content depends on the learning algorithm (e.g.
Out-of-bag is only available for Random Forest) and the hyper-parameters (e.g.
the *mean-decrease-in-accuracy* variable importance can be disabled in the
hyper-parameters).

```
%set_cell_height 300
model_1.summary()
```

<IPython.core.display.Javascript object> Model: "random_forest_model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= Total params: 1 Trainable params: 0 Non-trainable params: 1 _________________________________________________________________ Type: "RANDOM_FOREST" Task: CLASSIFICATION Label: "__LABEL" Input Features (7): bill_depth_mm bill_length_mm body_mass_g flipper_length_mm island sex year No weights Variable Importance: NUM_NODES: 1. "bill_length_mm" 590.000000 ################ 2. "bill_depth_mm" 396.000000 ########## 3. "flipper_length_mm" 348.000000 ######### 4. "body_mass_g" 319.000000 ######## 5. "island" 319.000000 ######## 6. "sex" 30.000000 7. "year" 10.000000 Variable Importance: NUM_AS_ROOT: 1. "flipper_length_mm" 155.000000 ################ 2. "bill_length_mm" 83.000000 ######## 3. "bill_depth_mm" 49.000000 #### 4. "island" 7.000000 5. "body_mass_g" 6.000000 Variable Importance: SUM_SCORE: 1. "bill_length_mm" 24482.459121 ################ 2. "flipper_length_mm" 24084.049782 ############### 3. "island" 10515.391016 ###### 4. "bill_depth_mm" 9786.367045 ###### 5. "body_mass_g" 3046.749499 # 6. "sex" 223.179520 7. "year" 16.648722 Variable Importance: MEAN_MIN_DEPTH: 1. "__LABEL" 3.199197 ################ 2. "year" 3.183185 ############### 3. "sex" 3.154709 ############### 4. "body_mass_g" 2.645094 ########### 5. "bill_depth_mm" 2.204884 ######## 6. "island" 2.187556 ####### 7. "bill_length_mm" 1.326099 8. "flipper_length_mm" 1.209073 Winner take all: true Out-of-bag evaluation: accuracy:0.983402 logloss:0.0892339 Number of trees: 300 Total number of nodes: 4324 Number of nodes by tree: Count: 300 Average: 14.4133 StdDev: 2.98482 Min: 7 Max: 27 Ignored: 0 ---------------------------------------------- [ 7, 8) 3 1.00% 1.00% [ 8, 9) 0 0.00% 1.00% [ 9, 10) 11 3.67% 4.67% # [ 10, 11) 0 0.00% 4.67% [ 11, 12) 43 14.33% 19.00% ##### [ 12, 13) 0 0.00% 19.00% [ 13, 14) 84 28.00% 47.00% ########## [ 14, 15) 0 0.00% 47.00% [ 15, 16) 80 26.67% 73.67% ########## [ 16, 17) 0 0.00% 73.67% [ 17, 18) 52 17.33% 91.00% ###### [ 18, 19) 0 0.00% 91.00% [ 19, 20) 15 5.00% 96.00% ## [ 20, 21) 0 0.00% 96.00% [ 21, 22) 6 2.00% 98.00% # [ 22, 23) 0 0.00% 98.00% [ 23, 24) 4 1.33% 99.33% [ 24, 25) 0 0.00% 99.33% [ 25, 26) 1 0.33% 99.67% [ 26, 27] 1 0.33% 100.00% Depth by leafs: Count: 2312 Average: 3.2699 StdDev: 1.02554 Min: 1 Max: 8 Ignored: 0 ---------------------------------------------- [ 1, 2) 15 0.65% 0.65% [ 2, 3) 574 24.83% 25.48% ####### [ 3, 4) 796 34.43% 59.90% ########## [ 4, 5) 683 29.54% 89.45% ######### [ 5, 6) 196 8.48% 97.92% ## [ 6, 7) 41 1.77% 99.70% # [ 7, 8) 5 0.22% 99.91% [ 8, 8] 2 0.09% 100.00% Number of training obs by leaf: Count: 2312 Average: 31.2716 StdDev: 32.3669 Min: 5 Max: 119 Ignored: 0 ---------------------------------------------- [ 5, 10) 1137 49.18% 49.18% ########## [ 10, 16) 123 5.32% 54.50% # [ 16, 22) 63 2.72% 57.22% # [ 22, 28) 65 2.81% 60.03% # [ 28, 33) 73 3.16% 63.19% # [ 33, 39) 93 4.02% 67.21% # [ 39, 45) 106 4.58% 71.80% # [ 45, 51) 39 1.69% 73.49% [ 51, 56) 26 1.12% 74.61% [ 56, 62) 28 1.21% 75.82% [ 62, 68) 45 1.95% 77.77% [ 68, 74) 75 3.24% 81.01% # [ 74, 79) 84 3.63% 84.65% # [ 79, 85) 133 5.75% 90.40% # [ 85, 91) 81 3.50% 93.90% # [ 91, 97) 64 2.77% 96.67% # [ 97, 102) 27 1.17% 97.84% [ 102, 108) 36 1.56% 99.39% [ 108, 114) 10 0.43% 99.83% [ 114, 119] 4 0.17% 100.00% Attribute in nodes: 590 : bill_length_mm [NUMERICAL] 396 : bill_depth_mm [NUMERICAL] 348 : flipper_length_mm [NUMERICAL] 319 : island [CATEGORICAL] 319 : body_mass_g [NUMERICAL] 30 : sex [CATEGORICAL] 10 : year [NUMERICAL] Attribute in nodes with depth <= 0: 155 : flipper_length_mm [NUMERICAL] 83 : bill_length_mm [NUMERICAL] 49 : bill_depth_mm [NUMERICAL] 7 : island [CATEGORICAL] 6 : body_mass_g [NUMERICAL] Attribute in nodes with depth <= 1: 242 : flipper_length_mm [NUMERICAL] 228 : bill_length_mm [NUMERICAL] 179 : island [CATEGORICAL] 166 : bill_depth_mm [NUMERICAL] 70 : body_mass_g [NUMERICAL] Attribute in nodes with depth <= 2: 418 : bill_length_mm [NUMERICAL] 305 : flipper_length_mm [NUMERICAL] 291 : bill_depth_mm [NUMERICAL] 275 : island [CATEGORICAL] 185 : body_mass_g [NUMERICAL] 5 : sex [CATEGORICAL] 2 : year [NUMERICAL] Attribute in nodes with depth <= 3: 538 : bill_length_mm [NUMERICAL] 382 : bill_depth_mm [NUMERICAL] 329 : flipper_length_mm [NUMERICAL] 309 : island [CATEGORICAL] 288 : body_mass_g [NUMERICAL] 26 : sex [CATEGORICAL] 5 : year [NUMERICAL] Attribute in nodes with depth <= 5: 588 : bill_length_mm [NUMERICAL] 395 : bill_depth_mm [NUMERICAL] 348 : flipper_length_mm [NUMERICAL] 319 : body_mass_g [NUMERICAL] 318 : island [CATEGORICAL] 30 : sex [CATEGORICAL] 10 : year [NUMERICAL] Condition type in nodes: 1663 : HigherCondition 349 : ContainsBitmapCondition Condition type in nodes with depth <= 0: 293 : HigherCondition 7 : ContainsBitmapCondition Condition type in nodes with depth <= 1: 706 : HigherCondition 179 : ContainsBitmapCondition Condition type in nodes with depth <= 2: 1201 : HigherCondition 280 : ContainsBitmapCondition Condition type in nodes with depth <= 3: 1542 : HigherCondition 335 : ContainsBitmapCondition Condition type in nodes with depth <= 5: 1660 : HigherCondition 348 : ContainsBitmapCondition Training OOB: trees: 1, Out-of-bag evaluation: accuracy:0.930233 logloss:2.51467 trees: 11, Out-of-bag evaluation: accuracy:0.954167 logloss:0.372422 trees: 21, Out-of-bag evaluation: accuracy:0.979253 logloss:0.219489 trees: 31, Out-of-bag evaluation: accuracy:0.983402 logloss:0.223161 trees: 41, Out-of-bag evaluation: accuracy:0.983402 logloss:0.226764 trees: 51, Out-of-bag evaluation: accuracy:0.983402 logloss:0.224177 trees: 61, Out-of-bag evaluation: accuracy:0.987552 logloss:0.220807 trees: 71, Out-of-bag evaluation: accuracy:0.987552 logloss:0.220629 trees: 81, Out-of-bag evaluation: accuracy:0.987552 logloss:0.221598 trees: 91, Out-of-bag evaluation: accuracy:0.987552 logloss:0.220145 trees: 101, Out-of-bag evaluation: accuracy:0.987552 logloss:0.222572 trees: 111, Out-of-bag evaluation: accuracy:0.991701 logloss:0.221798 trees: 121, Out-of-bag evaluation: accuracy:0.987552 logloss:0.22368 trees: 131, Out-of-bag evaluation: accuracy:0.991701 logloss:0.221948 trees: 141, Out-of-bag evaluation: accuracy:0.991701 logloss:0.221793 trees: 151, Out-of-bag evaluation: accuracy:0.991701 logloss:0.21972 trees: 162, Out-of-bag evaluation: accuracy:0.991701 logloss:0.220273 trees: 172, Out-of-bag evaluation: accuracy:0.987552 logloss:0.219791 trees: 182, Out-of-bag evaluation: accuracy:0.987552 logloss:0.219373 trees: 192, Out-of-bag evaluation: accuracy:0.987552 logloss:0.219834 trees: 202, Out-of-bag evaluation: accuracy:0.987552 logloss:0.219216 trees: 212, Out-of-bag evaluation: accuracy:0.987552 logloss:0.0881386 trees: 222, Out-of-bag evaluation: accuracy:0.987552 logloss:0.0878226 trees: 232, Out-of-bag evaluation: accuracy:0.983402 logloss:0.0884495 trees: 242, Out-of-bag evaluation: accuracy:0.983402 logloss:0.0886758 trees: 252, Out-of-bag evaluation: accuracy:0.983402 logloss:0.0884062 trees: 262, Out-of-bag evaluation: accuracy:0.983402 logloss:0.0887074 trees: 272, Out-of-bag evaluation: accuracy:0.983402 logloss:0.0887917 trees: 283, Out-of-bag evaluation: accuracy:0.983402 logloss:0.0882363 trees: 293, Out-of-bag evaluation: accuracy:0.983402 logloss:0.0894863 trees: 300, Out-of-bag evaluation: accuracy:0.983402 logloss:0.0892339

The information in `summary`

are all available programatically using the model inspector:

```
# The input features
model_1.make_inspector().features()
```

["bill_depth_mm" (1; #0), "bill_length_mm" (1; #1), "body_mass_g" (1; #2), "flipper_length_mm" (1; #3), "island" (4; #4), "sex" (4; #5), "year" (1; #6)]

```
# The feature importances
model_1.make_inspector().variable_importances()
```

{'NUM_AS_ROOT': [("flipper_length_mm" (1; #3), 155.0), ("bill_length_mm" (1; #1), 83.0), ("bill_depth_mm" (1; #0), 49.0), ("island" (4; #4), 7.0), ("body_mass_g" (1; #2), 6.0)]}

The content of the summary and the inspector depends on the learning algorithm (`tfdf.keras.RandomForestModel`

in this case) and its hyper-parameters (e.g. `compute_oob_variable_importances=True`

will trigger the computation of Out-of-bag variable importances for the Random Forest learner).

## Model Self Evaluation

During training TFDF models can self evaluate even if no validation dataset is provided to the `fit()`

method. The exact logic depends on the model. For example, Random Forest will use Out-of-bag evaluation while Gradient Boosted Trees will use internal train-validation.

The model self evaluation is available with the inspector's `evaluation()`

:

```
model_1.make_inspector().evaluation()
```

Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.08923386946258703, rmse=None, ndcg=None, aucs=None)

## Plotting the training logs

The training logs show the quality of the model (e.g. accuracy evaluated on the out-of-bag or validation dataset) according to the number of trees in the model. These logs are helpful to study the balance between model size and model quality.

The logs are available in multiple ways:

- Displayed in during training if
`fit()`

is wrapped in`with sys_pipes():`

(see example above). - At the end of the model summary i.e.
`model.summary()`

(see example above). - Programmatically, using the model inspector i.e.
`model.make_inspector().training_logs()`

. - Using TensorBoard

Let's try the options 2 and 3:

```
%set_cell_height 150
model_1.make_inspector().training_logs()
```

<IPython.core.display.Javascript object> [TrainLog(num_trees=1, evaluation=Evaluation(num_examples=86, accuracy=0.9302325581395349, loss=2.5146733661030614, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=11, evaluation=Evaluation(num_examples=240, accuracy=0.9541666666666667, loss=0.3724224512775739, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=21, evaluation=Evaluation(num_examples=241, accuracy=0.979253112033195, loss=0.2194892905992591, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=31, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.2231612827211495, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=41, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.2267641667817638, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=51, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.22417666814077444, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=61, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.22080709267392198, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=71, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.2206288905605612, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=81, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.22159794349362494, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=91, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.22014530575003366, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=101, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.22257189703061867, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=111, evaluation=Evaluation(num_examples=241, accuracy=0.991701244813278, loss=0.22179837512524792, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=121, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.22367983726452248, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=131, evaluation=Evaluation(num_examples=241, accuracy=0.991701244813278, loss=0.22194802026067284, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=141, evaluation=Evaluation(num_examples=241, accuracy=0.991701244813278, loss=0.22179325376308806, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=151, evaluation=Evaluation(num_examples=241, accuracy=0.991701244813278, loss=0.21971970364157714, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=162, evaluation=Evaluation(num_examples=241, accuracy=0.991701244813278, loss=0.22027267315869387, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=172, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.21979096994824182, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=182, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.21937323502686137, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=192, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.21983355328564327, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=202, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.2192158271825227, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=212, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.0881385774394165, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=222, evaluation=Evaluation(num_examples=241, accuracy=0.9875518672199171, loss=0.08782261303583493, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=232, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.08844949056576025, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=242, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.08867583464042775, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=252, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.08840619923771045, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=262, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.08870735831357755, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=272, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.08879169083250632, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=283, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.08823629988828882, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=293, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.08948630657959034, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=300, evaluation=Evaluation(num_examples=241, accuracy=0.983402489626556, loss=0.08923386946258703, rmse=None, ndcg=None, aucs=None))]

Let's plot it:

```
import matplotlib.pyplot as plt
logs = model_1.make_inspector().training_logs()
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot([log.num_trees for log in logs], [log.evaluation.accuracy for log in logs])
plt.xlabel("Number of trees")
plt.ylabel("Accuracy (out-of-bag)")
plt.subplot(1, 2, 2)
plt.plot([log.num_trees for log in logs], [log.evaluation.loss for log in logs])
plt.xlabel("Number of trees")
plt.ylabel("Logloss (out-of-bag)")
plt.show()
```

This dataset is small. You can see the model converging almost immediately.

Let's use TensorBoard:

```
# This cell start TensorBoard that can be slow.
# Load the TensorBoard notebook extension
%load_ext tensorboard
# Google internal version
# %load_ext google3.learning.brain.tensorboard.notebook.extension
```

`# Clear existing results (if any)`

`rm -fr "/tmp/tensorboard_logs"`

```
# Export the meta-data to tensorboard.
model_1.make_inspector().export_to_tensorboard("/tmp/tensorboard_logs")
```

```
# Start a tensorboard instance.
%tensorboard --logdir "/tmp/tensorboard_logs"
```

## Re-train the model with a different learning algorithm

The learning algorithm is defined by the model class. For
example, `tfdf.keras.RandomForestModel()`

trains a Random Forest, while
`tfdf.keras.GradientBoostedTreesModel()`

trains a Gradient Boosted Decision
Trees.

The learning algorithms are listed by calling `tfdf.keras.get_all_models()`

or in the
learner list.

```
tfdf.keras.get_all_models()
```

[tensorflow_decision_forests.keras.RandomForestModel, tensorflow_decision_forests.keras.GradientBoostedTreesModel, tensorflow_decision_forests.keras.CartModel]

The description of the learning algorithms and their hyper-parameters are also available in the API reference and builtin help:

```
# help works anywhere.
help(tfdf.keras.RandomForestModel)
# ? only works in ipython or notebooks, it usually opens on a separate panel.
tfdf.keras.RandomForestModel?
```

Help on class RandomForestModel in module tensorflow_decision_forests.keras: class RandomForestModel(tensorflow_decision_forests.keras.wrappers.RandomForestModel) | RandomForestModel(*args, **kwargs) | | Random Forest learning algorithm. | | A Random Forest (https://www.stat.berkeley.edu/~breiman/randomforest2001.pdf) | is a collection of deep CART decision trees trained independently and without | pruning. Each tree is trained on a random subset of the original training | dataset (sampled with replacement). | | The algorithm is unique in that it is robust to overfitting, even in extreme | cases e.g. when there is more features than training examples. | | It is probably the most well-known of the Decision Forest training | algorithms. | | Usage example: | | ```python | import tensorflow_decision_forests as tfdf | import pandas as pd | | dataset = pd.read_csv("project/dataset.csv") | tf_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(dataset, label="my_label") | | model = tfdf.keras.RandomForestModel() | model.fit(tf_dataset) | | print(model.summary()) | ``` | | Attributes: | task: Task to solve (e.g. Task.CLASSIFICATION, Task.REGRESSION, | Task.RANKING). | features: Specify the list and semantic of the input features of the model. | If not specified, all the available features will be used. If specified | and if `exclude_non_specified_features=True`, only the features in | `features` will be used by the model. If "preprocessing" is used, | `features` corresponds to the output of the preprocessing. In this case, | it is recommended for the preprocessing to return a dictionary of tensors. | exclude_non_specified_features: If true, only use the features specified in | `features`. | preprocessing: Functional keras model or @tf.function to apply on the input | feature before the model to train. This preprocessing model can consume | and return tensors, list of tensors or dictionary of tensors. If | specified, the model only "sees" the output of the preprocessing (and not | the raw input). Can be used to prepare the features or to stack multiple | models on top of each other. Unlike preprocessing done in the tf.dataset, | the operation in "preprocessing" are serialized with the model. | ranking_group: Only for `task=Task.RANKING`. Name of a tf.string feature that | identifies queries in a query/document ranking task. The ranking group | is not added automatically for the set of features if | `exclude_non_specified_features=false`. | temp_directory: Temporary directory used during the training. The space | required depends on the learner. In many cases, only a temporary copy of a | model will be there. | verbose: If true, displays information about the training. | hyperparameter_template: Override the default value of the hyper-parameters. | If None (default) the default parameters of the library are used. If set, | `default_hyperparameter_template` refers to one of the following | preconfigured hyper-parameter sets. Those sets outperforms the default | hyper-parameters (either generally or in specific scenarios). | You can omit the version (e.g. remove "@v5") to use the last version of | the template. In this case, the hyper-parameter can change in between | releases (not recommended for training in production). | - better_default@v1: A configuration that is generally better than the | default parameters without being more expensive. The parameters are: | winner_take_all=True. | - benchmark_rank1@v1: Top ranking hyper-parameters on our benchmark | slightly modified to run in reasonable time. The parameters are: | winner_take_all=True, categorical_algorithm="RANDOM", | split_axis="SPARSE_OBLIQUE", sparse_oblique_normalization="MIN_MAX", | sparse_oblique_num_projections_exponent=1.0. | | advanced_arguments: Advanced control of the model that most users won't need | to use. See `AdvancedArguments` for details. | adapt_bootstrap_size_ratio_for_maximum_training_duration: Control how the | maximum training duration (if set) is applied. If false, the training | stop when the time is used. If true, adapts the size of the sampled | dataset used to train each tree such that `num_trees` will train within | `maximum_training_duration`. Has no effect if there is no maximum | training duration specified. Default: False. | allow_na_conditions: If true, the tree training evaluates conditions of the | type `X is NA` i.e. `X is missing`. Default: False. | categorical_algorithm: How to learn splits on categorical attributes. | - `CART`: CART algorithm. Find categorical splits of the form "value \\in | mask". The solution is exact for binary classification, regression and | ranking. It is approximated for multi-class classification. This is a | good first algorithm to use. In case of overfitting (very small | dataset, large dictionary), the "random" algorithm is a good | alternative. | - `ONE_HOT`: One-hot encoding. Find the optimal categorical split of the | form "attribute == param". This method is similar (but more efficient) | than converting converting each possible categorical value into a | boolean feature. This method is available for comparison purpose and | generally performs worse than other alternatives. | - `RANDOM`: Best splits among a set of random candidate. Find the a | categorical split of the form "value \\in mask" using a random search. | This solution can be seen as an approximation of the CART algorithm. | This method is a strong alternative to CART. This algorithm is inspired | from section "5.1 Categorical Variables" of "Random Forest", 2001. | Default: "CART". | categorical_set_split_greedy_sampling: For categorical set splits e.g. | texts. Probability for a categorical value to be a candidate for the | positive set. The sampling is applied once per node (i.e. not at every | step of the greedy optimization). Default: 0.1. | categorical_set_split_max_num_items: For categorical set splits e.g. texts. | Maximum number of items (prior to the sampling). If more items are | available, the least frequent items are ignored. Changing this value is | similar to change the "max_vocab_count" before loading the dataset, with | the following exception: With `max_vocab_count`, all the remaining items | are grouped in a special Out-of-vocabulary item. With `max_num_items`, | this is not the case. Default: -1. | categorical_set_split_min_item_frequency: For categorical set splits e.g. | texts. Minimum number of occurrences of an item to be considered. | Default: 1. | compute_oob_performances: If true, compute the Out-of-bag evaluation (then | available in the summary and model inspector). This evaluation is a cheap | alternative to cross-validation evaluation. Default: True. | compute_oob_variable_importances: If true, compute the Out-of-bag feature | importance (then available in the summary and model inspector). Note that | the OOB feature importance can be expensive to compute. Default: False. | growing_strategy: How to grow the tree. | - `LOCAL`: Each node is split independently of the other nodes. In other | words, as long as a node satisfy the splits "constraints (e.g. maximum | depth, minimum number of observations), the node will be split. This is | the "classical" way to grow decision trees. | - `BEST_FIRST_GLOBAL`: The node with the best loss reduction among all | the nodes of the tree is selected for splitting. This method is also | called "best first" or "leaf-wise growth". See "Best-first decision | tree learning", Shi and "Additive logistic regression : A statistical | view of boosting", Friedman for more details. Default: "LOCAL". | in_split_min_examples_check: Whether to check the `min_examples` constraint | in the split search (i.e. splits leading to one child having less than | `min_examples` examples are considered invalid) or before the split | search (i.e. a node can be derived only if it contains more than | `min_examples` examples). If false, there can be nodes with less than | `min_examples` training examples. Default: True. | max_depth: Maximum depth of the tree. `max_depth=1` means that all trees | will be roots. Negative values are ignored. Default: 16. | max_num_nodes: Maximum number of nodes in the tree. Set to -1 to disable | this limit. Only available for `growing_strategy=BEST_FIRST_GLOBAL`. | Default: None. | maximum_training_duration_seconds: Maximum training duration of the model | expressed in seconds. Each learning algorithm is free to use this | parameter at it sees fit. Enabling maximum training duration makes the | model training non-deterministic. Default: -1.0. | min_examples: Minimum number of examples in a node. Default: 5. | missing_value_policy: Method used to handle missing attribute values. | - `GLOBAL_IMPUTATION`: Missing attribute values are imputed, with the | mean (in case of numerical attribute) or the most-frequent-item (in | case of categorical attribute) computed on the entire dataset (i.e. the | information contained in the data spec). | - `LOCAL_IMPUTATION`: Missing attribute values are imputed with the mean | (numerical attribute) or most-frequent-item (in the case of categorical | attribute) evaluated on the training examples in the current node. | - `RANDOM_LOCAL_IMPUTATION`: Missing attribute values are imputed from | randomly sampled values from the training examples in the current node. | This method was proposed by Clinic et al. in "Random Survival Forests" | (https://projecteuclid.org/download/pdfview_1/euclid.aoas/1223908043). | Default: "GLOBAL_IMPUTATION". | num_candidate_attributes: Number of unique valid attributes tested for each | node. An attribute is valid if it has at least a valid split. If | `num_candidate_attributes=0`, the value is set to the classical default | value for Random Forest: `sqrt(number of input attributes)` in case of | classification and `number_of_input_attributes / 3` in case of | regression. If `num_candidate_attributes=-1`, all the attributes are | tested. Default: 0. | num_candidate_attributes_ratio: Ratio of attributes tested at each node. If | set, it is equivalent to `num_candidate_attributes = | number_of_input_features x num_candidate_attributes_ratio`. The possible | values are between ]0, and 1] as well as -1. If not set or equal to -1, | the `num_candidate_attributes` is used. Default: -1.0. | num_trees: Number of individual decision trees. Increasing the number of | trees can increase the quality of the model at the expense of size, | training speed, and inference latency. Default: 300. | sorting_strategy: How are sorted the numerical features in order to find | the splits | - PRESORT: The features are pre-sorted at the start of the training. This | solution is faster but consumes much more memory than IN_NODE. | - IN_NODE: The features are sorted just before being used in the node. | This solution is slow but consumes little amount of memory. | . Default: "PRESORT". | sparse_oblique_normalization: For sparse oblique splits i.e. | `split_axis=SPARSE_OBLIQUE`. Normalization applied on the features, | before applying the sparse oblique projections. | - `NONE`: No normalization. | - `STANDARD_DEVIATION`: Normalize the feature by the estimated standard | deviation on the entire train dataset. Also known as Z-Score | normalization. | - `MIN_MAX`: Normalize the feature by the range (i.e. max-min) estimated | on the entire train dataset. Default: None. | sparse_oblique_num_projections_exponent: For sparse oblique splits i.e. | `split_axis=SPARSE_OBLIQUE`. Controls of the number of random projections | to test at each node as `num_features^num_projections_exponent`. Default: | None. | sparse_oblique_projection_density_factor: For sparse oblique splits i.e. | `split_axis=SPARSE_OBLIQUE`. Controls of the number of random projections | to test at each node as `num_features^num_projections_exponent`. Default: | None. | split_axis: What structure of split to consider for numerical features. | - `AXIS_ALIGNED`: Axis aligned splits (i.e. one condition at a time). | This is the "classical" way to train a tree. Default value. | - `SPARSE_OBLIQUE`: Sparse oblique splits (i.e. splits one a small number | of features) from "Sparse Projection Oblique Random Forests", Tomita et | al., 2020. Default: "AXIS_ALIGNED". | winner_take_all: Control how classification trees vote. If true, each tree | votes for one class. If false, each tree vote for a distribution of | classes. winner_take_all_inference=false is often preferable. Default: | True. | | Method resolution order: | RandomForestModel | tensorflow_decision_forests.keras.wrappers.RandomForestModel | tensorflow_decision_forests.keras.core.CoreModel | tensorflow.python.keras.engine.training.Model | tensorflow.python.keras.engine.base_layer.Layer | tensorflow.python.module.module.Module | tensorflow.python.training.tracking.tracking.AutoTrackable | tensorflow.python.training.tracking.base.Trackable | tensorflow.python.keras.utils.version_utils.LayerVersionSelector | tensorflow.python.keras.utils.version_utils.ModelVersionSelector | builtins.object | | Methods inherited from tensorflow_decision_forests.keras.wrappers.RandomForestModel: | | __init__ = wrapper(*args, **kargs) | | ---------------------------------------------------------------------- | Static methods inherited from tensorflow_decision_forests.keras.wrappers.RandomForestModel: | | predefined_hyperparameters() -> List[tensorflow_decision_forests.keras.core.HyperParameterTemplate] | Returns a better than default set of hyper-parameters. | | They can be used directly with the `hyperparameter_template` argument of the | model constructor. | | These hyper-parameters outperforms the default hyper-parameters (either | generally or in specific scenarios). Like default hyper-parameters, existing | pre-defined hyper-parameters cannot change. | | ---------------------------------------------------------------------- | Methods inherited from tensorflow_decision_forests.keras.core.CoreModel: | | call(self, inputs, training=False) | Inference of the model. | | This method is used for prediction and evaluation of a trained model. | | Args: | inputs: Input tensors. | training: Is the model being trained. Always False. | | Returns: | Model predictions. | | compile(self, metrics=None) | Configure the model for training. | | Unlike for most Keras model, calling "compile" is optional before calling | "fit". | | Args: | metrics: Metrics to report during training. | | Raises: | ValueError: Invalid arguments. | | evaluate(self, *args, **kwargs) | Returns the loss value & metrics values for the model. | | See details on `keras.Model.evaluate`. | | Args: | *args: Passed to `keras.Model.evaluate`. | **kwargs: Passed to `keras.Model.evaluate`. Scalar test loss (if the | model has a single output and no metrics) or list of scalars (if the | model has multiple outputs and/or metrics). See details in | `keras.Model.evaluate`. | | fit(self, x=None, y=None, callbacks=None, **kwargs) -> tensorflow.python.keras.callbacks.History | Trains the model. | | The following dataset formats are supported: | | 1. "x" is a tf.data.Dataset containing a tuple "(features, labels)". | "features" can be a dictionary a tensor, a list of tensors or a | dictionary of tensors (recommended). "labels" is a tensor. | | 2. "x" is a tensor, list of tensors or dictionary of tensors containing | the input features. "y" is a tensor. | | 3. "x" is a numpy-array, list of numpy-arrays or dictionary of | numpy-arrays containing the input features. "y" is a numpy-array. | | Pandas Dataframe can be consumed with "dataframe_to_tf_dataset": | dataset = pandas.Dataframe(...) | model.fit(pd_dataframe_to_tf_dataset(dataset, label="my_label")) | | Args: | x: Training dataset (See details above for the supported formats). | y: Label of the training dataset. Only used if "x" does not contains the | labels. | callbacks: Callbacks triggered during the training. | **kwargs: Arguments passed to the core keras model's fit. | | Returns: | A `History` object. Its `History.history` attribute is not yet | implemented for decision forests algorithms, and will return empty. | All other fields are filled as usual for `Keras.Mode.fit()`. | | make_inspector(self) -> tensorflow_decision_forests.component.inspector.inspector.AbstractInspector | Creates an inspector to access the internal model structure. | | Usage example: | | ```python | inspector = model.make_inspector() | print(inspector.num_trees()) | print(inspector.variable_importances()) | ``` | | Returns: | A model inspector. | | make_predict_function(self) | Prediction of the model (!= evaluation). | | make_test_function(self) | Predictions for evaluation. | | summary(self, line_length=None, positions=None, print_fn=None) | Shows information about the model. | | train_step(self, data) | Collects training examples. | | yggdrasil_model_path_tensor(self) -> Union[tensorflow.python.framework.ops.Tensor, NoneType] | Gets the path to yggdrasil model, if available. | | The effective path can be obtained with: | | ```python | yggdrasil_model_path_tensor().numpy().decode("utf-8") | ``` | | Returns: | Path to the Yggdrasil model. | | ---------------------------------------------------------------------- | Methods inherited from tensorflow.python.keras.engine.training.Model: | | __setattr__(self, name, value) | Support self.foo = trackable syntax. | | build(self, input_shape) | Builds the model based on input shapes received. | | This is to be used for subclassed models, which do not know at instantiation | time what their inputs look like. | | This method only exists for users who want to call `model.build()` in a | standalone way (as a substitute for calling the model on real data to | build it). It will never be called by the framework (and thus it will | never throw unexpected errors in an unrelated workflow). | | Args: | input_shape: Single tuple, TensorShape, or list/dict of shapes, where | shapes are tuples, integers, or TensorShapes. | | Raises: | ValueError: | 1. In case of invalid user-provided data (not of type tuple, | list, TensorShape, or dict). | 2. If the model requires call arguments that are agnostic | to the input shapes (positional or kwarg in call signature). | 3. If not all layers were properly built. | 4. If float type inputs are not supported within the layers. | | In each of these cases, the user should build their model by calling it | on real tensor data. | | evaluate_generator(self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0) | Evaluates the model on a data generator. | | DEPRECATED: | `Model.evaluate` now supports generators, so there is no longer any need | to use this endpoint. | | fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0) | Fits the model on data yielded batch-by-batch by a Python generator. | | DEPRECATED: | `Model.fit` now supports generators, so there is no longer any need to use | this endpoint. | | get_config(self) | Returns the config of the layer. | | A layer config is a Python dictionary (serializable) | containing the configuration of a layer. | The same layer can be reinstantiated later | (without its trained weights) from this configuration. | | The config of a layer does not include connectivity | information, nor the layer class name. These are handled | by `Network` (one layer of abstraction above). | | Note that `get_config()` does not guarantee to return a fresh copy of dict | every time it is called. The callers should make a copy of the returned dict | if they want to modify it. | | Returns: | Python dictionary. | | get_layer(self, name=None, index=None) | Retrieves a layer based on either its name (unique) or index. | | If `name` and `index` are both provided, `index` will take precedence. | Indices are based on order of horizontal graph traversal (bottom-up). | | Args: | name: String, name of layer. | index: Integer, index of layer. | | Returns: | A layer instance. | | Raises: | ValueError: In case of invalid layer name or index. | | get_weights(self) | Retrieves the weights of the model. | | Returns: | A flat list of Numpy arrays. | | load_weights(self, filepath, by_name=False, skip_mismatch=False, options=None) | Loads all layer weights, either from a TensorFlow or an HDF5 weight file. | | If `by_name` is False weights are loaded based on the network's | topology. This means the architecture should be the same as when the weights | were saved. Note that layers that don't have weights are not taken into | account in the topological ordering, so adding or removing layers is fine as | long as they don't have weights. | | If `by_name` is True, weights are loaded into layers only if they share the | same name. This is useful for fine-tuning or transfer-learning models where | some of the layers have changed. | | Only topological loading (`by_name=False`) is supported when loading weights | from the TensorFlow format. Note that topological loading differs slightly | between TensorFlow and HDF5 formats for user-defined classes inheriting from | `tf.keras.Model`: HDF5 loads based on a flattened list of weights, while the | TensorFlow format loads based on the object-local names of attributes to | which layers are assigned in the `Model`'s constructor. | | Args: | filepath: String, path to the weights file to load. For weight files in | TensorFlow format, this is the file prefix (the same as was passed | to `save_weights`). This can also be a path to a SavedModel | saved from `model.save`. | by_name: Boolean, whether to load weights by name or by topological | order. Only topological loading is supported for weight files in | TensorFlow format. | skip_mismatch: Boolean, whether to skip loading of layers where there is | a mismatch in the number of weights, or a mismatch in the shape of | the weight (only valid when `by_name=True`). | options: Optional `tf.train.CheckpointOptions` object that specifies | options for loading weights. | | Returns: | When loading a weight file in TensorFlow format, returns the same status | object as `tf.train.Checkpoint.restore`. When graph building, restore | ops are run automatically as soon as the network is built (on first call | for user-defined classes inheriting from `Model`, immediately if it is | already built). | | When loading weights in HDF5 format, returns `None`. | | Raises: | ImportError: If h5py is not available and the weight file is in HDF5 | format. | ValueError: If `skip_mismatch` is set to `True` when `by_name` is | `False`. | | make_train_function(self) | Creates a function that executes one step of training. | | This method can be overridden to support custom training logic. | This method is called by `Model.fit` and `Model.train_on_batch`. | | Typically, this method directly controls `tf.function` and | `tf.distribute.Strategy` settings, and delegates the actual training | logic to `Model.train_step`. | | This function is cached the first time `Model.fit` or | `Model.train_on_batch` is called. The cache is cleared whenever | `Model.compile` is called. | | Returns: | Function. The function created by this method should accept a | `tf.data.Iterator`, and return a `dict` containing values that will | be passed to `tf.keras.Callbacks.on_train_batch_end`, such as | `{'loss': 0.2, 'accuracy': 0.7}`. | | predict(self, x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False) | Generates output predictions for the input samples. | | Computation is done in batches. This method is designed for performance in | large scale inputs. For small amount of inputs that fit in one batch, | directly using `__call__` is recommended for faster execution, e.g., | `model(x)`, or `model(x, training=False)` if you have layers such as | `tf.keras.layers.BatchNormalization` that behaves differently during | inference. Also, note the fact that test loss is not affected by | regularization layers like noise and dropout. | | Args: | x: Input samples. It could be: | - A Numpy array (or array-like), or a list of arrays | (in case the model has multiple inputs). | - A TensorFlow tensor, or a list of tensors | (in case the model has multiple inputs). | - A `tf.data` dataset. | - A generator or `keras.utils.Sequence` instance. | A more detailed description of unpacking behavior for iterator types | (Dataset, generator, Sequence) is given in the `Unpacking behavior | for iterator-like inputs` section of `Model.fit`. | batch_size: Integer or `None`. | Number of samples per batch. | If unspecified, `batch_size` will default to 32. | Do not specify the `batch_size` if your data is in the | form of dataset, generators, or `keras.utils.Sequence` instances | (since they generate batches). | verbose: Verbosity mode, 0 or 1. | steps: Total number of steps (batches of samples) | before declaring the prediction round finished. | Ignored with the default value of `None`. If x is a `tf.data` | dataset and `steps` is None, `predict` will | run until the input dataset is exhausted. | callbacks: List of `keras.callbacks.Callback` instances. | List of callbacks to apply during prediction. | See [callbacks](/api_docs/python/tf/keras/callbacks). | max_queue_size: Integer. Used for generator or `keras.utils.Sequence` | input only. Maximum size for the generator queue. | If unspecified, `max_queue_size` will default to 10. | workers: Integer. Used for generator or `keras.utils.Sequence` input | only. Maximum number of processes to spin up when using | process-based threading. If unspecified, `workers` will default | to 1. | use_multiprocessing: Boolean. Used for generator or | `keras.utils.Sequence` input only. If `True`, use process-based | threading. If unspecified, `use_multiprocessing` will default to | `False`. Note that because this implementation relies on | multiprocessing, you should not pass non-picklable arguments to | the generator as they can't be passed easily to children processes. | | See the discussion of `Unpacking behavior for iterator-like inputs` for | `Model.fit`. Note that Model.predict uses the same interpretation rules as | `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for all | three methods. | | `Model.predict` is not yet supported with | `tf.distribute.experimental.ParameterServerStrategy`. | | Returns: | Numpy array(s) of predictions. | | Raises: | RuntimeError: If `model.predict` is wrapped in `tf.function`. | ValueError: In case of mismatch between the provided | input data and the model's expectations, | or in case a stateful model receives a number of samples | that is not a multiple of the batch size. | | predict_generator(self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0) | Generates predictions for the input samples from a data generator. | | DEPRECATED: | `Model.predict` now supports generators, so there is no longer any need | to use this endpoint. | | predict_on_batch(self, x) | Returns predictions for a single batch of samples. | | Args: | x: Input data. It could be: | - A Numpy array (or array-like), or a list of arrays (in case the | model has multiple inputs). | - A TensorFlow tensor, or a list of tensors (in case the model has | multiple inputs). | | Returns: | Numpy array(s) of predictions. | | Raises: | RuntimeError: If `model.predict_on_batch` is wrapped in `tf.function`. | ValueError: In case of mismatch between given number of inputs and | expectations of the model. | | predict_step(self, data) | The logic for one inference step. | | This method can be overridden to support custom inference logic. | This method is called by `Model.make_predict_function`. | | This method should contain the mathematical logic for one step of inference. | This typically includes the forward pass. | | Configuration details for *how* this logic is run (e.g. `tf.function` and | `tf.distribute.Strategy` settings), should be left to | `Model.make_predict_function`, which can also be overridden. | | Args: | data: A nested structure of `Tensor`s. | | Returns: | The result of one inference step, typically the output of calling the | `Model` on data. | | reset_metrics(self) | Resets the state of all the metrics in the model. | | Examples: | | >>> inputs = tf.keras.layers.Input(shape=(3,)) | >>> outputs = tf.keras.layers.Dense(2)(inputs) | >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) | >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) | | >>> x = np.random.random((2, 3)) | >>> y = np.random.randint(0, 2, (2, 2)) | >>> _ = model.fit(x, y, verbose=0) | >>> assert all(float(m.result()) for m in model.metrics) | | >>> model.reset_metrics() | >>> assert all(float(m.result()) == 0 for m in model.metrics) | | reset_states(self) | | save(self, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None, save_traces=True) | Saves the model to Tensorflow SavedModel or a single HDF5 file. | | Please see `tf.keras.models.save_model` or the | [Serialization and Saving guide](https://keras.io/guides/serialization_and_saving/) | for details. | | Args: | filepath: String, PathLike, path to SavedModel or H5 file to save the | model. | overwrite: Whether to silently overwrite any existing file at the | target location, or provide the user with a manual prompt. | include_optimizer: If True, save optimizer's state together. | save_format: Either `'tf'` or `'h5'`, indicating whether to save the | model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, | and 'h5' in TF 1.X. | signatures: Signatures to save with the SavedModel. Applicable to the | 'tf' format only. Please see the `signatures` argument in | `tf.saved_model.save` for details. | options: (only applies to SavedModel format) | `tf.saved_model.SaveOptions` object that specifies options for | saving to SavedModel. | save_traces: (only applies to SavedModel format) When enabled, the | SavedModel will store the function traces for each layer. This | can be disabled, so that only the configs of each layer are stored. | Defaults to `True`. Disabling this will decrease serialization time | and reduce file size, but it requires that all custom layers/models | implement a `get_config()` method. | | Example: | | ```python | from keras.models import load_model | | model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' | del model # deletes the existing model | | # returns a compiled model | # identical to the previous one | model = load_model('my_model.h5') | ``` | | save_weights(self, filepath, overwrite=True, save_format=None, options=None) | Saves all layer weights. | | Either saves in HDF5 or in TensorFlow format based on the `save_format` | argument. | | When saving in HDF5 format, the weight file has: | - `layer_names` (attribute), a list of strings | (ordered names of model layers). | - For every layer, a `group` named `layer.name` | - For every such layer group, a group attribute `weight_names`, | a list of strings | (ordered names of weights tensor of the layer). | - For every weight in the layer, a dataset | storing the weight value, named after the weight tensor. | | When saving in TensorFlow format, all objects referenced by the network are | saved in the same format as `tf.train.Checkpoint`, including any `Layer` | instances or `Optimizer` instances assigned to object attributes. For | networks constructed from inputs and outputs using `tf.keras.Model(inputs, | outputs)`, `Layer` instances used by the network are tracked/saved | automatically. For user-defined classes which inherit from `tf.keras.Model`, | `Layer` instances must be assigned to object attributes, typically in the | constructor. See the documentation of `tf.train.Checkpoint` and | `tf.keras.Model` for details. | | While the formats are the same, do not mix `save_weights` and | `tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should be | loaded using `Model.load_weights`. Checkpoints saved using | `tf.train.Checkpoint.save` should be restored using the corresponding | `tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over | `save_weights` for training checkpoints. | | The TensorFlow format matches objects and variables by starting at a root | object, `self` for `save_weights`, and greedily matching attribute | names. For `Model.save` this is the `Model`, and for `Checkpoint.save` this | is the `Checkpoint` even if the `Checkpoint` has a model attached. This | means saving a `tf.keras.Model` using `save_weights` and loading into a | `tf.train.Checkpoint` with a `Model` attached (or vice versa) will not match | the `Model`'s variables. See the [guide to training | checkpoints](https://www.tensorflow.org/guide/checkpoint) for details | on the TensorFlow format. | | Args: | filepath: String or PathLike, path to the file to save the weights to. | When saving in TensorFlow format, this is the prefix used for | checkpoint files (multiple files are generated). Note that the '.h5' | suffix causes weights to be saved in HDF5 format. | overwrite: Whether to silently overwrite any existing file at the | target location, or provide the user with a manual prompt. | save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or | '.keras' will default to HDF5 if `save_format` is `None`. Otherwise | `None` defaults to 'tf'. | options: Optional `tf.train.CheckpointOptions` object that specifies | options for saving weights. | | Raises: | ImportError: If h5py is not available when attempting to save in HDF5 | format. | ValueError: For invalid/unknown format arguments. | | test_on_batch(self, x, y=None, sample_weight=None, reset_metrics=True, return_dict=False) | Test the model on a single batch of samples. | | Args: | x: Input data. It could be: | - A Numpy array (or array-like), or a list of arrays (in case the | model has multiple inputs). | - A TensorFlow tensor, or a list of tensors (in case the model has | multiple inputs). | - A dict mapping input names to the corresponding array/tensors, if | the model has named inputs. | y: Target data. Like the input data `x`, it could be either Numpy | array(s) or TensorFlow tensor(s). It should be consistent with `x` | (you cannot have Numpy inputs and tensor targets, or inversely). | sample_weight: Optional array of the same length as x, containing | weights to apply to the model's loss for each sample. In the case of | temporal data, you can pass a 2D array with shape (samples, | sequence_length), to apply a different weight to every timestep of | every sample. | reset_metrics: If `True`, the metrics returned will be only for this | batch. If `False`, the metrics will be statefully accumulated across | batches. | return_dict: If `True`, loss and metric results are returned as a dict, | with each key being the name of the metric. If `False`, they are | returned as a list. | | Returns: | Scalar test loss (if the model has a single output and no metrics) | or list of scalars (if the model has multiple outputs | and/or metrics). The attribute `model.metrics_names` will give you | the display labels for the scalar outputs. | | Raises: | RuntimeError: If `model.test_on_batch` is wrapped in `tf.function`. | ValueError: In case of invalid user-provided arguments. | | test_step(self, data) | The logic for one evaluation step. | | This method can be overridden to support custom evaluation logic. | This method is called by `Model.make_test_function`. | | This function should contain the mathematical logic for one step of | evaluation. | This typically includes the forward pass, loss calculation, and metrics | updates. | | Configuration details for *how* this logic is run (e.g. `tf.function` and | `tf.distribute.Strategy` settings), should be left to | `Model.make_test_function`, which can also be overridden. | | Args: | data: A nested structure of `Tensor`s. | | Returns: | A `dict` containing values that will be passed to | `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the | values of the `Model`'s metrics are returned. | | to_json(self, **kwargs) | Returns a JSON string containing the network configuration. | | To load a network from a JSON save file, use | `keras.models.model_from_json(json_string, custom_objects={})`. | | Args: | **kwargs: Additional keyword arguments | to be passed to `json.dumps()`. | | Returns: | A JSON string. | | to_yaml(self, **kwargs) | Returns a yaml string containing the network configuration. | | To load a network from a yaml save file, use | `keras.models.model_from_yaml(yaml_string, custom_objects={})`. | | `custom_objects` should be a dictionary mapping | the names of custom losses / layers / etc to the corresponding | functions / classes. | | Args: | **kwargs: Additional keyword arguments | to be passed to `yaml.dump()`. | | Returns: | A YAML string. | | Raises: | ImportError: if yaml module is not found. | | train_on_batch(self, x, y=None, sample_weight=None, class_weight=None, reset_metrics=True, return_dict=False) | Runs a single gradient update on a single batch of data. | | Args: | x: Input data. It could be: | - A Numpy array (or array-like), or a list of arrays | (in case the model has multiple inputs). | - A TensorFlow tensor, or a list of tensors | (in case the model has multiple inputs). | - A dict mapping input names to the corresponding array/tensors, | if the model has named inputs. | y: Target data. Like the input data `x`, it could be either Numpy | array(s) or TensorFlow tensor(s). It should be consistent with `x` | (you cannot have Numpy inputs and tensor targets, or inversely). | sample_weight: Optional array of the same length as x, containing | weights to apply to the model's loss for each sample. In the case of | temporal data, you can pass a 2D array with shape (samples, | sequence_length), to apply a different weight to every timestep of | every sample. | class_weight: Optional dictionary mapping class indices (integers) to a | weight (float) to apply to the model's loss for the samples from this | class during training. This can be useful to tell the model to "pay | more attention" to samples from an under-represented class. | reset_metrics: If `True`, the metrics returned will be only for this | batch. If `False`, the metrics will be statefully accumulated across | batches. | return_dict: If `True`, loss and metric results are returned as a dict, | with each key being the name of the metric. If `False`, they are | returned as a list. | | Returns: | Scalar training loss | (if the model has a single output and no metrics) | or list of scalars (if the model has multiple outputs | and/or metrics). The attribute `model.metrics_names` will give you | the display labels for the scalar outputs. | | Raises: | RuntimeError: If `model.train_on_batch` is wrapped in `tf.function`. | ValueError: In case of invalid user-provided arguments. | | ---------------------------------------------------------------------- | Class methods inherited from tensorflow.python.keras.engine.training.Model: | | from_config(config, custom_objects=None) from builtins.type | Creates a layer from its config. | | This method is the reverse of `get_config`, | capable of instantiating the same layer from the config | dictionary. It does not handle layer connectivity | (handled by Network), nor weights (handled by `set_weights`). | | Args: | config: A Python dictionary, typically the | output of get_config. | | Returns: | A layer instance. | | ---------------------------------------------------------------------- | Static methods inherited from tensorflow.python.keras.engine.training.Model: | | __new__(cls, *args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors inherited from tensorflow.python.keras.engine.training.Model: | | distribute_strategy | The `tf.distribute.Strategy` this model was created under. | | layers | | metrics | Returns the model's metrics added using `compile`, `add_metric` APIs. | | Note: Metrics passed to `compile()` are available only after a `keras.Model` | has been trained/evaluated on actual data. | | Examples: | | >>> inputs = tf.keras.layers.Input(shape=(3,)) | >>> outputs = tf.keras.layers.Dense(2)(inputs) | >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) | >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) | >>> [m.name for m in model.metrics] | [] | | >>> x = np.random.random((2, 3)) | >>> y = np.random.randint(0, 2, (2, 2)) | >>> model.fit(x, y) | >>> [m.name for m in model.metrics] | ['loss', 'mae'] | | >>> inputs = tf.keras.layers.Input(shape=(3,)) | >>> d = tf.keras.layers.Dense(2, name='out') | >>> output_1 = d(inputs) | >>> output_2 = d(inputs) | >>> model = tf.keras.models.Model( | ... inputs=inputs, outputs=[output_1, output_2]) | >>> model.add_metric( | ... tf.reduce_sum(output_2), name='mean', aggregation='mean') | >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) | >>> model.fit(x, (y, y)) | >>> [m.name for m in model.metrics] | ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', | 'out_1_acc', 'mean'] | | metrics_names | Returns the model's display labels for all outputs. | | Note: `metrics_names` are available only after a `keras.Model` has been | trained/evaluated on actual data. | | Examples: | | >>> inputs = tf.keras.layers.Input(shape=(3,)) | >>> outputs = tf.keras.layers.Dense(2)(inputs) | >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) | >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) | >>> model.metrics_names | [] | | >>> x = np.random.random((2, 3)) | >>> y = np.random.randint(0, 2, (2, 2)) | >>> model.fit(x, y) | >>> model.metrics_names | ['loss', 'mae'] | | >>> inputs = tf.keras.layers.Input(shape=(3,)) | >>> d = tf.keras.layers.Dense(2, name='out') | >>> output_1 = d(inputs) | >>> output_2 = d(inputs) | >>> model = tf.keras.models.Model( | ... inputs=inputs, outputs=[output_1, output_2]) | >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) | >>> model.fit(x, (y, y)) | >>> model.metrics_names | ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', | 'out_1_acc'] | | non_trainable_weights | List of all non-trainable weights tracked by this layer. | | Non-trainable weights are *not* updated during training. They are expected | to be updated manually in `call()`. | | Returns: | A list of non-trainable variables. | | run_eagerly | Settable attribute indicating whether the model should run eagerly. | | Running eagerly means that your model will be run step by step, | like Python code. Your model might run slower, but it should become easier | for you to debug it by stepping into individual layer calls. | | By default, we will attempt to compile your model to a static graph to | deliver the best execution performance. | | Returns: | Boolean, whether the model should run eagerly. | | state_updates | Deprecated, do NOT use! | | Returns the `updates` from all layers that are stateful. | | This is useful for separating training updates and | state updates, e.g. when we need to update a layer's internal state | during prediction. | | Returns: | A list of update ops. | | trainable_weights | List of all trainable weights tracked by this layer. | | Trainable weights are updated via gradient descent during training. | | Returns: | A list of trainable variables. | | weights | Returns the list of all layer variables/weights. | | Note: This will not track the weights of nested `tf.Modules` that are not | themselves Keras layers. | | Returns: | A list of variables. | | ---------------------------------------------------------------------- | Methods inherited from tensorflow.python.keras.engine.base_layer.Layer: | | __call__(self, *args, **kwargs) | Wraps `call`, applying pre- and post-processing steps. | | Args: | *args: Positional arguments to be passed to `self.call`. | **kwargs: Keyword arguments to be passed to `self.call`. | | Returns: | Output tensor(s). | | Note: | - The following optional keyword arguments are reserved for specific uses: | * `training`: Boolean scalar tensor of Python boolean indicating | whether the `call` is meant for training or inference. | * `mask`: Boolean input mask. | - If the layer's `call` method takes a `mask` argument (as some Keras | layers do), its default value will be set to the mask generated | for `inputs` by the previous layer (if `input` did come from | a layer that generated a corresponding mask, i.e. if it came from | a Keras layer with masking support. | - If the layer is not built, the method will call `build`. | | Raises: | ValueError: if the layer's `call` method returns None (an invalid value). | RuntimeError: if `super().__init__()` was not called in the constructor. | | __delattr__(self, name) | Implement delattr(self, name). | | __getstate__(self) | | __setstate__(self, state) | | add_loss(self, losses, **kwargs) | Add loss tensor(s), potentially dependent on layer inputs. | | Some losses (for instance, activity regularization losses) may be dependent | on the inputs passed when calling a layer. Hence, when reusing the same | layer on different inputs `a` and `b`, some entries in `layer.losses` may | be dependent on `a` and some on `b`. This method automatically keeps track | of dependencies. | | This method can be used inside a subclassed layer or model's `call` | function, in which case `losses` should be a Tensor or list of Tensors. | | Example: | | ```python | class MyLayer(tf.keras.layers.Layer): | def call(self, inputs): | self.add_loss(tf.abs(tf.reduce_mean(inputs))) | return inputs | ``` | | This method can also be called directly on a Functional Model during | construction. In this case, any loss Tensors passed to this Model must | be symbolic and be able to be traced back to the model's `Input`s. These | losses become part of the model's topology and are tracked in `get_config`. | | Example: | | ```python | inputs = tf.keras.Input(shape=(10,)) | x = tf.keras.layers.Dense(10)(inputs) | outputs = tf.keras.layers.Dense(1)(x) | model = tf.keras.Model(inputs, outputs) | # Activity regularization. | model.add_loss(tf.abs(tf.reduce_mean(x))) | ``` | | If this is not the case for your loss (if, for example, your loss references | a `Variable` of one of the model's layers), you can wrap your loss in a | zero-argument lambda. These losses are not tracked as part of the model's | topology since they can't be serialized. | | Example: | | ```python | inputs = tf.keras.Input(shape=(10,)) | d = tf.keras.layers.Dense(10) | x = d(inputs) | outputs = tf.keras.layers.Dense(1)(x) | model = tf.keras.Model(inputs, outputs) | # Weight regularization. | model.add_loss(lambda: tf.reduce_mean(d.kernel)) | ``` | | Args: | losses: Loss tensor, or list/tuple of tensors. Rather than tensors, losses | may also be zero-argument callables which create a loss tensor. | **kwargs: Additional keyword arguments for backward compatibility. | Accepted values: | inputs - Deprecated, will be automatically inferred. | | add_metric(self, value, name=None, **kwargs) | Adds metric tensor to the layer. | | This method can be used inside the `call()` method of a subclassed layer | or model. | | ```python | class MyMetricLayer(tf.keras.layers.Layer): | def __init__(self): | super(MyMetricLayer, self).__init__(name='my_metric_layer') | self.mean = tf.keras.metrics.Mean(name='metric_1') | | def call(self, inputs): | self.add_metric(self.mean(inputs)) | self.add_metric(tf.reduce_sum(inputs), name='metric_2') | return inputs | ``` | | This method can also be called directly on a Functional Model during | construction. In this case, any tensor passed to this Model must | be symbolic and be able to be traced back to the model's `Input`s. These | metrics become part of the model's topology and are tracked when you | save the model via `save()`. | | ```python | inputs = tf.keras.Input(shape=(10,)) | x = tf.keras.layers.Dense(10)(inputs) | outputs = tf.keras.layers.Dense(1)(x) | model = tf.keras.Model(inputs, outputs) | model.add_metric(math_ops.reduce_sum(x), name='metric_1') | ``` | | Note: Calling `add_metric()` with the result of a metric object on a | Functional Model, as shown in the example below, is not supported. This is | because we cannot trace the metric result tensor back to the model's inputs. | | ```python | inputs = tf.keras.Input(shape=(10,)) | x = tf.keras.layers.Dense(10)(inputs) | outputs = tf.keras.layers.Dense(1)(x) | model = tf.keras.Model(inputs, outputs) | model.add_metric(tf.keras.metrics.Mean()(x), name='metric_1') | ``` | | Args: | value: Metric tensor. | name: String metric name. | **kwargs: Additional keyword arguments for backward compatibility. | Accepted values: | `aggregation` - When the `value` tensor provided is not the result of | calling a `keras.Metric` instance, it will be aggregated by default | using a `keras.Metric.Mean`. | | add_update(self, updates, inputs=None) | Add update op(s), potentially dependent on layer inputs. | | Weight updates (for instance, the updates of the moving mean and variance | in a BatchNormalization layer) may be dependent on the inputs passed | when calling a layer. Hence, when reusing the same layer on | different inputs `a` and `b`, some entries in `layer.updates` may be | dependent on `a` and some on `b`. This method automatically keeps track | of dependencies. | | This call is ignored when eager execution is enabled (in that case, variable | updates are run on the fly and thus do not need to be tracked for later | execution). | | Args: | updates: Update op, or list/tuple of update ops, or zero-arg callable | that returns an update op. A zero-arg callable should be passed in | order to disable running the updates by setting `trainable=False` | on this Layer, when executing in Eager mode. | inputs: Deprecated, will be automatically inferred. | | add_variable(self, *args, **kwargs) | Deprecated, do NOT use! Alias for `add_weight`. | | add_weight(self, name=None, shape=None, dtype=None, initializer=None, regularizer=None, trainable=None, constraint=None, use_resource=None, synchronization=<VariableSynchronization.AUTO: 0>, aggregation=<VariableAggregation.NONE: 0>, **kwargs) | Adds a new variable to the layer. | | Args: | name: Variable name. | shape: Variable shape. Defaults to scalar if unspecified. | dtype: The type of the variable. Defaults to `self.dtype`. | initializer: Initializer instance (callable). | regularizer: Regularizer instance (callable). | trainable: Boolean, whether the variable should be part of the layer's | "trainable_variables" (e.g. variables, biases) | or "non_trainable_variables" (e.g. BatchNorm mean and variance). | Note that `trainable` cannot be `True` if `synchronization` | is set to `ON_READ`. | constraint: Constraint instance (callable). | use_resource: Whether to use `ResourceVariable`. | synchronization: Indicates when a distributed a variable will be | aggregated. Accepted values are constants defined in the class | `tf.VariableSynchronization`. By default the synchronization is set to | `AUTO` and the current `DistributionStrategy` chooses | when to synchronize. If `synchronization` is set to `ON_READ`, | `trainable` must not be set to `True`. | aggregation: Indicates how a distributed variable will be aggregated. | Accepted values are constants defined in the class | `tf.VariableAggregation`. | **kwargs: Additional keyword arguments. Accepted values are `getter`, | `collections`, `experimental_autocast` and `caching_device`. | | Returns: | The variable created. | | Raises: | ValueError: When giving unsupported dtype and no initializer or when | trainable has been set to True with synchronization set as `ON_READ`. | | apply(self, inputs, *args, **kwargs) | Deprecated, do NOT use! | | This is an alias of `self.__call__`. | | Args: | inputs: Input tensor(s). | *args: additional positional arguments to be passed to `self.call`. | **kwargs: additional keyword arguments to be passed to `self.call`. | | Returns: | Output tensor(s). | | compute_mask(self, inputs, mask=None) | Computes an output mask tensor. | | Args: | inputs: Tensor or list of tensors. | mask: Tensor or list of tensors. | | Returns: | None or a tensor (or list of tensors, | one per output tensor of the layer). | | compute_output_shape(self, input_shape) | Computes the output shape of the layer. | | If the layer has not been built, this method will call `build` on the | layer. This assumes that the layer will later be used with inputs that | match the input shape provided here. | | Args: | input_shape: Shape tuple (tuple of integers) | or list of shape tuples (one per output tensor of the layer). | Shape tuples can include None for free dimensions, | instead of an integer. | | Returns: | An input shape tuple. | | compute_output_signature(self, input_signature) | Compute the output tensor signature of the layer based on the inputs. | | Unlike a TensorShape object, a TensorSpec object contains both shape | and dtype information for a tensor. This method allows layers to provide | output dtype information if it is different from the input dtype. | For any layer that doesn't implement this function, | the framework will fall back to use `compute_output_shape`, and will | assume that the output dtype matches the input dtype. | | Args: | input_signature: Single TensorSpec or nested structure of TensorSpec | objects, describing a candidate input for the layer. | | Returns: | Single TensorSpec or nested structure of TensorSpec objects, describing | how the layer would transform the provided input. | | Raises: | TypeError: If input_signature contains a non-TensorSpec object. | | count_params(self) | Count the total number of scalars composing the weights. | | Returns: | An integer count. | | Raises: | ValueError: if the layer isn't yet built | (in which case its weights aren't yet defined). | | get_input_at(self, node_index) | Retrieves the input tensor(s) of a layer at a given node. | | Args: | node_index: Integer, index of the node | from which to retrieve the attribute. | E.g. `node_index=0` will correspond to the | first input node of the layer. | | Returns: | A tensor (or list of tensors if the layer has multiple inputs). | | Raises: | RuntimeError: If called in Eager mode. | | get_input_mask_at(self, node_index) | Retrieves the input mask tensor(s) of a layer at a given node. | | Args: | node_index: Integer, index of the node | from which to retrieve the attribute. | E.g. `node_index=0` will correspond to the | first time the layer was called. | | Returns: | A mask tensor | (or list of tensors if the layer has multiple inputs). | | get_input_shape_at(self, node_index) | Retrieves the input shape(s) of a layer at a given node. | | Args: | node_index: Integer, index of the node | from which to retrieve the attribute. | E.g. `node_index=0` will correspond to the | first time the layer was called. | | Returns: | A shape tuple | (or list of shape tuples if the layer has multiple inputs). | | Raises: | RuntimeError: If called in Eager mode. | | get_losses_for(self, inputs) | Deprecated, do NOT use! | | Retrieves losses relevant to a specific set of inputs. | | Args: | inputs: Input tensor or list/tuple of input tensors. | | Returns: | List of loss tensors of the layer that depend on `inputs`. | | get_output_at(self, node_index) | Retrieves the output tensor(s) of a layer at a given node. | | Args: | node_index: Integer, index of the node | from which to retrieve the attribute. | E.g. `node_index=0` will correspond to the | first output node of the layer. | | Returns: | A tensor (or list of tensors if the layer has multiple outputs). | | Raises: | RuntimeError: If called in Eager mode. | | get_output_mask_at(self, node_index) | Retrieves the output mask tensor(s) of a layer at a given node. | | Args: | node_index: Integer, index of the node | from which to retrieve the attribute. | E.g. `node_index=0` will correspond to the | first time the layer was called. | | Returns: | A mask tensor | (or list of tensors if the layer has multiple outputs). | | get_output_shape_at(self, node_index) | Retrieves the output shape(s) of a layer at a given node. | | Args: | node_index: Integer, index of the node | from which to retrieve the attribute. | E.g. `node_index=0` will correspond to the | first time the layer was called. | | Returns: | A shape tuple | (or list of shape tuples if the layer has multiple outputs). | | Raises: | RuntimeError: If called in Eager mode. | | get_updates_for(self, inputs) | Deprecated, do NOT use! | | Retrieves updates relevant to a specific set of inputs. | | Args: | inputs: Input tensor or list/tuple of input tensors. | | Returns: | List of update ops of the layer that depend on `inputs`. | | set_weights(self, weights) | Sets the weights of the layer, from NumPy arrays. | | The weights of a layer represent the state of the layer. This function | sets the weight values from numpy arrays. The weight values should be | passed in the order they are created by the layer. Note that the layer's | weights must be instantiated before calling this function, by calling | the layer. | | For example, a `Dense` layer returns a list of two values: the kernel matrix | and the bias vector. These can be used to set the weights of another | `Dense` layer: | | >>> layer_a = tf.keras.layers.Dense(1, | ... kernel_initializer=tf.constant_initializer(1.)) | >>> a_out = layer_a(tf.convert_to_tensor([[1., 2., 3.]])) | >>> layer_a.get_weights() | [array([[1.], | [1.], | [1.]], dtype=float32), array([0.], dtype=float32)] | >>> layer_b = tf.keras.layers.Dense(1, | ... kernel_initializer=tf.constant_initializer(2.)) | >>> b_out = layer_b(tf.convert_to_tensor([[10., 20., 30.]])) | >>> layer_b.get_weights() | [array([[2.], | [2.], | [2.]], dtype=float32), array([0.], dtype=float32)] | >>> layer_b.set_weights(layer_a.get_weights()) | >>> layer_b.get_weights() | [array([[1.], | [1.], | [1.]], dtype=float32), array([0.], dtype=float32)] | | Args: | weights: a list of NumPy arrays. The number | of arrays and their shape must match | number of the dimensions of the weights | of the layer (i.e. it should match the | output of `get_weights`). | | Raises: | ValueError: If the provided weights list does not match the | layer's specifications. | | ---------------------------------------------------------------------- | Data descriptors inherited from tensorflow.python.keras.engine.base_layer.Layer: | | activity_regularizer | Optional regularizer function for the output of this layer. | | compute_dtype | The dtype of the layer's computations. | | This is equivalent to `Layer.dtype_policy.compute_dtype`. Unless | mixed precision is used, this is the same as `Layer.dtype`, the dtype of | the weights. | | Layers automatically cast their inputs to the compute dtype, which causes | computations and the output to be in the compute dtype as well. This is done | by the base Layer class in `Layer.__call__`, so you do not have to insert | these casts if implementing your own layer. | | Layers often perform certain internal computations in higher precision when | `compute_dtype` is float16 or bfloat16 for numeric stability. The output | will still typically be float16 or bfloat16 in such cases. | | Returns: | The layer's compute dtype. | | dtype | The dtype of the layer weights. | | This is equivalent to `Layer.dtype_policy.variable_dtype`. Unless | mixed precision is used, this is the same as `Layer.compute_dtype`, the | dtype of the layer's computations. | | dtype_policy | The dtype policy associated with this layer. | | This is an instance of a `tf.keras.mixed_precision.Policy`. | | dynamic | Whether the layer is dynamic (eager-only); set in the constructor. | | inbound_nodes | Deprecated, do NOT use! Only for compatibility with external Keras. | | input | Retrieves the input tensor(s) of a layer. | | Only applicable if the layer has exactly one input, | i.e. if it is connected to one incoming layer. | | Returns: | Input tensor or list of input tensors. | | Raises: | RuntimeError: If called in Eager mode. | AttributeError: If no inbound nodes are found. | | input_mask | Retrieves the input mask tensor(s) of a layer. | | Only applicable if the layer has exactly one inbound node, | i.e. if it is connected to one incoming layer. | | Returns: | Input mask tensor (potentially None) or list of input | mask tensors. | | Raises: | AttributeError: if the layer is connected to | more than one incoming layers. | | input_shape | Retrieves the input shape(s) of a layer. | | Only applicable if the layer has exactly one input, | i.e. if it is connected to one incoming layer, or if all inputs | have the same shape. | | Returns: | Input shape, as an integer shape tuple | (or list of shape tuples, one tuple per input tensor). | | Raises: | AttributeError: if the layer has no defined input_shape. | RuntimeError: if called in Eager mode. | | input_spec | `InputSpec` instance(s) describing the input format for this layer. | | When you create a layer subclass, you can set `self.input_spec` to enable | the layer to run input compatibility checks when it is called. | Consider a `Conv2D` layer: it can only be called on a single input tensor | of rank 4. As such, you can set, in `__init__()`: | | ```python | self.input_spec = tf.keras.layers.InputSpec(ndim=4) | ``` | | Now, if you try to call the layer on an input that isn't rank 4 | (for instance, an input of shape `(2,)`, it will raise a nicely-formatted | error: | | ``` | ValueError: Input 0 of layer conv2d is incompatible with the layer: | expected ndim=4, found ndim=1. Full shape received: [2] | ``` | | Input checks that can be specified via `input_spec` include: | - Structure (e.g. a single input, a list of 2 inputs, etc) | - Shape | - Rank (ndim) | - Dtype | | For more information, see `tf.keras.layers.InputSpec`. | | Returns: | A `tf.keras.layers.InputSpec` instance, or nested structure thereof. | | losses | List of losses added using the `add_loss()` API. | | Variable regularization tensors are created when this property is accessed, | so it is eager safe: accessing `losses` under a `tf.GradientTape` will | propagate gradients back to the corresponding variables. | | Examples: | | >>> class MyLayer(tf.keras.layers.Layer): | ... def call(self, inputs): | ... self.add_loss(tf.abs(tf.reduce_mean(inputs))) | ... return inputs | >>> l = MyLayer() | >>> l(np.ones((10, 1))) | >>> l.losses | [1.0] | | >>> inputs = tf.keras.Input(shape=(10,)) | >>> x = tf.keras.layers.Dense(10)(inputs) | >>> outputs = tf.keras.layers.Dense(1)(x) | >>> model = tf.keras.Model(inputs, outputs) | >>> # Activity regularization. | >>> len(model.losses) | 0 | >>> model.add_loss(tf.abs(tf.reduce_mean(x))) | >>> len(model.losses) | 1 | | >>> inputs = tf.keras.Input(shape=(10,)) | >>> d = tf.keras.layers.Dense(10, kernel_initializer='ones') | >>> x = d(inputs) | >>> outputs = tf.keras.layers.Dense(1)(x) | >>> model = tf.keras.Model(inputs, outputs) | >>> # Weight regularization. | >>> model.add_loss(lambda: tf.reduce_mean(d.kernel)) | >>> model.losses | [<tf.Tensor: shape=(), dtype=float32, numpy=1.0>] | | Returns: | A list of tensors. | | name | Name of the layer (string), set in the constructor. | | non_trainable_variables | Sequence of non-trainable variables owned by this module and its submodules. | | Note: this method uses reflection to find variables on the current instance | and submodules. For performance reasons you may wish to cache the result | of calling this method if you don't expect the return value to change. | | Returns: | A sequence of variables for the current module (sorted by attribute | name) followed by variables from all submodules recursively (breadth | first). | | outbound_nodes | Deprecated, do NOT use! Only for compatibility with external Keras. | | output | Retrieves the output tensor(s) of a layer. | | Only applicable if the layer has exactly one output, | i.e. if it is connected to one incoming layer. | | Returns: | Output tensor or list of output tensors. | | Raises: | AttributeError: if the layer is connected to more than one incoming | layers. | RuntimeError: if called in Eager mode. | | output_mask | Retrieves the output mask tensor(s) of a layer. | | Only applicable if the layer has exactly one inbound node, | i.e. if it is connected to one incoming layer. | | Returns: | Output mask tensor (potentially None) or list of output | mask tensors. | | Raises: | AttributeError: if the layer is connected to | more than one incoming layers. | | output_shape | Retrieves the output shape(s) of a layer. | | Only applicable if the layer has one output, | or if all outputs have the same shape. | | Returns: | Output shape, as an integer shape tuple | (or list of shape tuples, one tuple per output tensor). | | Raises: | AttributeError: if the layer has no defined output shape. | RuntimeError: if called in Eager mode. | | stateful | | supports_masking | Whether this layer supports computing a mask using `compute_mask`. | | trainable | | trainable_variables | Sequence of trainable variables owned by this module and its submodules. | | Note: this method uses reflection to find variables on the current instance | and submodules. For performance reasons you may wish to cache the result | of calling this method if you don't expect the return value to change. | | Returns: | A sequence of variables for the current module (sorted by attribute | name) followed by variables from all submodules recursively (breadth | first). | | updates | | variable_dtype | Alias of `Layer.dtype`, the dtype of the weights. | | variables | Returns the list of all layer variables/weights. | | Alias of `self.weights`. | | Note: This will not track the weights of nested `tf.Modules` that are not | themselves Keras layers. | | Returns: | A list of variables. | | ---------------------------------------------------------------------- | Class methods inherited from tensorflow.python.module.module.Module: | | with_name_scope(method) from builtins.type | Decorator to automatically enter the module name scope. | | >>> class MyModule(tf.Module): | ... @tf.Module.with_name_scope | ... def __call__(self, x): | ... if not hasattr(self, 'w'): | ... self.w = tf.Variable(tf.random.normal([x.shape[1], 3])) | ... return tf.matmul(x, self.w) | | Using the above module would produce `tf.Variable`s and `tf.Tensor`s whose | names included the module name: | | >>> mod = MyModule() | >>> mod(tf.ones([1, 2])) | <tf.Tensor: shape=(1, 3), dtype=float32, numpy=..., dtype=float32)> | >>> mod.w | <tf.Variable 'my_module/Variable:0' shape=(2, 3) dtype=float32, | numpy=..., dtype=float32)> | | Args: | method: The method to wrap. | | Returns: | The original method wrapped such that it enters the module's name scope. | | ---------------------------------------------------------------------- | Data descriptors inherited from tensorflow.python.module.module.Module: | | name_scope | Returns a `tf.name_scope` instance for this class. | | submodules | Sequence of all sub-modules. | | Submodules are modules which are properties of this module, or found as | properties of modules which are properties of this module (and so on). | | >>> a = tf.Module() | >>> b = tf.Module() | >>> c = tf.Module() | >>> a.b = b | >>> b.c = c | >>> list(a.submodules) == [b, c] | True | >>> list(b.submodules) == [c] | True | >>> list(c.submodules) == [] | True | | Returns: | A sequence of all submodules. | | ---------------------------------------------------------------------- | Data descriptors inherited from tensorflow.python.training.tracking.base.Trackable: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)

## Using a subset of features

The previous example did not specify the features, so all the columns were used as input feature (except for the label). The following example shows how to specify input features.

```
feature_1 = tfdf.keras.FeatureUsage(name="bill_length_mm")
feature_2 = tfdf.keras.FeatureUsage(name="island")
all_features = [feature_1, feature_2]
# Note: This model is only trained with two features. It will not be as good as
# the one trained on all features.
model_2 = tfdf.keras.GradientBoostedTreesModel(
features=all_features, exclude_non_specified_features=True)
model_2.compile(metrics=["accuracy"])
model_2.fit(x=train_ds, validation_data=test_ds)
print(model_2.evaluate(test_ds, return_dict=True))
```

4/4 [==============================] - 1s 431ms/step - val_loss: 0.0000e+00 - val_accuracy: 0.9709 2/2 [==============================] - 0s 4ms/step - loss: 0.0000e+00 - accuracy: 0.9709 {'loss': 0.0, 'accuracy': 0.9708737730979919}

**TF-DF** attaches a **semantics** to each feature. This semantics controls how
the feature is used by the model. The following semantics are currently supported:

**Numerical**: Generally for quantities or counts with full ordering. For example, the age of a person, or the number of items in a bag. Can be a float or an integer. Missing values are represented with float(Nan) or with an empty sparse tensor.**Categorical**: Generally for a type/class in finite set of possible values without ordering. For example, the color RED in the set {RED, BLUE, GREEN}. Can be a string or an integer. Missing values are represented as "" (empty sting), value -2 or with an empty sparse tensor.**Categorical-Set**: A set of categorical values. Great to represent tokenized text. Can be a string or an integer in a sparse tensor or a ragged tensor (recommended). The order/index of each item doesn't matter.

If not specified, the semantics is inferred from the representation type and shown in the training logs:

- int, float (dense or sparse) → Numerical semantics.
- str (dense or sparse) → Categorical semantics
- int, str (ragged) → Categorical-Set semantics

In some cases, the inferred semantics is incorrect. For example: An Enum stored as an integer is semantically categorical, but it will be detected as numerical. In this case, you should specify the semantic argument in the input. The `education_num`

field of the Adult dataset is classical example.

This dataset doesn't contain such a feature. However, for the demonstration, we will make the model treat the `year`

as a categorical feature:

```
%set_cell_height 300
feature_1 = tfdf.keras.FeatureUsage(name="year", semantic=tfdf.keras.FeatureSemantic.CATEGORICAL)
feature_2 = tfdf.keras.FeatureUsage(name="bill_length_mm")
feature_3 = tfdf.keras.FeatureUsage(name="sex")
all_features = [feature_1, feature_2, feature_3]
model_3 = tfdf.keras.GradientBoostedTreesModel(features=all_features, exclude_non_specified_features=True)
model_3.compile( metrics=["accuracy"])
with sys_pipes():
model_3.fit(x=train_ds, validation_data=test_ds)
```

<IPython.core.display.Javascript object> 1/4 [======>.......................] - ETA: 0s [INFO kernel.cc:746] Start Yggdrasil model training [INFO kernel.cc:747] Collect training examples [INFO kernel.cc:392] Number of batches: 4 [INFO kernel.cc:393] Number of examples: 241 [INFO kernel.cc:769] Dataset: Number of records: 241 Number of columns: 4 Number of columns by type: CATEGORICAL: 3 (75%) NUMERICAL: 1 (25%) Columns: CATEGORICAL: 3 (75%) 1: "sex" CATEGORICAL num-nas:8 (3.3195%) has-dict vocab-size:3 zero-ood-items most-frequent:"female" 120 (51.5021%) 2: "year" CATEGORICAL integerized vocab-size:2011 no-ood-item 3: "__LABEL" CATEGORICAL integerized vocab-size:4 no-ood-item NUMERICAL: 1 (25%) 0: "bill_length_mm" NUMERICAL num-nas:1 (0.414938%) mean:43.5587 min:32.1 max:59.6 sd:5.33806 Terminology: nas: Number of non-available (i.e. missing) values. ood: Out of dictionary. manually-defined: Attribute which type is manually defined by the user i.e. the type was not automatically inferred. tokenized: The attribute value is obtained through tokenization. has-dict: The attribute is attached to a string dictionary e.g. a categorical attribute stored as a string. vocab-size: Number of unique values. [INFO kernel.cc:772] Configure learner [WARNING gradient_boosted_trees.cc:1532] Subsample hyperparameter given but sampling method does not match. [WARNING gradient_boosted_trees.cc:1545] GOSS alpha hyperparameter given but GOSS is disabled. [WARNING gradient_boosted_trees.cc:1554] GOSS beta hyperparameter given but GOSS is disabled. [WARNING gradient_boosted_trees.cc:1566] SelGB ratio hyperparameter given but SelGB is disabled. [INFO kernel.cc:797] Training config: learner: "GRADIENT_BOOSTED_TREES" features: "bill_length_mm" features: "sex" features: "year" label: "__LABEL" task: CLASSIFICATION [yggdrasil_decision_forests.model.gradient_boosted_trees.proto.gradient_boosted_trees_config] { num_trees: 300 decision_tree { max_depth: 6 min_examples: 5 in_split_min_examples_check: true missing_value_policy: GLOBAL_IMPUTATION allow_na_conditions: false categorical_set_greedy_forward { sampling: 0.1 max_num_items: -1 min_item_frequency: 1 } growing_strategy_local { } categorical { cart { } } num_candidate_attributes_ratio: -1 axis_aligned_split { } internal { sorting_strategy: PRESORTED } } shrinkage: 0.1 validation_set_ratio: 0.1 early_stopping: VALIDATION_LOSS_INCREASE early_stopping_num_trees_look_ahead: 30 l2_regularization: 0 lambda_loss: 1 mart { } adapt_subsample_for_maximum_training_duration: false l1_regularization: 0 use_hessian_gain: false l2_regularization_categorical: 1 } [INFO kernel.cc:800] Deployment config: [INFO kernel.cc:837] Train model [INFO gradient_boosted_trees.cc:480] Default loss set to MULTINOMIAL_LOG_LIKELIHOOD [INFO gradient_boosted_trees.cc:1358] num-trees:1 train-loss:0.962911 train-accuracy:0.863208 valid-loss:1.015087 valid-accuracy:0.758621 [INFO gradient_boosted_trees.cc:2506] Early stop of the training because the validation loss does not decrease anymore. Best valid-loss: 0.725294 [INFO gradient_boosted_trees.cc:319] Truncates the model to 114 tree(s) i.e. 38 iteration(s). [INFO gradient_boosted_trees.cc:348] Final model valid-loss:0.725294 valid-accuracy:0.655172 [INFO kernel.cc:856] Export model in log directory: /tmp/tmph591s_hi [INFO kernel.cc:864] Save model in resources [INFO kernel.cc:929] Loading model from path [INFO decision_forest.cc:590] Model loaded with 114 root(s), 3530 node(s), and 3 input feature(s). [INFO kernel.cc:797] Use fast generic engine 4/4 [==============================] - 0s 137ms/step - val_loss: 0.0000e+00 - val_accuracy: 0.7767

Note that `year`

is in the list of CATEGORICAL features (unlike the first run).

## Hyper-parameters

**Hyper-parameters** are parameters of the training algorithm that impact
the quality of the final model. They are specified in the model class
constructor. The list of hyper-parameters is visible with the *question mark* colab command (e.g. `?tfdf.keras.GradientBoostedTreesModel`

).

Alternatively, you can find them on the TensorFlow Decision Forest Github or the Yggdrasil Decision Forest documentation.

The default hyper-parameters of each algorithm matches approximatively the initial publication paper. To ensure consistancy, new features and their matching hyper-parameters are always disable by default. That's why it is a good idea to tune your hyper-parameters.

```
# A classical but slighly more complex model.
model_6 = tfdf.keras.GradientBoostedTreesModel(
num_trees=500, growing_strategy="BEST_FIRST_GLOBAL", max_depth=8)
model_6.fit(x=train_ds)
```

4/4 [==============================] - 0s 1ms/step <tensorflow.python.keras.callbacks.History at 0x7fd1aa6227d0>

```
# A more complex, but possibly, more accurate model.
model_7 = tfdf.keras.GradientBoostedTreesModel(
num_trees=500,
growing_strategy="BEST_FIRST_GLOBAL",
max_depth=8,
split_axis="SPARSE_OBLIQUE",
categorical_algorithm="RANDOM",
)
model_7.fit(x=train_ds)
```

4/4 [==============================] - 0s 1ms/step WARNING:tensorflow:5 out of the last 5 calls to <function CoreModel.make_predict_function.<locals>.predict_function_trained at 0x7fd1aa5480e0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details. WARNING:tensorflow:5 out of the last 5 calls to <function CoreModel.make_predict_function.<locals>.predict_function_trained at 0x7fd1aa5480e0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details. <tensorflow.python.keras.callbacks.History at 0x7fd1aa541090>

As new training methods are published and implemented, combinaisons of hyper-parameters can emerge as good or almost-always-better than the default parameters. To avoid changing the default hyper-parameter values these good combinaisons are indexed and available as hyper-parameter templates.

For example, the `benchmark_rank1`

template is the best combinaison on our internal benchmarks. Those templates are versioned to allow training configuration stability e.g. `benchmark_rank1@v1`

.

```
# A good template of hyper-parameters.
model_8 = tfdf.keras.GradientBoostedTreesModel(hyperparameter_template="benchmark_rank1")
model_8.fit(x=train_ds)
```

4/4 [==============================] - 0s 1ms/step WARNING:tensorflow:6 out of the last 6 calls to <function CoreModel.make_predict_function.<locals>.predict_function_trained at 0x7fd1aa4d4a70> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details. WARNING:tensorflow:6 out of the last 6 calls to <function CoreModel.make_predict_function.<locals>.predict_function_trained at 0x7fd1aa4d4a70> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details. <tensorflow.python.keras.callbacks.History at 0x7fd1aa4c5d50>

The available tempaltes are available with `predefined_hyperparameters`

. Note that different learning algorithms have different templates, even if the name is similar.

```
# The hyper-parameter templates of the Gradient Boosted Tree model.
print(tfdf.keras.GradientBoostedTreesModel.predefined_hyperparameters())
```

[HyperParameterTemplate(name='better_default', version=1, parameters={'growing_strategy': 'BEST_FIRST_GLOBAL'}, description='A configuration that is generally better than the default parameters without being more expensive.'), HyperParameterTemplate(name='benchmark_rank1', version=1, parameters={'growing_strategy': 'BEST_FIRST_GLOBAL', 'categorical_algorithm': 'RANDOM', 'split_axis': 'SPARSE_OBLIQUE', 'sparse_oblique_normalization': 'MIN_MAX', 'sparse_oblique_num_projections_exponent': 1.0}, description='Top ranking hyper-parameters on our benchmark slightly modified to run in reasonable time.')]

## Feature Preprocessing

Pre-processing features is sometimes necessary to consume signals with complex structures, to regularize the model or to apply transfer learning. Pre-processing can be done in one of three ways:

Preprocessing on the Pandas dataframe. This solution is easy to implement and generally suitable for experimentation. However, the pre-processing logic will not be exported in the model by

`model.save()`

.Keras Preprocessing: While more complex than the previous solution, Keras Preprocessing is packaged in the model.

TensorFlow Feature Columns: This API is part of the TF Estimator library (!= Keras) and planned for deprecation. This solution is interesting when using existing preprocessing code.

In the next example, pre-process the `body_mass_g`

feature into `body_mass_kg = body_mass_g / 1000`

. The `bill_length_mm`

is consumed without pre-processing. Note that such
monotonic transformations have generally no impact on decision forest models.

```
%set_cell_height 300
body_mass_g = tf.keras.layers.Input(shape=(1,), name="body_mass_g")
body_mass_kg = body_mass_g / 1000.0
bill_length_mm = tf.keras.layers.Input(shape=(1,), name="bill_length_mm")
raw_inputs = {"body_mass_g": body_mass_g, "bill_length_mm": bill_length_mm}
processed_inputs = {"body_mass_kg": body_mass_kg, "bill_length_mm": bill_length_mm}
# "preprocessor" contains the preprocessing logic.
preprocessor = tf.keras.Model(inputs=raw_inputs, outputs=processed_inputs)
# "model_4" contains both the pre-processing logic and the decision forest.
model_4 = tfdf.keras.RandomForestModel(preprocessing=preprocessor)
model_4.fit(x=train_ds)
model_4.summary()
```

<IPython.core.display.Javascript object> 4/4 [==============================] - 0s 1ms/step /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow/python/keras/engine/functional.py:591: UserWarning: Input dict contained keys ['island', 'bill_depth_mm', 'flipper_length_mm', 'sex', 'year'] which did not match any model input. They will be ignored by the model. [n for n in tensors.keys() if n not in ref_input_names]) Model: "random_forest_model_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= model (Functional) {'body_mass_kg': (None, 1 0 ================================================================= Total params: 1 Trainable params: 0 Non-trainable params: 1 _________________________________________________________________ Type: "RANDOM_FOREST" Task: CLASSIFICATION Label: "__LABEL" Input Features (2): bill_length_mm body_mass_kg No weights Variable Importance: NUM_NODES: 1. "bill_length_mm" 1628.000000 ################ 2. "body_mass_kg" 1262.000000 Variable Importance: NUM_AS_ROOT: 1. "bill_length_mm" 297.000000 ################ 2. "body_mass_kg" 3.000000 Variable Importance: SUM_SCORE: 1. "bill_length_mm" 43784.335649 ################ 2. "body_mass_kg" 24828.911682 Variable Importance: MEAN_MIN_DEPTH: 1. "__LABEL" 3.918327 ################ 2. "body_mass_kg" 1.240148 ##### 3. "bill_length_mm" 0.011333 Winner take all: true Out-of-bag evaluation: accuracy:0.921162 logloss:0.524026 Number of trees: 300 Total number of nodes: 6080 Number of nodes by tree: Count: 300 Average: 20.2667 StdDev: 3.21593 Min: 13 Max: 29 Ignored: 0 ---------------------------------------------- [ 13, 14) 8 2.67% 2.67% # [ 14, 15) 0 0.00% 2.67% [ 15, 16) 24 8.00% 10.67% ### [ 16, 17) 0 0.00% 10.67% [ 17, 18) 43 14.33% 25.00% ###### [ 18, 19) 0 0.00% 25.00% [ 19, 20) 56 18.67% 43.67% ######## [ 20, 21) 0 0.00% 43.67% [ 21, 22) 73 24.33% 68.00% ########## [ 22, 23) 0 0.00% 68.00% [ 23, 24) 69 23.00% 91.00% ######### [ 24, 25) 0 0.00% 91.00% [ 25, 26) 15 5.00% 96.00% ## [ 26, 27) 0 0.00% 96.00% [ 27, 28) 11 3.67% 99.67% ## [ 28, 29) 0 0.00% 99.67% [ 29, 29] 1 0.33% 100.00% Depth by leafs: Count: 3190 Average: 3.95172 StdDev: 1.33139 Min: 1 Max: 8 Ignored: 0 ---------------------------------------------- [ 1, 2) 44 1.38% 1.38% [ 2, 3) 338 10.60% 11.97% #### [ 3, 4) 903 28.31% 40.28% ########## [ 4, 5) 937 29.37% 69.66% ########## [ 5, 6) 501 15.71% 85.36% ##### [ 6, 7) 361 11.32% 96.68% #### [ 7, 8) 90 2.82% 99.50% # [ 8, 8] 16 0.50% 100.00% Number of training obs by leaf: Count: 3190 Average: 22.6646 StdDev: 28.2298 Min: 5 Max: 119 Ignored: 0 ---------------------------------------------- [ 5, 10) 2060 64.58% 64.58% ########## [ 10, 16) 200 6.27% 70.85% # [ 16, 22) 29 0.91% 71.76% [ 22, 28) 30 0.94% 72.70% [ 28, 33) 51 1.60% 74.29% [ 33, 39) 115 3.61% 77.90% # [ 39, 45) 79 2.48% 80.38% [ 45, 51) 47 1.47% 81.85% [ 51, 56) 47 1.47% 83.32% [ 56, 62) 82 2.57% 85.89% [ 62, 68) 81 2.54% 88.43% [ 68, 74) 60 1.88% 90.31% [ 74, 79) 34 1.07% 91.38% [ 79, 85) 60 1.88% 93.26% [ 85, 91) 72 2.26% 95.52% [ 91, 97) 59 1.85% 97.37% [ 97, 102) 41 1.29% 98.65% [ 102, 108) 32 1.00% 99.66% [ 108, 114) 8 0.25% 99.91% [ 114, 119] 3 0.09% 100.00% Attribute in nodes: 1628 : bill_length_mm [NUMERICAL] 1262 : body_mass_kg [NUMERICAL] Attribute in nodes with depth <= 0: 297 : bill_length_mm [NUMERICAL] 3 : body_mass_kg [NUMERICAL] Attribute in nodes with depth <= 1: 491 : bill_length_mm [NUMERICAL] 365 : body_mass_kg [NUMERICAL] Attribute in nodes with depth <= 2: 831 : bill_length_mm [NUMERICAL] 799 : body_mass_kg [NUMERICAL] Attribute in nodes with depth <= 3: 1261 : bill_length_mm [NUMERICAL] 1014 : body_mass_kg [NUMERICAL] Attribute in nodes with depth <= 5: 1596 : bill_length_mm [NUMERICAL] 1237 : body_mass_kg [NUMERICAL] Condition type in nodes: 2890 : HigherCondition Condition type in nodes with depth <= 0: 300 : HigherCondition Condition type in nodes with depth <= 1: 856 : HigherCondition Condition type in nodes with depth <= 2: 1630 : HigherCondition Condition type in nodes with depth <= 3: 2275 : HigherCondition Condition type in nodes with depth <= 5: 2833 : HigherCondition Training OOB: trees: 1, Out-of-bag evaluation: accuracy:0.902174 logloss:3.52601 trees: 11, Out-of-bag evaluation: accuracy:0.895833 logloss:2.18637 trees: 21, Out-of-bag evaluation: accuracy:0.896266 logloss:1.60396 trees: 31, Out-of-bag evaluation: accuracy:0.904564 logloss:1.45657 trees: 41, Out-of-bag evaluation: accuracy:0.917012 logloss:1.32046 trees: 51, Out-of-bag evaluation: accuracy:0.912863 logloss:1.18675 trees: 61, Out-of-bag evaluation: accuracy:0.917012 logloss:1.04504 trees: 71, Out-of-bag evaluation: accuracy:0.917012 logloss:1.04581 trees: 81, Out-of-bag evaluation: accuracy:0.917012 logloss:1.04844 trees: 91, Out-of-bag evaluation: accuracy:0.917012 logloss:1.0457 trees: 101, Out-of-bag evaluation: accuracy:0.917012 logloss:0.907743 trees: 111, Out-of-bag evaluation: accuracy:0.921162 logloss:0.90545 trees: 121, Out-of-bag evaluation: accuracy:0.917012 logloss:0.9075 trees: 131, Out-of-bag evaluation: accuracy:0.917012 logloss:0.908492 trees: 141, Out-of-bag evaluation: accuracy:0.921162 logloss:0.907198 trees: 151, Out-of-bag evaluation: accuracy:0.921162 logloss:0.774951 trees: 161, Out-of-bag evaluation: accuracy:0.921162 logloss:0.776715 trees: 171, Out-of-bag evaluation: accuracy:0.921162 logloss:0.776741 trees: 183, Out-of-bag evaluation: accuracy:0.921162 logloss:0.77779 trees: 193, Out-of-bag evaluation: accuracy:0.921162 logloss:0.77864 trees: 203, Out-of-bag evaluation: accuracy:0.921162 logloss:0.776266 trees: 213, Out-of-bag evaluation: accuracy:0.921162 logloss:0.77733 trees: 223, Out-of-bag evaluation: accuracy:0.921162 logloss:0.77938 trees: 233, Out-of-bag evaluation: accuracy:0.921162 logloss:0.779876 trees: 243, Out-of-bag evaluation: accuracy:0.921162 logloss:0.650293 trees: 253, Out-of-bag evaluation: accuracy:0.917012 logloss:0.520962 trees: 263, Out-of-bag evaluation: accuracy:0.917012 logloss:0.522289 trees: 273, Out-of-bag evaluation: accuracy:0.921162 logloss:0.522673 trees: 283, Out-of-bag evaluation: accuracy:0.921162 logloss:0.523093 trees: 293, Out-of-bag evaluation: accuracy:0.921162 logloss:0.523728 trees: 300, Out-of-bag evaluation: accuracy:0.921162 logloss:0.524026

The following example re-implements the same logic using TensorFlow Feature Columns.

```
def g_to_kg(x):
return x / 1000
feature_columns = [
tf.feature_column.numeric_column("body_mass_g", normalizer_fn=g_to_kg),
tf.feature_column.numeric_column("bill_length_mm"),
]
preprocessing = tf.keras.layers.DenseFeatures(feature_columns)
model_5 = tfdf.keras.RandomForestModel(preprocessing=preprocessing)
model_5.compile(metrics=["accuracy"])
model_5.fit(x=train_ds)
```

4/4 [==============================] - 0s 1ms/step <tensorflow.python.keras.callbacks.History at 0x7fd1aa3490d0>

## Training a regression model

The previous example trains a classification model (TF-DF does not differentiate between binary classification and multi-class classification). In the next example, train a regression model on the Abalone dataset. The objective of this dataset is to predict the number of shell's rings of an abalone.

```
# Download the dataset.
!wget -q https://storage.googleapis.com/download.tensorflow.org/data/abalone_raw.csv -O /tmp/abalone.csv
dataset_df = pd.read_csv("/tmp/abalone.csv")
print(dataset_df.head(3))
```

Type LongestShell Diameter Height WholeWeight ShuckedWeight \ 0 M 0.455 0.365 0.095 0.5140 0.2245 1 M 0.350 0.265 0.090 0.2255 0.0995 2 F 0.530 0.420 0.135 0.6770 0.2565 VisceraWeight ShellWeight Rings 0 0.1010 0.15 15 1 0.0485 0.07 7 2 0.1415 0.21 9

```
# Split the dataset into a training and testing dataset.
train_ds_pd, test_ds_pd = split_dataset(dataset_df)
print("{} examples in training, {} examples for testing.".format(
len(train_ds_pd), len(test_ds_pd)))
# Name of the label column.
label = "Rings"
train_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_ds_pd, label=label, task=tfdf.keras.Task.REGRESSION)
test_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_ds_pd, label=label, task=tfdf.keras.Task.REGRESSION)
```

2913 examples in training, 1264 examples for testing.

```
%set_cell_height 300
# Configure the model.
model_7 = tfdf.keras.RandomForestModel(task = tfdf.keras.Task.REGRESSION)
# Optional.
model_7.compile(metrics=["mse"])
# Train the model.
with sys_pipes():
model_7.fit(x=train_ds)
```

<IPython.core.display.Javascript object> 46/46 [==============================] - 0s 1ms/step [INFO kernel.cc:746] Start Yggdrasil model training [INFO kernel.cc:747] Collect training examples [INFO kernel.cc:392] Number of batches: 46 [INFO kernel.cc:393] Number of examples: 2913 [INFO kernel.cc:769] Dataset: Number of records: 2913 Number of columns: 9 Number of columns by type: NUMERICAL: 8 (88.8889%) CATEGORICAL: 1 (11.1111%) Columns: NUMERICAL: 8 (88.8889%) 0: "Diameter" NUMERICAL mean:0.407719 min:0.055 max:0.65 sd:0.0997924 1: "Height" NUMERICAL mean:0.139617 min:0 max:1.13 sd:0.0429335 2: "LongestShell" NUMERICAL mean:0.523872 min:0.075 max:0.815 sd:0.121004 3: "ShellWeight" NUMERICAL mean:0.239187 min:0.0015 max:1.005 sd:0.140299 4: "ShuckedWeight" NUMERICAL mean:0.359693 min:0.001 max:1.488 sd:0.222965 6: "VisceraWeight" NUMERICAL mean:0.180913 min:0.0005 max:0.76 sd:0.110437 7: "WholeWeight" NUMERICAL mean:0.829425 min:0.002 max:2.8255 sd:0.493682 8: "__LABEL" NUMERICAL mean:9.94439 min:1 max:29 sd:3.2201 CATEGORICAL: 1 (11.1111%) 5: "Type" CATEGORICAL has-dict vocab-size:4 zero-ood-items most-frequent:"M" 1052 (36.114%) Terminology: nas: Number of non-available (i.e. missing) values. ood: Out of dictionary. manually-defined: Attribute which type is manually defined by the user i.e. the type was not automatically inferred. tokenized: The attribute value is obtained through tokenization. has-dict: The attribute is attached to a string dictionary e.g. a categorical attribute stored as a string. vocab-size: Number of unique values. [INFO kernel.cc:772] Configure learner [INFO kernel.cc:797] Training config: learner: "RANDOM_FOREST" features: "Diameter" features: "Height" features: "LongestShell" features: "ShellWeight" features: "ShuckedWeight" features: "Type" features: "VisceraWeight" features: "WholeWeight" label: "__LABEL" task: REGRESSION [yggdrasil_decision_forests.model.random_forest.proto.random_forest_config] { num_trees: 300 decision_tree { max_depth: 16 min_examples: 5 in_split_min_examples_check: true missing_value_policy: GLOBAL_IMPUTATION allow_na_conditions: false categorical_set_greedy_forward { sampling: 0.1 max_num_items: -1 min_item_frequency: 1 } growing_strategy_local { } categorical { cart { } } num_candidate_attributes_ratio: -1 axis_aligned_split { } internal { sorting_strategy: PRESORTED } } winner_take_all_inference: true compute_oob_performances: true compute_oob_variable_importances: false adapt_bootstrap_size_ratio_for_maximum_training_duration: false } [INFO kernel.cc:800] Deployment config: [INFO kernel.cc:837] Train model [INFO random_forest.cc:303] Training random forest on 2913 example(s) and 8 feature(s). [INFO random_forest.cc:578] Training of tree 1/300 (tree index:2) done rmse:2.74324 [INFO random_forest.cc:578] Training of tree 11/300 (tree index:10) done rmse:2.26707 [INFO random_forest.cc:578] Training of tree 21/300 (tree index:21) done rmse:2.17195 [INFO random_forest.cc:578] Training of tree 31/300 (tree index:29) done rmse:2.15851 [INFO random_forest.cc:578] Training of tree 41/300 (tree index:41) done rmse:2.15911 [INFO random_forest.cc:578] Training of tree 51/300 (tree index:52) done rmse:2.15556 [INFO random_forest.cc:578] Training of tree 61/300 (tree index:59) done rmse:2.15008 [INFO random_forest.cc:578] Training of tree 71/300 (tree index:68) done rmse:2.14707 [INFO random_forest.cc:578] Training of tree 81/300 (tree index:78) done rmse:2.15 [INFO random_forest.cc:578] Training of tree 91/300 (tree index:88) done rmse:2.14442 [INFO random_forest.cc:578] Training of tree 101/300 (tree index:99) done rmse:2.14255 [INFO random_forest.cc:578] Training of tree 111/300 (tree index:112) done rmse:2.13911 [INFO random_forest.cc:578] Training of tree 121/300 (tree index:122) done rmse:2.13603 [INFO random_forest.cc:578] Training of tree 131/300 (tree index:131) done rmse:2.1335 [INFO random_forest.cc:578] Training of tree 141/300 (tree index:139) done rmse:2.13602 [INFO random_forest.cc:578] Training of tree 151/300 (tree index:149) done rmse:2.13297 [INFO random_forest.cc:578] Training of tree 161/300 (tree index:162) done rmse:2.1326 [INFO random_forest.cc:578] Training of tree 171/300 (tree index:170) done rmse:2.13156 [INFO random_forest.cc:578] Training of tree 181/300 (tree index:179) done rmse:2.1328 [INFO random_forest.cc:578] Training of tree 191/300 (tree index:189) done rmse:2.13095 [INFO random_forest.cc:578] Training of tree 201/300 (tree index:201) done rmse:2.13145 [INFO random_forest.cc:578] Training of tree 211/300 (tree index:212) done rmse:2.13075 [INFO random_forest.cc:578] Training of tree 221/300 (tree index:221) done rmse:2.12984 [INFO random_forest.cc:578] Training of tree 231/300 (tree index:229) done rmse:2.13135 [INFO random_forest.cc:578] Training of tree 241/300 (tree index:239) done rmse:2.13139 [INFO random_forest.cc:578] Training of tree 251/300 (tree index:252) done rmse:2.13081 [INFO random_forest.cc:578] Training of tree 261/300 (tree index:261) done rmse:2.13043 [INFO random_forest.cc:578] Training of tree 271/300 (tree index:268) done rmse:2.13058 [INFO random_forest.cc:578] Training of tree 281/300 (tree index:278) done rmse:2.13084 [INFO random_forest.cc:578] Training of tree 291/300 (tree index:290) done rmse:2.13123 [INFO random_forest.cc:578] Training of tree 300/300 (tree index:298) done rmse:2.13212 [INFO random_forest.cc:645] Final OOB metrics: rmse:2.13212 [INFO kernel.cc:856] Export model in log directory: /tmp/tmpn11mud5r [INFO kernel.cc:864] Save model in resources [INFO kernel.cc:929] Loading model from path [INFO decision_forest.cc:590] Model loaded with 300 root(s), 258432 node(s), and 8 input feature(s). [INFO kernel.cc:797] Use fast generic engine

```
# Evaluate the model on the test dataset.
evaluation = model_7.evaluate(test_ds, return_dict=True)
print(evaluation)
print()
print(f"MSE: {evaluation['mse']}")
print(f"RMSE: {math.sqrt(evaluation['mse'])}")
```

WARNING:tensorflow:5 out of the last 9 calls to <function CoreModel.make_test_function.<locals>.test_function_trained at 0x7fd1aa2e2ef0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details. WARNING:tensorflow:5 out of the last 9 calls to <function CoreModel.make_test_function.<locals>.test_function_trained at 0x7fd1aa2e2ef0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details. 46/46 [==============================] - 0s 4ms/step - loss: 0.0000e+00 - mse: 1.9022 {'loss': 0.0, 'mse': 1.9022186994552612} MSE: 1.9022186994552612 RMSE: 1.3792094472759608

## Training a ranking model

Finaly, after having trained a classification and a regression models, train a ranking model.

The goal of a ranking is to **order** items by importance. The "value" of
relevance does not matter directly. Ranking a set of *documents* with regard to
a user *query* is an example of ranking problem: It is only important to get the right order, where the top documents matter more.

TF-DF expects for ranking datasets to be presented in a "flat" format. A document+query dataset might look like that:

query | document_id | feature_1 | feature_2 | relevance/label |
---|---|---|---|---|

cat | 1 | 0.1 | blue | 4 |

cat | 2 | 0.5 | green | 1 |

cat | 3 | 0.2 | red | 2 |

dog | 4 | NA | red | 0 |

dog | 5 | 0.2 | red | 1 |

dog | 6 | 0.6 | green | 1 |

The *relevance/label* is a floating point numerical value between 0 and 5
(generally between 0 and 4) where 0 means "completely unrelated", 4 means "very
relevant" and 5 means "the same as the query".

Interestingly, decision forests are often good rankers, and many state-of-the-art ranking models are decision forests.

In this example, use a sample of the
LETOR3
dataset. More precisely, we want to download the `OHSUMED.zip`

from the LETOR3 repo. This dataset is stored in the
libsvm format, so we will need to convert it to csv.

```
%set_cell_height 200
archive_path = tf.keras.utils.get_file("letor.zip",
"https://download.microsoft.com/download/E/7/E/E7EABEF1-4C7B-4E31-ACE5-73927950ED5E/Letor.zip",
extract=True)
# Path to the train and test dataset using libsvm format.
raw_dataset_path = os.path.join(os.path.dirname(archive_path),"OHSUMED/Data/All/OHSUMED.txt")
```

<IPython.core.display.Javascript object> Downloading data from https://download.microsoft.com/download/E/7/E/E7EABEF1-4C7B-4E31-ACE5-73927950ED5E/Letor.zip 61825024/61824018 [==============================] - 2s 0us/step

The dataset is stored as a .txt file in a specific format, so first convert it into a csv file.

```
def convert_libsvm_to_csv(src_path, dst_path):
"""Converts a libsvm ranking dataset into a flat csv file.
Note: This code is specific to the LETOR3 dataset.
"""
dst_handle = open(dst_path, "w")
first_line = True
for src_line in open(src_path,"r"):
# Note: The last 3 items are comments.
items = src_line.split(" ")[:-3]
relevance = items[0]
group = items[1].split(":")[1]
features = [ item.split(":") for item in items[2:]]
if first_line:
# Csv header
dst_handle.write("relevance,group," + ",".join(["f_" + feature[0] for feature in features]) + "\n")
first_line = False
dst_handle.write(relevance + ",g_" + group + "," + (",".join([feature[1] for feature in features])) + "\n")
dst_handle.close()
# Convert the dataset.
csv_dataset_path="/tmp/ohsumed.csv"
convert_libsvm_to_csv(raw_dataset_path, csv_dataset_path)
# Load a dataset into a Pandas Dataframe.
dataset_df = pd.read_csv(csv_dataset_path)
# Display the first 3 examples.
dataset_df.head(3)
```

```
train_ds_pd, test_ds_pd = split_dataset(dataset_df)
print("{} examples in training, {} examples for testing.".format(
len(train_ds_pd), len(test_ds_pd)))
# Display the first 3 examples of the training dataset.
train_ds_pd.head(3)
```

11279 examples in training, 4861 examples for testing.

In this dataset, the `relevance`

defines the ground-truth rank among rows of the same `group`

.

```
# Name of the relevance and grouping columns.
relevance = "relevance"
ranking_train_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_ds_pd, label=relevance, task=tfdf.keras.Task.RANKING)
ranking_test_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_ds_pd, label=relevance, task=tfdf.keras.Task.RANKING)
```

```
%set_cell_height 400
model_8 = tfdf.keras.GradientBoostedTreesModel(
task=tfdf.keras.Task.RANKING,
ranking_group="group",
num_trees=50)
with sys_pipes():
model_8.fit(x=ranking_train_ds)
```

<IPython.core.display.Javascript object> 177/177 [==============================] - 1s 2ms/step [INFO kernel.cc:746] Start Yggdrasil model training [INFO kernel.cc:747] Collect training examples [INFO kernel.cc:392] Number of batches: 177 [INFO kernel.cc:393] Number of examples: 11279 [INFO kernel.cc:769] Dataset: Number of records: 11279 Number of columns: 27 Number of columns by type: NUMERICAL: 26 (96.2963%) HASH: 1 (3.7037%) Columns: NUMERICAL: 26 (96.2963%) 1: "f_1" NUMERICAL mean:1.17298 min:0 max:7 sd:1.11624 2: "f_10" NUMERICAL mean:3.98877 min:0 max:21.0369 sd:3.7682 3: "f_11" NUMERICAL mean:4.54845 min:0 max:59 sd:4.72675 4: "f_12" NUMERICAL mean:2.01149 min:0 max:9.75731 sd:1.64919 5: "f_13" NUMERICAL mean:0.0481248 min:0 max:0.384615 sd:0.0475592 6: "f_14" NUMERICAL mean:0.0470899 min:0 max:0.361682 sd:0.0460568 7: "f_15" NUMERICAL mean:21.6958 min:7.51456 max:40.0616 sd:7.02539 8: "f_16" NUMERICAL mean:6.90344 min:2.01684 max:13.5772 sd:2.23886 9: "f_17" NUMERICAL mean:19.7232 min:9.0472 max:40.1808 sd:6.57119 10: "f_18" NUMERICAL mean:0.200521 min:0 max:1.51088 sd:0.189494 11: "f_19" NUMERICAL mean:20.609 min:0 max:178.097 sd:20.8541 12: "f_2" NUMERICAL mean:0.799579 min:0 max:4.27667 sd:0.749224 13: "f_20" NUMERICAL mean:1.82841 min:0 max:13.4423 sd:1.72707 14: "f_21" NUMERICAL mean:12.2444 min:3.18098 max:45.0899 sd:6.96814 15: "f_22" NUMERICAL mean:2.30804 min:1.15719 max:3.80866 sd:0.676559 16: "f_23" NUMERICAL mean:-6.11895 min:-9.49097 max:-1.85651 sd:2.21482 17: "f_24" NUMERICAL mean:-5.81453 min:-9.22971 max:-0.691579 sd:2.0085 18: "f_25" NUMERICAL mean:-5.98016 min:-9.60073 max:-0.691579 sd:2.21731 19: "f_3" NUMERICAL mean:0.159424 min:0 max:1 sd:0.165221 20: "f_4" NUMERICAL mean:0.147232 min:0 max:0.892574 sd:0.148984 21: "f_5" NUMERICAL mean:27.1684 min:6.3511 max:55.3932 sd:9.4171 22: "f_6" NUMERICAL mean:8.14506 min:2.03154 max:16.8986 sd:2.75622 23: "f_7" NUMERICAL mean:27.6231 min:14.2035 max:55.1926 sd:9.4504 24: "f_8" NUMERICAL mean:0.626431 min:0 max:3.80599 sd:0.606115 25: "f_9" NUMERICAL mean:6.47588 min:0 max:47.7046 sd:6.06894 26: "__LABEL" NUMERICAL mean:0.436918 min:0 max:2 sd:0.724899 HASH: 1 (3.7037%) 0: "__RANK_GROUP" HASH Terminology: nas: Number of non-available (i.e. missing) values. ood: Out of dictionary. manually-defined: Attribute which type is manually defined by the user i.e. the type was not automatically inferred. tokenized: The attribute value is obtained through tokenization. has-dict: The attribute is attached to a string dictionary e.g. a categorical attribute stored as a string. vocab-size: Number of unique values. [INFO kernel.cc:772] Configure learner [WARNING gradient_boosted_trees.cc:1532] Subsample hyperparameter given but sampling method does not match. [WARNING gradient_boosted_trees.cc:1545] GOSS alpha hyperparameter given but GOSS is disabled. [WARNING gradient_boosted_trees.cc:1554] GOSS beta hyperparameter given but GOSS is disabled. [WARNING gradient_boosted_trees.cc:1566] SelGB ratio hyperparameter given but SelGB is disabled. [INFO kernel.cc:797] Training config: learner: "GRADIENT_BOOSTED_TREES" features: "__RANK_GROUP" features: "f_1" features: "f_10" features: "f_11" features: "f_12" features: "f_13" features: "f_14" features: "f_15" features: "f_16" features: "f_17" features: "f_18" features: "f_19" features: "f_2" features: "f_20" features: "f_21" features: "f_22" features: "f_23" features: "f_24" features: "f_25" features: "f_3" features: "f_4" features: "f_5" features: "f_6" features: "f_7" features: "f_8" features: "f_9" label: "__LABEL" task: RANKING ranking_group: "__RANK_GROUP" [yggdrasil_decision_forests.model.gradient_boosted_trees.proto.gradient_boosted_trees_config] { num_trees: 50 decision_tree { max_depth: 6 min_examples: 5 in_split_min_examples_check: true missing_value_policy: GLOBAL_IMPUTATION allow_na_conditions: false categorical_set_greedy_forward { sampling: 0.1 max_num_items: -1 min_item_frequency: 1 } growing_strategy_local { } categorical { cart { } } num_candidate_attributes_ratio: -1 axis_aligned_split { } internal { sorting_strategy: PRESORTED } } shrinkage: 0.1 validation_set_ratio: 0.1 early_stopping: VALIDATION_LOSS_INCREASE early_stopping_num_trees_look_ahead: 30 l2_regularization: 0 lambda_loss: 1 mart { } adapt_subsample_for_maximum_training_duration: false l1_regularization: 0 use_hessian_gain: false l2_regularization_categorical: 1 } [INFO kernel.cc:800] Deployment config: [INFO kernel.cc:837] Train model [INFO abstract_learner.cc:125] The ranking_group "__RANK_GROUP" was removed from the input feature set. [INFO gradient_boosted_trees.cc:480] Default loss set to LAMBDA_MART_NDCG5 [INFO gradient_boosted_trees.cc:2122] Split training/validation dataset by "__RANK_GROUP". 106 groups found in 11279 examples i.e. 106.406 examples/groups. [INFO gradient_boosted_trees_loss.cc:1231] Found 97 groups in 10238 examples. [INFO gradient_boosted_trees_loss.cc:1231] Found 9 groups in 1041 examples. [INFO gradient_boosted_trees.cc:1358] num-trees:1 train-loss:-0.374987 train-NDCG@5:0.374987 valid-loss:-0.504338 valid-NDCG@5:0.504338 [INFO gradient_boosted_trees.cc:2506] Early stop of the training because the validation loss does not decrease anymore. Best valid-loss: -0.584718 [INFO gradient_boosted_trees.cc:319] Truncates the model to 17 tree(s) i.e. 17 iteration(s). [INFO gradient_boosted_trees.cc:348] Final model valid-loss:-0.584718 valid-NDCG@5:0.584718 [INFO kernel.cc:856] Export model in log directory: /tmp/tmpg20rm8nc [INFO kernel.cc:864] Save model in resources [INFO kernel.cc:929] Loading model from path [INFO abstract_model.cc:876] Engine "GradientBoostedTreesQuickScorerExtended" built [INFO kernel.cc:797] Use fast generic engine

At this point, keras does not propose any ranking metrics. Instead, the training and validation (a GBDT uses a validation dataset) are shown in the training
logs. In this case the loss is `LAMBDA_MART_NDCG5`

, and the final (i.e. at
the end of the training) NDCG (normalized discounted cumulative gain) is `0.510136`

(see line `Final model valid-loss: -0.510136`

).

Note that the NDCG is a value between 0 and 1. The larget the NDCG, the better the model. For this reason, the loss to be -NDCG.

As before, the model can be analysed:

```
%set_cell_height 400
model_8.summary()
```

<IPython.core.display.Javascript object> Model: "gradient_boosted_trees_model_5" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= Total params: 1 Trainable params: 0 Non-trainable params: 1 _________________________________________________________________ Type: "GRADIENT_BOOSTED_TREES" Task: RANKING Label: "__LABEL" Rank group: "__RANK_GROUP" Input Features (25): f_1 f_10 f_11 f_12 f_13 f_14 f_15 f_16 f_17 f_18 f_19 f_2 f_20 f_21 f_22 f_23 f_24 f_25 f_3 f_4 f_5 f_6 f_7 f_8 f_9 No weights Variable Importance: NUM_NODES: 1. "f_20" 26.000000 ################ 2. "f_8" 24.000000 ############## 3. "f_21" 22.000000 ############# 4. "f_23" 22.000000 ############# 5. "f_22" 21.000000 ############ 6. "f_4" 18.000000 ########## 7. "f_10" 16.000000 ######### 8. "f_17" 14.000000 ######## 9. "f_12" 11.000000 ###### 10. "f_9" 11.000000 ###### 11. "f_19" 7.000000 ### 12. "f_25" 7.000000 ### 13. "f_13" 5.000000 ## 14. "f_15" 5.000000 ## 15. "f_24" 5.000000 ## 16. "f_6" 5.000000 ## 17. "f_11" 4.000000 # 18. "f_5" 4.000000 # 19. "f_14" 3.000000 # 20. "f_16" 3.000000 # 21. "f_7" 3.000000 # 22. "f_2" 2.000000 23. "f_18" 1.000000 24. "f_3" 1.000000 Variable Importance: NUM_AS_ROOT: 1. "f_4" 8.000000 ################ 2. "f_8" 8.000000 ################ 3. "f_21" 1.000000 Variable Importance: SUM_SCORE: 1. "f_8" 4341.527551 ################ 2. "f_22" 3157.146618 ########### 3. "f_21" 3104.641964 ########### 4. "f_4" 2506.020570 ######### 5. "f_17" 2427.139801 ######## 6. "f_20" 2215.593718 ######## 7. "f_23" 1711.683672 ###### 8. "f_10" 1583.054270 ##### 9. "f_12" 1336.363784 #### 10. "f_9" 642.749957 ## 11. "f_16" 471.770836 # 12. "f_7" 413.087204 # 13. "f_25" 361.348265 # 14. "f_6" 335.215953 # 15. "f_24" 331.329976 # 16. "f_15" 268.796355 17. "f_19" 244.829229 18. "f_5" 243.232028 19. "f_13" 133.990157 20. "f_11" 87.437019 21. "f_14" 76.274135 22. "f_2" 45.033420 23. "f_3" 34.370324 24. "f_18" 18.726494 Variable Importance: MEAN_MIN_DEPTH: 1. "__RANK_GROUP" 4.182878 ################ 2. "f_1" 4.182878 ################ 3. "__LABEL" 4.182878 ################ 4. "f_18" 4.176995 ############### 5. "f_3" 4.172182 ############### 6. "f_14" 4.162616 ############### 7. "f_2" 4.150198 ############### 8. "f_13" 4.138760 ############### 9. "f_11" 4.130590 ############### 10. "f_7" 4.120222 ############### 11. "f_5" 4.119799 ############### 12. "f_15" 4.115519 ############### 13. "f_16" 4.112289 ############### 14. "f_19" 4.092860 ############### 15. "f_6" 4.092682 ############### 16. "f_24" 4.089740 ############### 17. "f_12" 4.069136 ############### 18. "f_9" 4.027649 ############## 19. "f_25" 4.009300 ############## 20. "f_10" 3.861148 ############# 21. "f_20" 3.794699 ############# 22. "f_17" 3.418966 ########## 23. "f_23" 3.246011 ######### 24. "f_21" 2.889391 ####### 25. "f_22" 2.888251 ####### 26. "f_4" 2.003586 # 27. "f_8" 1.773183 Loss: LAMBDA_MART_NDCG5 Validation loss value: -0.584718 Number of trees per iteration: 1 Number of trees: 17 Total number of nodes: 497 Number of nodes by tree: Count: 17 Average: 29.2353 StdDev: 6.71722 Min: 21 Max: 39 Ignored: 0 ---------------------------------------------- [ 21, 22) 3 17.65% 17.65% ######## [ 22, 23) 0 0.00% 17.65% [ 23, 24) 3 17.65% 35.29% ######## [ 24, 25) 0 0.00% 35.29% [ 25, 26) 1 5.88% 41.18% ### [ 26, 27) 0 0.00% 41.18% [ 27, 28) 0 0.00% 41.18% [ 28, 29) 0 0.00% 41.18% [ 29, 30) 4 23.53% 64.71% ########## [ 30, 31) 0 0.00% 64.71% [ 31, 32) 0 0.00% 64.71% [ 32, 33) 0 0.00% 64.71% [ 33, 34) 1 5.88% 70.59% ### [ 34, 35) 0 0.00% 70.59% [ 35, 36) 1 5.88% 76.47% ### [ 36, 37) 0 0.00% 76.47% [ 37, 38) 0 0.00% 76.47% [ 38, 39) 0 0.00% 76.47% [ 39, 39] 4 23.53% 100.00% ########## Depth by leafs: Count: 257 Average: 4.24125 StdDev: 0.89756 Min: 2 Max: 5 Ignored: 0 ---------------------------------------------- [ 2, 3) 12 4.67% 4.67% # [ 3, 4) 44 17.12% 21.79% ### [ 4, 5) 71 27.63% 49.42% ##### [ 5, 5] 130 50.58% 100.00% ########## Number of training obs by leaf: Count: 257 Average: 677.222 StdDev: 2223.79 Min: 5 Max: 9958 Ignored: 0 ---------------------------------------------- [ 5, 502) 228 88.72% 88.72% ########## [ 502, 1000) 3 1.17% 89.88% [ 1000, 1498) 4 1.56% 91.44% [ 1498, 1995) 2 0.78% 92.22% [ 1995, 2493) 0 0.00% 92.22% [ 2493, 2991) 1 0.39% 92.61% [ 2991, 3488) 2 0.78% 93.39% [ 3488, 3986) 0 0.00% 93.39% [ 3986, 4484) 0 0.00% 93.39% [ 4484, 4982) 1 0.39% 93.77% [ 4982, 5479) 0 0.00% 93.77% [ 5479, 5977) 0 0.00% 93.77% [ 5977, 6475) 0 0.00% 93.77% [ 6475, 6972) 2 0.78% 94.55% [ 6972, 7470) 1 0.39% 94.94% [ 7470, 7968) 0 0.00% 94.94% [ 7968, 8465) 0 0.00% 94.94% [ 8465, 8963) 3 1.17% 96.11% [ 8963, 9461) 2 0.78% 96.89% [ 9461, 9958] 8 3.11% 100.00% Attribute in nodes: 26 : f_20 [NUMERICAL] 24 : f_8 [NUMERICAL] 22 : f_23 [NUMERICAL] 22 : f_21 [NUMERICAL] 21 : f_22 [NUMERICAL] 18 : f_4 [NUMERICAL] 16 : f_10 [NUMERICAL] 14 : f_17 [NUMERICAL] 11 : f_9 [NUMERICAL] 11 : f_12 [NUMERICAL] 7 : f_25 [NUMERICAL] 7 : f_19 [NUMERICAL] 5 : f_6 [NUMERICAL] 5 : f_24 [NUMERICAL] 5 : f_15 [NUMERICAL] 5 : f_13 [NUMERICAL] 4 : f_5 [NUMERICAL] 4 : f_11 [NUMERICAL] 3 : f_7 [NUMERICAL] 3 : f_16 [NUMERICAL] 3 : f_14 [NUMERICAL] 2 : f_2 [NUMERICAL] 1 : f_3 [NUMERICAL] 1 : f_18 [NUMERICAL] Attribute in nodes with depth <= 0: 8 : f_8 [NUMERICAL] 8 : f_4 [NUMERICAL] 1 : f_21 [NUMERICAL] Attribute in nodes with depth <= 1: 13 : f_22 [NUMERICAL] 9 : f_8 [NUMERICAL] 9 : f_21 [NUMERICAL] 8 : f_4 [NUMERICAL] 5 : f_17 [NUMERICAL] 2 : f_25 [NUMERICAL] 1 : f_7 [NUMERICAL] 1 : f_24 [NUMERICAL] 1 : f_23 [NUMERICAL] 1 : f_12 [NUMERICAL] 1 : f_10 [NUMERICAL] Attribute in nodes with depth <= 2: 16 : f_8 [NUMERICAL] 16 : f_22 [NUMERICAL] 12 : f_23 [NUMERICAL] 11 : f_4 [NUMERICAL] 10 : f_21 [NUMERICAL] 10 : f_20 [NUMERICAL] 8 : f_17 [NUMERICAL] 6 : f_25 [NUMERICAL] 3 : f_19 [NUMERICAL] 3 : f_16 [NUMERICAL] 2 : f_7 [NUMERICAL] 2 : f_6 [NUMERICAL] 2 : f_5 [NUMERICAL] 2 : f_10 [NUMERICAL] 1 : f_24 [NUMERICAL] 1 : f_13 [NUMERICAL] 1 : f_12 [NUMERICAL] 1 : f_11 [NUMERICAL] Attribute in nodes with depth <= 3: 20 : f_8 [NUMERICAL] 19 : f_22 [NUMERICAL] 18 : f_23 [NUMERICAL] 17 : f_4 [NUMERICAL] 16 : f_21 [NUMERICAL] 16 : f_20 [NUMERICAL] 11 : f_17 [NUMERICAL] 9 : f_10 [NUMERICAL] 8 : f_12 [NUMERICAL] 7 : f_25 [NUMERICAL] 6 : f_9 [NUMERICAL] 5 : f_19 [NUMERICAL] 3 : f_6 [NUMERICAL] 3 : f_5 [NUMERICAL] 3 : f_24 [NUMERICAL] 3 : f_16 [NUMERICAL] 3 : f_15 [NUMERICAL] 2 : f_7 [NUMERICAL] 2 : f_13 [NUMERICAL] 2 : f_11 [NUMERICAL] 1 : f_2 [NUMERICAL] 1 : f_14 [NUMERICAL] Attribute in nodes with depth <= 5: 26 : f_20 [NUMERICAL] 24 : f_8 [NUMERICAL] 22 : f_23 [NUMERICAL] 22 : f_21 [NUMERICAL] 21 : f_22 [NUMERICAL] 18 : f_4 [NUMERICAL] 16 : f_10 [NUMERICAL] 14 : f_17 [NUMERICAL] 11 : f_9 [NUMERICAL] 11 : f_12 [NUMERICAL] 7 : f_25 [NUMERICAL] 7 : f_19 [NUMERICAL] 5 : f_6 [NUMERICAL] 5 : f_24 [NUMERICAL] 5 : f_15 [NUMERICAL] 5 : f_13 [NUMERICAL] 4 : f_5 [NUMERICAL] 4 : f_11 [NUMERICAL] 3 : f_7 [NUMERICAL] 3 : f_16 [NUMERICAL] 3 : f_14 [NUMERICAL] 2 : f_2 [NUMERICAL] 1 : f_3 [NUMERICAL] 1 : f_18 [NUMERICAL] Condition type in nodes: 240 : HigherCondition Condition type in nodes with depth <= 0: 17 : HigherCondition Condition type in nodes with depth <= 1: 51 : HigherCondition Condition type in nodes with depth <= 2: 107 : HigherCondition Condition type in nodes with depth <= 3: 175 : HigherCondition Condition type in nodes with depth <= 5: 240 : HigherCondition