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`

Wurlitzer is needed to display the detailed training logs in Colabs (when using `verbose=2`

in the model constructor).

`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
```

WARNING:root:TF Parameter Server distributed training not available (this is expected for the pre-build release).

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.2.4

## 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)))
```

236 examples in training, 108 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)
```

/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow_decision_forests/keras/core.py:2036: FutureWarning: In a future version of pandas all arguments of DataFrame.drop except for the argument 'labels' will be keyword-only features_dataframe = dataframe.drop(label, 1)

**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()
# Train the model.
model_1.fit(x=train_ds)
```

<IPython.core.display.Javascript object> Use /tmp/tmp6me1pn0g as temporary training directory Starting reading the dataset 1/1 [==============================] - ETA: 0s Dataset read in 0:00:03.315373 Training model Model trained in 0:00:00.025709 Compiling model 1/1 [==============================] - 3s 3s/step [INFO kernel.cc:1153] Loading model from path [INFO abstract_model.cc:1063] Engine "RandomForestGeneric" built [INFO kernel.cc:1001] Use fast generic engine WARNING:tensorflow:AutoGraph could not transform <function simple_ml_inference_op_with_handle at 0x7f6580d04cb0> and will run it as-is. Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: could not get source code To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert WARNING:tensorflow:AutoGraph could not transform <function simple_ml_inference_op_with_handle at 0x7f6580d04cb0> and will run it as-is. Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: could not get source code To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert WARNING: AutoGraph could not transform <function simple_ml_inference_op_with_handle at 0x7f6580d04cb0> and will run it as-is. Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: could not get source code To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert <keras.callbacks.History at 0x7f65ec8849d0>

### 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.
- Add a
`verbose`

argument to`RandomForestModel`

to control the amount of displayed training logs. Set`verbose=0`

to hide most of the logs. Set`verbose=2`

to show all the logs.

## Evaluate the model

Let's evaluate our model on the test dataset.

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

1/1 [==============================] - 0s 292ms/step - loss: 0.0000e+00 - accuracy: 1.0000 loss: 0.0000 accuracy: 1.0000

**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")
```

2022-04-19 11:16:01.402841: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them. WARNING:absl:Found untraced functions such as call_get_leaves while saving (showing 1 of 1). These functions will not be directly callable after loading. 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: MEAN_MIN_DEPTH: 1. "__LABEL" 3.280961 ################ 2. "year" 3.260605 ############### 3. "sex" 3.207424 ############### 4. "body_mass_g" 2.809716 ############ 5. "island" 2.144323 ####### 6. "bill_depth_mm" 2.056055 ###### 7. "flipper_length_mm" 1.616061 ### 8. "bill_length_mm" 1.201421 Variable Importance: NUM_AS_ROOT: 1. "flipper_length_mm" 120.000000 ################ 2. "bill_length_mm" 93.000000 ############ 3. "bill_depth_mm" 70.000000 ######### 4. "island" 16.000000 ## 5. "body_mass_g" 1.000000 Variable Importance: NUM_NODES: 1. "bill_length_mm" 715.000000 ################ 2. "bill_depth_mm" 390.000000 ######## 3. "flipper_length_mm" 349.000000 ####### 4. "island" 307.000000 ###### 5. "body_mass_g" 280.000000 ###### 6. "sex" 49.000000 7. "year" 18.000000 Variable Importance: SUM_SCORE: 1. "bill_length_mm" 26762.987352 ################ 2. "flipper_length_mm" 18170.776541 ########## 3. "bill_depth_mm" 11901.538405 ####### 4. "island" 11507.267366 ###### 5. "body_mass_g" 2007.039783 # 6. "sex" 385.181357 7. "year" 44.290259 Winner take all: true Out-of-bag evaluation: accuracy:0.974576 logloss:0.108678 Number of trees: 300 Total number of nodes: 4516 Number of nodes by tree: Count: 300 Average: 15.0533 StdDev: 3.22859 Min: 9 Max: 29 Ignored: 0 ---------------------------------------------- [ 9, 10) 7 2.33% 2.33% # [ 10, 11) 0 0.00% 2.33% [ 11, 12) 42 14.00% 16.33% ##### [ 12, 13) 0 0.00% 16.33% [ 13, 14) 69 23.00% 39.33% ######## [ 14, 15) 0 0.00% 39.33% [ 15, 16) 85 28.33% 67.67% ########## [ 16, 17) 0 0.00% 67.67% [ 17, 18) 49 16.33% 84.00% ###### [ 18, 19) 0 0.00% 84.00% [ 19, 20) 27 9.00% 93.00% ### [ 20, 21) 0 0.00% 93.00% [ 21, 22) 13 4.33% 97.33% ## [ 22, 23) 0 0.00% 97.33% [ 23, 24) 3 1.00% 98.33% [ 24, 25) 0 0.00% 98.33% [ 25, 26) 3 1.00% 99.33% [ 26, 27) 0 0.00% 99.33% [ 27, 28) 1 0.33% 99.67% [ 28, 29] 1 0.33% 100.00% Depth by leafs: Count: 2408 Average: 3.35507 StdDev: 1.06465 Min: 1 Max: 7 Ignored: 0 ---------------------------------------------- [ 1, 2) 10 0.42% 0.42% [ 2, 3) 585 24.29% 24.71% ######## [ 3, 4) 743 30.86% 55.56% ########## [ 4, 5) 748 31.06% 86.63% ########## [ 5, 6) 270 11.21% 97.84% #### [ 6, 7) 36 1.50% 99.34% [ 7, 7] 16 0.66% 100.00% Number of training obs by leaf: Count: 2408 Average: 29.402 StdDev: 30.6362 Min: 5 Max: 118 Ignored: 0 ---------------------------------------------- [ 5, 10) 1226 50.91% 50.91% ########## [ 10, 16) 122 5.07% 55.98% # [ 16, 22) 68 2.82% 58.80% # [ 22, 27) 49 2.03% 60.84% [ 27, 33) 74 3.07% 63.91% # [ 33, 39) 108 4.49% 68.40% # [ 39, 44) 72 2.99% 71.39% # [ 44, 50) 85 3.53% 74.92% # [ 50, 56) 45 1.87% 76.79% [ 56, 62) 54 2.24% 79.03% [ 62, 67) 46 1.91% 80.94% [ 67, 73) 77 3.20% 84.14% # [ 73, 79) 109 4.53% 88.66% # [ 79, 84) 81 3.36% 92.03% # [ 84, 90) 65 2.70% 94.73% # [ 90, 96) 54 2.24% 96.97% [ 96, 101) 35 1.45% 98.42% [ 101, 107) 25 1.04% 99.46% [ 107, 113) 11 0.46% 99.92% [ 113, 118] 2 0.08% 100.00% Attribute in nodes: 715 : bill_length_mm [NUMERICAL] 390 : bill_depth_mm [NUMERICAL] 349 : flipper_length_mm [NUMERICAL] 307 : island [CATEGORICAL] 280 : body_mass_g [NUMERICAL] 49 : sex [CATEGORICAL] 18 : year [NUMERICAL] Attribute in nodes with depth <= 0: 120 : flipper_length_mm [NUMERICAL] 93 : bill_length_mm [NUMERICAL] 70 : bill_depth_mm [NUMERICAL] 16 : island [CATEGORICAL] 1 : body_mass_g [NUMERICAL] Attribute in nodes with depth <= 1: 263 : bill_length_mm [NUMERICAL] 203 : flipper_length_mm [NUMERICAL] 192 : bill_depth_mm [NUMERICAL] 167 : island [CATEGORICAL] 65 : body_mass_g [NUMERICAL] Attribute in nodes with depth <= 2: 463 : bill_length_mm [NUMERICAL] 294 : flipper_length_mm [NUMERICAL] 292 : bill_depth_mm [NUMERICAL] 263 : island [CATEGORICAL] 158 : body_mass_g [NUMERICAL] 13 : sex [CATEGORICAL] 2 : year [NUMERICAL] Attribute in nodes with depth <= 3: 642 : bill_length_mm [NUMERICAL] 363 : bill_depth_mm [NUMERICAL] 337 : flipper_length_mm [NUMERICAL] 296 : island [CATEGORICAL] 249 : body_mass_g [NUMERICAL] 38 : sex [CATEGORICAL] 7 : year [NUMERICAL] Attribute in nodes with depth <= 5: 710 : bill_length_mm [NUMERICAL] 390 : bill_depth_mm [NUMERICAL] 349 : flipper_length_mm [NUMERICAL] 307 : island [CATEGORICAL] 278 : body_mass_g [NUMERICAL] 49 : sex [CATEGORICAL] 17 : year [NUMERICAL] Condition type in nodes: 1752 : HigherCondition 356 : ContainsBitmapCondition Condition type in nodes with depth <= 0: 284 : HigherCondition 16 : ContainsBitmapCondition Condition type in nodes with depth <= 1: 723 : HigherCondition 167 : ContainsBitmapCondition Condition type in nodes with depth <= 2: 1209 : HigherCondition 276 : ContainsBitmapCondition Condition type in nodes with depth <= 3: 1598 : HigherCondition 334 : ContainsBitmapCondition Condition type in nodes with depth <= 5: 1744 : HigherCondition 356 : ContainsBitmapCondition Node format: NOT_SET Training OOB: trees: 1, Out-of-bag evaluation: accuracy:0.94186 logloss:2.09556 trees: 12, Out-of-bag evaluation: accuracy:0.940426 logloss:1.28487 trees: 22, Out-of-bag evaluation: accuracy:0.95339 logloss:0.390486 trees: 32, Out-of-bag evaluation: accuracy:0.974576 logloss:0.391091 trees: 42, Out-of-bag evaluation: accuracy:0.978814 logloss:0.386502 trees: 52, Out-of-bag evaluation: accuracy:0.974576 logloss:0.387766 trees: 62, Out-of-bag evaluation: accuracy:0.974576 logloss:0.391257 trees: 72, Out-of-bag evaluation: accuracy:0.978814 logloss:0.390902 trees: 82, Out-of-bag evaluation: accuracy:0.978814 logloss:0.388326 trees: 92, Out-of-bag evaluation: accuracy:0.978814 logloss:0.388357 trees: 102, Out-of-bag evaluation: accuracy:0.978814 logloss:0.246323 trees: 114, Out-of-bag evaluation: accuracy:0.974576 logloss:0.247876 trees: 124, Out-of-bag evaluation: accuracy:0.966102 logloss:0.248823 trees: 134, Out-of-bag evaluation: accuracy:0.961864 logloss:0.249112 trees: 144, Out-of-bag evaluation: accuracy:0.961864 logloss:0.249749 trees: 154, Out-of-bag evaluation: accuracy:0.961864 logloss:0.249416 trees: 164, Out-of-bag evaluation: accuracy:0.966102 logloss:0.24757 trees: 174, Out-of-bag evaluation: accuracy:0.970339 logloss:0.246334 trees: 184, Out-of-bag evaluation: accuracy:0.970339 logloss:0.245399 trees: 194, Out-of-bag evaluation: accuracy:0.966102 logloss:0.246147 trees: 204, Out-of-bag evaluation: accuracy:0.966102 logloss:0.245177 trees: 214, Out-of-bag evaluation: accuracy:0.966102 logloss:0.246102 trees: 224, Out-of-bag evaluation: accuracy:0.961864 logloss:0.245869 trees: 234, Out-of-bag evaluation: accuracy:0.966102 logloss:0.24546 trees: 244, Out-of-bag evaluation: accuracy:0.970339 logloss:0.112047 trees: 254, Out-of-bag evaluation: accuracy:0.970339 logloss:0.11123 trees: 264, Out-of-bag evaluation: accuracy:0.970339 logloss:0.108868 trees: 274, Out-of-bag evaluation: accuracy:0.970339 logloss:0.108434 trees: 284, Out-of-bag evaluation: accuracy:0.970339 logloss:0.107632 trees: 295, Out-of-bag evaluation: accuracy:0.970339 logloss:0.107871 trees: 300, Out-of-bag evaluation: accuracy:0.974576 logloss:0.108678

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), 120.0), ("bill_length_mm" (1; #1), 93.0), ("bill_depth_mm" (1; #0), 70.0), ("island" (4; #4), 16.0), ("body_mass_g" (1; #2), 1.0)], 'MEAN_MIN_DEPTH': [("__LABEL" (4; #7), 3.280960604210599), ("year" (1; #6), 3.2606045898545846), ("sex" (4; #5), 3.207423927923923), ("body_mass_g" (1; #2), 2.809716228216225), ("island" (4; #4), 2.1443225755725748), ("bill_depth_mm" (1; #0), 2.0560545380545374), ("flipper_length_mm" (1; #3), 1.6160606800606798), ("bill_length_mm" (1; #1), 1.2014205146705157)], 'SUM_SCORE': [("bill_length_mm" (1; #1), 26762.987352006137), ("flipper_length_mm" (1; #3), 18170.776540881954), ("bill_depth_mm" (1; #0), 11901.538405206986), ("island" (4; #4), 11507.26736571081), ("body_mass_g" (1; #2), 2007.0397834228352), ("sex" (4; #5), 385.18135726079345), ("year" (1; #6), 44.290259033441544)], 'NUM_NODES': [("bill_length_mm" (1; #1), 715.0), ("bill_depth_mm" (1; #0), 390.0), ("flipper_length_mm" (1; #3), 349.0), ("island" (4; #4), 307.0), ("body_mass_g" (1; #2), 280.0), ("sex" (4; #5), 49.0), ("year" (1; #6), 18.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=236, accuracy=0.9745762711864406, loss=0.10867847165613735, 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.9418604651162791, loss=2.095561138419218, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=12, evaluation=Evaluation(num_examples=235, accuracy=0.9404255319148936, loss=1.284872737336666, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=22, evaluation=Evaluation(num_examples=236, accuracy=0.9533898305084746, loss=0.39048642611478346, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=32, evaluation=Evaluation(num_examples=236, accuracy=0.9745762711864406, loss=0.3910905674920749, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=42, evaluation=Evaluation(num_examples=236, accuracy=0.9788135593220338, loss=0.38650180805095674, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=52, evaluation=Evaluation(num_examples=236, accuracy=0.9745762711864406, loss=0.38776641405361184, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=62, evaluation=Evaluation(num_examples=236, accuracy=0.9745762711864406, loss=0.39125654724884334, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=72, evaluation=Evaluation(num_examples=236, accuracy=0.9788135593220338, loss=0.3909018231255902, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=82, evaluation=Evaluation(num_examples=236, accuracy=0.9788135593220338, loss=0.3883263948057794, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=92, evaluation=Evaluation(num_examples=236, accuracy=0.9788135593220338, loss=0.38835708283961323, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=102, evaluation=Evaluation(num_examples=236, accuracy=0.9788135593220338, loss=0.24632317714109006, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=114, evaluation=Evaluation(num_examples=236, accuracy=0.9745762711864406, loss=0.24787567710598646, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=124, evaluation=Evaluation(num_examples=236, accuracy=0.9661016949152542, loss=0.2488230452793887, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=134, evaluation=Evaluation(num_examples=236, accuracy=0.961864406779661, loss=0.24911191773806082, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=144, evaluation=Evaluation(num_examples=236, accuracy=0.961864406779661, loss=0.24974867270596451, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=154, evaluation=Evaluation(num_examples=236, accuracy=0.961864406779661, loss=0.24941576454567455, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=164, evaluation=Evaluation(num_examples=236, accuracy=0.9661016949152542, loss=0.24756958704220794, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=174, evaluation=Evaluation(num_examples=236, accuracy=0.9703389830508474, loss=0.24633406362717308, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=184, evaluation=Evaluation(num_examples=236, accuracy=0.9703389830508474, loss=0.245399254121644, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=194, evaluation=Evaluation(num_examples=236, accuracy=0.9661016949152542, loss=0.2461469640552808, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=204, evaluation=Evaluation(num_examples=236, accuracy=0.9661016949152542, loss=0.24517727281771978, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=214, evaluation=Evaluation(num_examples=236, accuracy=0.9661016949152542, loss=0.24610210644965202, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=224, evaluation=Evaluation(num_examples=236, accuracy=0.961864406779661, loss=0.24586882274518956, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=234, evaluation=Evaluation(num_examples=236, accuracy=0.9661016949152542, loss=0.24545953160751674, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=244, evaluation=Evaluation(num_examples=236, accuracy=0.9703389830508474, loss=0.11204697870870389, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=254, evaluation=Evaluation(num_examples=236, accuracy=0.9703389830508474, loss=0.11123040572629642, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=264, evaluation=Evaluation(num_examples=236, accuracy=0.9703389830508474, loss=0.1088680922077432, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=274, evaluation=Evaluation(num_examples=236, accuracy=0.9703389830508474, loss=0.10843369439717825, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=284, evaluation=Evaluation(num_examples=236, accuracy=0.9703389830508474, loss=0.10763167934413305, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=295, evaluation=Evaluation(num_examples=236, accuracy=0.9703389830508474, loss=0.1078709541559535, rmse=None, ndcg=None, aucs=None)), TrainLog(num_trees=300, evaluation=Evaluation(num_examples=236, accuracy=0.9745762711864406, loss=0.10867847165613735, 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")
```

```
# docs_infra: no_execute
# 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, tensorflow_decision_forests.keras.DistributedGradientBoostedTreesModel]

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, Task.CATEGORICAL_UPLIFT). | 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. | postprocessing: Like "preprocessing" but applied on the model output. | 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`. | uplift_treatment: Only for task=Task.CATEGORICAL_UPLIFT. Name of an integer | feature that identifies the treatment in an uplift problem. The value 0 is | reserved for the control treatment. | temp_directory: Temporary directory used to store the model Assets after the | training, and possibly as a work directory during the training. This | temporary directory is necessary for the model to be exported after | training e.g. `model.save(path)`. If not specified, `temp_directory` is | set to a temporary directory using `tempfile.TemporaryDirectory`. This | directory is deleted when the model python object is garbage-collected. | verbose: Verbosity mode. 0 = silent, 1 = small details, 2 = full details. | 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. | num_threads: Number of threads used to train the model. Different learning | algorithms use multi-threading differently and with different degree of | efficiency. If `None`, `num_threads` will be automatically set to the | number of processors (up to a maximum of 32; or set to 6 if the number of | processors is not available). | Making `num_threads` significantly larger than the number of processors | can slow-down the training speed. The default value logic might change in | the future. | name: The name of the model. | max_vocab_count: Default maximum size of the vocabulary for CATEGORICAL and | CATEGORICAL_SET features stored as strings. If more unique values exist, | only the most frequent values are kept, and the remaining values are | considered as out-of-vocabulary. The value `max_vocab_count` defined in a | `FeatureUsage` (if any) takes precedence. | try_resume_training: If true, the model training resumes from the checkpoint | stored in the `temp_directory` directory. If `temp_directory` does not | contain any model checkpoint, the training start from the beginning. | Resuming training is useful in the following situations: (1) The training | was interrupted by the user (e.g. ctrl+c or "stop" button in a | notebook). (2) the training job was interrupted (e.g. rescheduling), ond | (3) the hyper-parameter of the model were changed such that an initially | completed training is now incomplete (e.g. increasing the number of | trees). | Note: Training can only be resumed if the training datasets is exactly the | same (i.e. no reshuffle in the tf.data.Dataset). | check_dataset: If set to true, test if the dataset is well configured for | the training: (1) Check if the dataset does contains any `repeat` | operations, (2) Check if the dataset does contain a `batch` operation, | (3) Check if the dataset has a large enough batch size (min 100 if the | dataset contains more than 1k examples or if the number of examples is | not available) If set to false, do not run any test. | 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. | bootstrap_size_ratio: Number of examples used to train each trees; | expressed as a ratio of the training dataset size. Default: 1.0. | bootstrap_training_dataset: If true (default), each tree is trained on a | separate dataset sampled with replacement from the original dataset. If | false, all the trees are trained on the entire same dataset. If | bootstrap_training_dataset:false, OOB metrics are not available. | bootstrap_training_dataset=false is used in "Extremely randomized trees" | (https://link.springer.com/content/pdf/10.1007%2Fs10994-006-6226-1.pdf). | Default: True. | 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". | honest: In honest trees, different training examples are used to infer the | structure and the leaf values. This regularization technique trades | examples for bias estimates. It might increase or reduce the quality of | the model. See "Generalized Random Forests", Athey et al. In this paper, | Honest tree are trained with the Random Forest algorithm with a sampling | without replacement. Default: False. | 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. | keep_non_leaf_label_distribution: Whether to keep the node value (i.e. the | distribution of the labels of the training examples) of non-leaf nodes. | This information is not used during serving, however it can be used for | model interpretation as well as hyper parameter tuning. This can take | lots of space, sometimes accounting for half of the model size. 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_model_size_in_memory_in_bytes: Limit the size of the model when | stored in ram. Different algorithms can enforce this limit differently. | Note that when models are compiled into an inference, the size of the | inference engine is generally much smaller than the original model. | Default: -1.0. | 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_oob_variable_importances_permutations: Number of time the dataset is | re-shuffled to compute the permutation variable importances. Increasing | this value increase the training time (if | "compute_oob_variable_importances:true") as well as the stability of the | oob variable importance metrics. Default: 1. | 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. | random_seed: Random seed for the training of the model. Learners are | expected to be deterministic by the random seed. Default: 123456. | sampling_with_replacement: If true, the training examples are sampled with | replacement. If false, the training samples are sampled without | replacement. Only used when "bootstrap_training_dataset=true". If false | (sampling without replacement) and if "bootstrap_size_ratio=1" (default), | all the examples are used to train all the trees (you probably do not | want that). Default: True. | 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. | sparse_oblique_weights: For sparse oblique splits i.e. | `split_axis=SPARSE_OBLIQUE`. Possible values: | - `BINARY`: The oblique weights are sampled in {-1,1} (default). | - `CONTINUOUS`: The oblique weights are be sampled in [-1,1]. 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". | uplift_min_examples_in_treatment: For uplift models only. Minimum number of | examples per treatment in a node. Default: 5. | uplift_split_score: For uplift models only. Splitter score i.e. score | optimized by the splitters. The scores are introduced in "Decision trees | for uplift modeling with single and multiple treatments", Rzepakowski et | al. Notation: `p` probability / average value of the positive outcome, | `q` probability / average value in the control group. | - `KULLBACK_LEIBLER` or `KL`: - p log (p/q) | - `EUCLIDEAN_DISTANCE` or `ED`: (p-q)^2 | - `CHI_SQUARED` or `CS`: (p-q)^2/q | Default: "KULLBACK_LEIBLER". | 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 | keras.engine.training.Model | keras.engine.base_layer.Layer | tensorflow.python.module.module.Module | tensorflow.python.training.tracking.autotrackable.AutoTrackable | tensorflow.python.training.tracking.base.Trackable | keras.utils.version_utils.LayerVersionSelector | 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: | | capabilities() -> yggdrasil_decision_forests.learner.abstract_learner_pb2.LearnerCapabilities | Lists the capabilities of the learning algorithm. | | 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. | | call_get_leaves(self, inputs) | Computes the index of the active leaf in each tree. | | The active leaf is the leave that that receive the example during inference. | | The returned value "leaves[i,j]" is the index of the active leave for the | i-th example and the j-th tree. Leaves are indexed by depth first | exploration with the negative child visited before the positive one | (similarly as "iterate_on_nodes()" iteration). Leaf indices are also | available with LeafNode.leaf_idx. | | Args: | inputs: Input tensors. Same signature as the model's "call(inputs)". | | Returns: | Index of the active leaf for each tree in the model. | | collect_data_step(self, data, is_training_example) | Collect examples e.g. training or validation. | | compile(self, metrics=None, weighted_metrics=None) | Configure the model for training. | | Unlike for most Keras model, calling "compile" is optional before calling | "fit". | | Args: | metrics: List of metrics to be evaluated by the model during training and | testing. | weighted_metrics: List of metrics to be evaluated and weighted by | `sample_weight` or `class_weight` during training and testing. | | 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, verbose: Union[int, NoneType] = None, **kwargs) -> 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. | | Unlike classical neural networks, the learning algorithm requires to scan | the training dataset exactly once. Therefore, the dataset should not be | repeated. The algorithm also does not benefit from shuffling the dataset. | | Input features generally do not need to be normalized (numerical) or indexed | (categorical features stored as string). Also, missing values are well | supported (i.e. not need to replace missing values). | | Pandas Dataframe can be prepared with "dataframe_to_tf_dataset": | dataset = pandas.Dataframe(...) | model.fit(pd_dataframe_to_tf_dataset(dataset, label="my_label")) | | Some of the learning algorithm will support distributed training with the | ParameterServerStrategy e.g.: | | with tf.distribute.experimental.ParameterServerStrategy(...).scope(): | model = DistributedGradientBoostedTreesModel() | model.fit(...) | | 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. | verbose: Verbosity mode. 0 = silent, 1 = small details, 2 = full details. | **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()`. | | fit_on_dataset_path(self, train_path: str, label_key: str, weight_key: Union[str, NoneType] = None, ranking_key: Union[str, NoneType] = None, valid_path: Union[str, NoneType] = None, dataset_format: Union[str, NoneType] = 'csv', max_num_scanned_rows_to_accumulate_statistics: Union[int, NoneType] = 100000, try_resume_training: Union[bool, NoneType] = True, input_model_signature_fn: Union[Callable[[tensorflow_decision_forests.component.inspector.inspector.AbstractInspector], Any], NoneType] = <function build_default_input_model_signature at 0x7f6580ce79e0>) | Trains the model on a dataset stored on disk. | | This solution is generally more efficient and easier that loading the | dataset with a tf.Dataset both for local and distributed training. | | Usage example: | | # Local training | model = model = keras.GradientBoostedTreesModel() | model.fit_on_dataset_path( | train_path="/path/to/dataset.csv", | label_key="label", | dataset_format="csv") | model.save("/model/path") | | # Distributed training | with tf.distribute.experimental.ParameterServerStrategy(...).scope(): | model = model = keras.DistributedGradientBoostedTreesModel() | model.fit_on_dataset_path( | train_path="/path/to/dataset@10", | label_key="label", | dataset_format="tfrecord+tfe") | model.save("/model/path") | | Args: | train_path: Path to the training dataset. Support comma separated files, | shard and glob notation. | label_key: Name of the label column. | weight_key: Name of the weighing column. | ranking_key: Name of the ranking column. | valid_path: Path to the validation dataset. If not provided, or if the | learning algorithm does not support/need a validation dataset, | `valid_path` is ignored. | dataset_format: Format of the dataset. Should be one of the registered | dataset format (see | https://github.com/google/yggdrasil-decision-forests/blob/main/documentation/user_manual#dataset-path-and-format | for more details). The format "csv" always available but it is | generally only suited for small datasets. | max_num_scanned_rows_to_accumulate_statistics: Maximum number of examples | to scan to determine the statistics of the features (i.e. the dataspec, | e.g. mean value, dictionaries). (Currently) the "first" examples of the | dataset are scanned (e.g. the first examples of the dataset is a single | file). Therefore, it is important that the sampled dataset is relatively | uniformly sampled, notably the scanned examples should contains all the | possible categorical values (otherwise the not seen value will be | treated as out-of-vocabulary). If set to None, the entire dataset is | scanned. This parameter has no effect if the dataset is stored in a | format that already contains those values. | try_resume_training: If true, tries to resume training from the model | checkpoint stored in the `temp_directory` directory. If `temp_directory` | does not contain any model checkpoint, start the training from the | start. Works in the following three situations: (1) The training was | interrupted by the user (e.g. ctrl+c). (2) the training job was | interrupted (e.g. rescheduling), ond (3) the hyper-parameter of the | model were changed such that an initially completed training is now | incomplete (e.g. increasing the number of trees). | input_model_signature_fn: A lambda that returns the | (Dense,Sparse,Ragged)TensorSpec (or structure of TensorSpec e.g. | dictionary, list) corresponding to input signature of the model. If not | specified, the input model signature is created by | "build_default_input_model_signature". For example, specify | "input_model_signature_fn" if an numerical input feature (which is | consumed as DenseTensorSpec(float32) by default) will be feed | differently (e.g. RaggedTensor(int64)). | | 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. | | predict_get_leaves(self, x) | Gets the index of the active leaf of each tree. | | The active leaf is the leave that that receive the example during inference. | | The returned value "leaves[i,j]" is the index of the active leave for the | i-th example and the j-th tree. Leaves are indexed by depth first | exploration with the negative child visited before the positive one | (similarly as "iterate_on_nodes()" iteration). Leaf indices are also | available with LeafNode.leaf_idx. | | Args: | x: Input samples as a tf.data.Dataset. | | Returns: | Index of the active leaf for each tree in the model. | | save(self, filepath: str, overwrite: Union[bool, NoneType] = True, **kwargs) | Saves the model as a TensorFlow SavedModel. | | The exported SavedModel contains a standalone Yggdrasil Decision Forests | model in the "assets" sub-directory. The Yggdrasil model can be used | directly using the Yggdrasil API. However, this model does not contain the | "preprocessing" layer (if any). | | Args: | filepath: Path to the output model. | overwrite: If true, override an already existing model. If false, raise an | error if a model already exist. | **kwargs: Arguments passed to the core keras model's save. | | summary(self, line_length=None, positions=None, print_fn=None) | Shows information about the model. | | train_step(self, data) | Collects training examples. | | valid_step(self, data) | Collects validation 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. | | ---------------------------------------------------------------------- | Data descriptors inherited from tensorflow_decision_forests.keras.core.CoreModel: | | learner_params | Gets the dictionary of hyper-parameters passed in the model constructor. | | Changing this dictionary will impact the training. | | ---------------------------------------------------------------------- | Methods inherited from keras.engine.training.Model: | | __copy__(self) | | __deepcopy__(self, memo) | | __reduce__(self) | Helper for pickle. | | __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` instance, or list/dict of shapes, | where shapes are tuples, integers, or `TensorShape` instances. | | 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 keyword arg 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. | | compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None) | Compute the total loss, validate it, and return it. | | Subclasses can optionally override this method to provide custom loss | computation logic. | | Example: | ```python | class MyModel(tf.keras.Model): | | def __init__(self, *args, **kwargs): | super(MyModel, self).__init__(*args, **kwargs) | self.loss_tracker = tf.keras.metrics.Mean(name='loss') | | def compute_loss(self, x, y, y_pred, sample_weight): | loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y)) | loss += tf.add_n(self.losses) | self.loss_tracker.update_state(loss) | return loss | | def reset_metrics(self): | self.loss_tracker.reset_states() | | @property | def metrics(self): | return [self.loss_tracker] | | tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,)) | dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1) | | inputs = tf.keras.layers.Input(shape=(10,), name='my_input') | outputs = tf.keras.layers.Dense(10)(inputs) | model = MyModel(inputs, outputs) | model.add_loss(tf.reduce_sum(outputs)) | | optimizer = tf.keras.optimizers.SGD() | model.compile(optimizer, loss='mse', steps_per_execution=10) | model.fit(dataset, epochs=2, steps_per_epoch=10) | print('My custom loss: ', model.loss_tracker.result().numpy()) | ``` | | Args: | x: Input data. | y: Target data. | y_pred: Predictions returned by the model (output of `model(x)`) | sample_weight: Sample weights for weighting the loss function. | | Returns: | The total loss as a `tf.Tensor`, or `None` if no loss results (which is | the case when called by `Model.test_step`). | | compute_metrics(self, x, y, y_pred, sample_weight) | Update metric states and collect all metrics to be returned. | | Subclasses can optionally override this method to provide custom metric | updating and collection logic. | | Example: | ```python | class MyModel(tf.keras.Sequential): | | def compute_metrics(self, x, y, y_pred, sample_weight): | | # This super call updates `self.compiled_metrics` and returns results | # for all metrics listed in `self.metrics`. | metric_results = super(MyModel, self).compute_metrics( | x, y, y_pred, sample_weight) | | # Note that `self.custom_metric` is not listed in `self.metrics`. | self.custom_metric.update_state(x, y, y_pred, sample_weight) | metric_results['custom_metric_name'] = self.custom_metric.result() | return metric_results | ``` | | Args: | x: Input data. | y: Target data. | y_pred: Predictions returned by the model (output of `model.call(x)`) | sample_weight: Sample weights for weighting the loss function. | | Returns: | A `dict` containing values that will be passed to | `tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the | values of the metrics listed in `self.metrics` are returned. Example: | `{'loss': 0.2, 'accuracy': 0.7}`. | | 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. | | 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, force=False) | 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. You can skip the cache and generate again the | function with `force=True`. | | Args: | force: Whether to regenerate the train function and skip the cached | function if available. | | 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 batch processing | of large numbers of inputs. It is not intended for use inside of loops | that iterate over your data and process small numbers of inputs at a time. | | For small numbers of inputs that fit in one batch, | directly use `__call__()` for faster execution, e.g., | `model(x)`, or `model(x, training=False)` if you have layers such as | `tf.keras.layers.BatchNormalization` that behave differently during | inference. You may pair the individual model call with a `tf.function` | for additional performance inside your inner loop. | If you need access to numpy array values instead of tensors after your | model call, you can use `tensor.numpy()` to get the numpy array value of | an eager tensor. | | Also, note the fact that test loss is not affected by | regularization layers like noise and dropout. | | Note: See [this FAQ entry]( | https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call) | for more details about the difference between `Model` methods `predict()` | and `__call__()`. | | 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. | | Returns: | Numpy array(s) of predictions. | | Raises: | RuntimeError: If `model.predict` is wrapped in a `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 a `tf.function`. | | 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_spec(self, dynamic_batch=True) | Returns the `tf.TensorSpec` of call inputs as a tuple `(args, kwargs)`. | | This value is automatically defined after calling the model for the first | time. Afterwards, you can use it when exporting the model for serving: | | ```python | model = tf.keras.Model(...) | | @tf.function | def serve(*args, **kwargs): | outputs = model(*args, **kwargs) | # Apply postprocessing steps, or add additional outputs. | ... | return outputs | | # arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this example, is | # an empty dict since functional models do not use keyword arguments. | arg_specs, kwarg_specs = model.save_spec() | | model.save(path, signatures={ | 'serving_default': serve.get_concrete_function(*arg_specs, **kwarg_specs) | }) | ``` | | Args: | dynamic_batch: Whether to set the batch sizes of all the returned | `tf.TensorSpec` to `None`. (Note that when defining functional or | Sequential models with `tf.keras.Input([...], batch_size=X)`, the | batch size will always be preserved). Defaults to `True`. | Returns: | If the model inputs are defined, returns a tuple `(args, kwargs)`. All | elements in `args` and `kwargs` are `tf.TensorSpec`. | If the model inputs are not defined, returns `None`. | The model inputs are automatically set when calling the model, | `model.fit`, `model.evaluate` or `model.predict`. | | 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. | | 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 a `tf.function`. | | 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. | | Note: Since TF 2.6, this method is no longer supported and will raise a | RuntimeError. | | 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: | RuntimeError: announces that the method poses a security risk | | 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 a `tf.function`. | | ---------------------------------------------------------------------- | Class methods inherited from 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 keras.engine.training.Model: | | __new__(cls, *args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors inherited from 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 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=<VariableAggregationV2.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. | | This method will cause the layer's state to be built, if that has not | happened before. This requires 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). | | finalize_state(self) | Finalizes the layers state after updating layer weights. | | This function can be subclassed in a layer and will be called after updating | a layer weights. It can be overridden to finalize any additional layer state | after a weight update. | | This function will be called after weights of a layer have been restored | from a loaded model. | | 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 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))
```

Use /tmp/tmppf8e7g5_ as temporary training directory Starting reading the dataset 1/1 [==============================] - ETA: 0s Dataset read in 0:00:00.218573 Training model Model trained in 0:00:00.242015 Compiling model 1/1 [==============================] - 1s 608ms/step - val_loss: 0.0000e+00 - val_accuracy: 0.9722 [INFO kernel.cc:1153] Loading model from path [INFO kernel.cc:1001] Use fast generic engine 1/1 [==============================] - 0s 79ms/step - loss: 0.0000e+00 - accuracy: 0.9722 {'loss': 0.0, 'accuracy': 0.9722222089767456}

**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"])
model_3.fit(x=train_ds, validation_data=test_ds)
```

<IPython.core.display.Javascript object> Use /tmp/tmpihvn_e8p as temporary training directory Starting reading the dataset 1/1 [==============================] - ETA: 0s Dataset read in 0:00:00.154245 Training model Model trained in 0:00:00.135197 Compiling model 1/1 [==============================] - 0s 437ms/step - val_loss: 0.0000e+00 - val_accuracy: 0.8148 [INFO kernel.cc:1153] Loading model from path [INFO kernel.cc:1001] Use fast generic engine <keras.callbacks.History at 0x7f64d02b6810>

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)
```

Use /tmp/tmpj23_ibou as temporary training directory Starting reading the dataset 1/1 [==============================] - ETA: 0s Dataset read in 0:00:00.097619 Training model Model trained in 0:00:00.228236 Compiling model 1/1 [==============================] - 0s 337ms/step [INFO kernel.cc:1153] Loading model from path [INFO kernel.cc:1001] Use fast generic engine <keras.callbacks.History at 0x7f64d0034490>

```
# 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)
```

Use /tmp/tmpyh5caajh as temporary training directory Starting reading the dataset WARNING:tensorflow:5 out of the last 5 calls to <function Model.make_train_function.<locals>.train_function at 0x7f60f0e37cb0> 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 Model.make_train_function.<locals>.train_function at 0x7f60f0e37cb0> 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. 1/1 [==============================] - ETA: 0s Dataset read in 0:00:00.103518 Training model Model trained in 0:00:00.186311 Compiling model 1/1 [==============================] - 0s 302ms/step [INFO kernel.cc:1153] Loading model from path [INFO kernel.cc:1001] Use fast generic engine WARNING:tensorflow:5 out of the last 5 calls to <function CoreModel.make_predict_function.<locals>.predict_function_trained at 0x7f60f0df7200> 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 0x7f60f0df7200> 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. <keras.callbacks.History at 0x7f60f0e4cad0>

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)
```

Resolve hyper-parameter template "benchmark_rank1" to "benchmark_rank1@v1" -> {'growing_strategy': 'BEST_FIRST_GLOBAL', 'categorical_algorithm': 'RANDOM', 'split_axis': 'SPARSE_OBLIQUE', 'sparse_oblique_normalization': 'MIN_MAX', 'sparse_oblique_num_projections_exponent': 1.0}. Use /tmp/tmppji8zs02 as temporary training directory Starting reading the dataset WARNING:tensorflow:6 out of the last 6 calls to <function Model.make_train_function.<locals>.train_function at 0x7f60f0dcfcb0> 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 Model.make_train_function.<locals>.train_function at 0x7f60f0dcfcb0> 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. 1/1 [==============================] - ETA: 0s Dataset read in 0:00:00.099185 Training model Model trained in 0:00:00.064944 Compiling model [INFO kernel.cc:1153] Loading model from path 1/1 [==============================] - 0s 176ms/step WARNING:tensorflow:6 out of the last 6 calls to <function CoreModel.make_predict_function.<locals>.predict_function_trained at 0x7f60f0de7a70> 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. [INFO kernel.cc:1001] Use fast generic engine WARNING:tensorflow:6 out of the last 6 calls to <function CoreModel.make_predict_function.<locals>.predict_function_trained at 0x7f60f0de7a70> 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. <keras.callbacks.History at 0x7f60f0de12d0>

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> /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/keras/engine/functional.py:559: 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. inputs = self._flatten_to_reference_inputs(inputs) Use /tmp/tmpgm_bt05j as temporary training directory Starting reading the dataset 1/1 [==============================] - ETA: 0s Dataset read in 0:00:00.167678 Training model Model trained in 0:00:00.021172 Compiling model 1/1 [==============================] - 0s 209ms/step [INFO kernel.cc:1153] Loading model from path [INFO kernel.cc:1001] Use fast generic engine Model: "random_forest_model_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= model (Functional) {'body_mass_kg': (None, 0 1), 'bill_length_mm': (None , 1)} ================================================================= 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: MEAN_MIN_DEPTH: 1. "__LABEL" 4.001979 ################ 2. "body_mass_kg" 1.228907 #### 3. "bill_length_mm" 0.011190 Variable Importance: NUM_AS_ROOT: 1. "bill_length_mm" 297.000000 ################ 2. "body_mass_kg" 3.000000 Variable Importance: NUM_NODES: 1. "bill_length_mm" 1658.000000 ################ 2. "body_mass_kg" 1425.000000 Variable Importance: SUM_SCORE: 1. "bill_length_mm" 43748.331708 ################ 2. "body_mass_kg" 23863.336913 Winner take all: true Out-of-bag evaluation: accuracy:0.911017 logloss:0.676724 Number of trees: 300 Total number of nodes: 6466 Number of nodes by tree: Count: 300 Average: 21.5533 StdDev: 3.11991 Min: 13 Max: 33 Ignored: 0 ---------------------------------------------- [ 13, 14) 1 0.33% 0.33% [ 14, 15) 0 0.00% 0.33% [ 15, 16) 11 3.67% 4.00% # [ 16, 17) 0 0.00% 4.00% [ 17, 18) 30 10.00% 14.00% #### [ 18, 19) 0 0.00% 14.00% [ 19, 20) 46 15.33% 29.33% ###### [ 20, 21) 0 0.00% 29.33% [ 21, 22) 73 24.33% 53.67% ######### [ 22, 23) 0 0.00% 53.67% [ 23, 24) 79 26.33% 80.00% ########## [ 24, 25) 0 0.00% 80.00% [ 25, 26) 39 13.00% 93.00% ##### [ 26, 27) 0 0.00% 93.00% [ 27, 28) 17 5.67% 98.67% ## [ 28, 29) 0 0.00% 98.67% [ 29, 30) 3 1.00% 99.67% [ 30, 31) 0 0.00% 99.67% [ 31, 32) 0 0.00% 99.67% [ 32, 33] 1 0.33% 100.00% Depth by leafs: Count: 3383 Average: 4.03606 StdDev: 1.37882 Min: 1 Max: 9 Ignored: 0 ---------------------------------------------- [ 1, 2) 9 0.27% 0.27% [ 2, 3) 363 10.73% 11.00% #### [ 3, 4) 955 28.23% 39.23% ########## [ 4, 5) 998 29.50% 68.73% ########## [ 5, 6) 516 15.25% 83.98% ##### [ 6, 7) 359 10.61% 94.59% #### [ 7, 8) 146 4.32% 98.91% # [ 8, 9) 27 0.80% 99.70% [ 9, 9] 10 0.30% 100.00% Number of training obs by leaf: Count: 3383 Average: 20.9282 StdDev: 25.5954 Min: 5 Max: 114 Ignored: 0 ---------------------------------------------- [ 5, 10) 2191 64.77% 64.77% ########## [ 10, 16) 257 7.60% 72.36% # [ 16, 21) 29 0.86% 73.22% [ 21, 27) 18 0.53% 73.75% [ 27, 32) 43 1.27% 75.02% [ 32, 38) 113 3.34% 78.36% # [ 38, 43) 87 2.57% 80.93% [ 43, 49) 114 3.37% 84.30% # [ 49, 54) 62 1.83% 86.14% [ 54, 60) 63 1.86% 88.00% [ 60, 65) 63 1.86% 89.86% [ 65, 71) 42 1.24% 91.10% [ 71, 76) 40 1.18% 92.28% [ 76, 82) 70 2.07% 94.35% [ 82, 87) 69 2.04% 96.39% [ 87, 93) 61 1.80% 98.20% [ 93, 98) 29 0.86% 99.05% [ 98, 104) 22 0.65% 99.70% [ 104, 109) 8 0.24% 99.94% [ 109, 114] 2 0.06% 100.00% Attribute in nodes: 1658 : bill_length_mm [NUMERICAL] 1425 : 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: 473 : bill_length_mm [NUMERICAL] 418 : body_mass_kg [NUMERICAL] Attribute in nodes with depth <= 2: 916 : bill_length_mm [NUMERICAL] 794 : body_mass_kg [NUMERICAL] Attribute in nodes with depth <= 3: 1250 : bill_length_mm [NUMERICAL] 1143 : body_mass_kg [NUMERICAL] Attribute in nodes with depth <= 5: 1599 : bill_length_mm [NUMERICAL] 1382 : body_mass_kg [NUMERICAL] Condition type in nodes: 3083 : HigherCondition Condition type in nodes with depth <= 0: 300 : HigherCondition Condition type in nodes with depth <= 1: 891 : HigherCondition Condition type in nodes with depth <= 2: 1710 : HigherCondition Condition type in nodes with depth <= 3: 2393 : HigherCondition Condition type in nodes with depth <= 5: 2981 : HigherCondition Node format: NOT_SET Training OOB: trees: 1, Out-of-bag evaluation: accuracy:0.866667 logloss:4.80582 trees: 11, Out-of-bag evaluation: accuracy:0.910638 logloss:1.93149 trees: 21, Out-of-bag evaluation: accuracy:0.902542 logloss:1.64002 trees: 31, Out-of-bag evaluation: accuracy:0.915254 logloss:1.36133 trees: 43, Out-of-bag evaluation: accuracy:0.915254 logloss:1.36785 trees: 53, Out-of-bag evaluation: accuracy:0.919492 logloss:1.36436 trees: 63, Out-of-bag evaluation: accuracy:0.919492 logloss:1.3579 trees: 73, Out-of-bag evaluation: accuracy:0.919492 logloss:1.35894 trees: 83, Out-of-bag evaluation: accuracy:0.919492 logloss:1.2213 trees: 93, Out-of-bag evaluation: accuracy:0.915254 logloss:1.08423 trees: 104, Out-of-bag evaluation: accuracy:0.915254 logloss:1.08206 trees: 114, Out-of-bag evaluation: accuracy:0.911017 logloss:0.946757 trees: 124, Out-of-bag evaluation: accuracy:0.911017 logloss:0.948618 trees: 134, Out-of-bag evaluation: accuracy:0.90678 logloss:0.946607 trees: 144, Out-of-bag evaluation: accuracy:0.90678 logloss:0.947383 trees: 155, Out-of-bag evaluation: accuracy:0.90678 logloss:0.949077 trees: 165, Out-of-bag evaluation: accuracy:0.911017 logloss:0.813627 trees: 175, Out-of-bag evaluation: accuracy:0.90678 logloss:0.677211 trees: 185, Out-of-bag evaluation: accuracy:0.90678 logloss:0.679264 trees: 195, Out-of-bag evaluation: accuracy:0.90678 logloss:0.680527 trees: 206, Out-of-bag evaluation: accuracy:0.90678 logloss:0.683075 trees: 216, Out-of-bag evaluation: accuracy:0.90678 logloss:0.684769 trees: 226, Out-of-bag evaluation: accuracy:0.90678 logloss:0.686165 trees: 236, Out-of-bag evaluation: accuracy:0.911017 logloss:0.686101 trees: 246, Out-of-bag evaluation: accuracy:0.915254 logloss:0.683619 trees: 256, Out-of-bag evaluation: accuracy:0.911017 logloss:0.680965 trees: 266, Out-of-bag evaluation: accuracy:0.90678 logloss:0.680605 trees: 276, Out-of-bag evaluation: accuracy:0.911017 logloss:0.681375 trees: 286, Out-of-bag evaluation: accuracy:0.911017 logloss:0.677813 trees: 296, Out-of-bag evaluation: accuracy:0.911017 logloss:0.676555 trees: 300, Out-of-bag evaluation: accuracy:0.911017 logloss:0.676724

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.fit(x=train_ds)
```

Use /tmp/tmp7zcurxdh as temporary training directory Starting reading the dataset 1/1 [==============================] - ETA: 0s Dataset read in 0:00:00.094296 Training model Model trained in 0:00:00.021447 Compiling model 1/1 [==============================] - 0s 135ms/step [INFO kernel.cc:1153] Loading model from path [INFO kernel.cc:1001] Use fast generic engine <keras.callbacks.History at 0x7f60f25b2790>

## 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)
```

2901 examples in training, 1276 examples for testing. /tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow_decision_forests/keras/core.py:2036: FutureWarning: In a future version of pandas all arguments of DataFrame.drop except for the argument 'labels' will be keyword-only features_dataframe = dataframe.drop(label, 1)

```
%set_cell_height 300
# Configure the model.
model_7 = tfdf.keras.RandomForestModel(task = tfdf.keras.Task.REGRESSION)
# Train the model.
model_7.fit(x=train_ds)
```

<IPython.core.display.Javascript object> Use /tmp/tmpmj202ct3 as temporary training directory Starting reading the dataset 1/3 [=========>....................] - ETA: 0s Dataset read in 0:00:00.121706 Training model Model trained in 0:00:00.792651 Compiling model [INFO kernel.cc:1153] Loading model from path 3/3 [==============================] - 2s 755ms/step [INFO kernel.cc:1001] Use fast generic engine <keras.callbacks.History at 0x7f65ecc18c90>

```
# Evaluate the model on the test dataset.
model_7.compile(metrics=["mse"])
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 5 calls to <function CoreModel.make_test_function.<locals>.test_function at 0x7f60f240a560> 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_test_function.<locals>.test_function at 0x7f60f240a560> 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. 3/3 [==============================] - 0s 34ms/step - loss: 0.0000e+00 - mse: 1.9625 {'loss': 0.0, 'mse': 1.9624943733215332} MSE: 1.9624943733215332 RMSE: 1.4008905643630887

## 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 [==============================] - 6s 0us/step 61833216/61824018 [==============================] - 6s 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)
```

11318 examples in training, 4822 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)
```

/tmpfs/src/tf_docs_env/lib/python3.7/site-packages/tensorflow_decision_forests/keras/core.py:2036: FutureWarning: In a future version of pandas all arguments of DataFrame.drop except for the argument 'labels' will be keyword-only features_dataframe = dataframe.drop(label, 1)

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

<IPython.core.display.Javascript object> Use /tmp/tmplxrwn2da as temporary training directory Starting reading the dataset 9/12 [=====================>........] - ETA: 0s Dataset read in 0:00:00.567589 Training model Model trained in 0:00:01.289335 Compiling model 12/12 [==============================] - 2s 131ms/step [INFO kernel.cc:1153] Loading model from path [INFO abstract_model.cc:1063] Engine "GradientBoostedTreesQuickScorerExtended" built [INFO kernel.cc:1001] Use fast generic engine <keras.callbacks.History at 0x7f60f2392510>

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: MEAN_MIN_DEPTH: 1. "__RANK_GROUP" 4.562782 ################ 2. "__LABEL" 4.562782 ################ 3. "f_1" 4.519585 ############### 4. "f_11" 4.518717 ############### 5. "f_2" 4.513908 ############### 6. "f_13" 4.513215 ############### 7. "f_14" 4.487473 ############### 8. "f_20" 4.469217 ############### 9. "f_19" 4.436435 ############### 10. "f_17" 4.434869 ############### 11. "f_16" 4.433665 ############### 12. "f_7" 4.397136 ############### 13. "f_12" 4.394809 ############### 14. "f_18" 4.392938 ############### 15. "f_15" 4.316405 ############## 16. "f_5" 4.297642 ############## 17. "f_10" 4.273483 ############## 18. "f_3" 4.263667 ############## 19. "f_6" 4.228209 ############## 20. "f_24" 4.160024 ############# 21. "f_22" 4.080274 ############# 22. "f_23" 4.079044 ############# 23. "f_21" 3.811776 ########### 24. "f_25" 3.787336 ########### 25. "f_9" 3.118690 ####### 26. "f_4" 3.044802 ####### 27. "f_8" 1.743550 Variable Importance: NUM_AS_ROOT: 1. "f_8" 25.000000 ################ 2. "f_4" 12.000000 ####### 3. "f_21" 5.000000 ## 4. "f_25" 3.000000 # 5. "f_3" 2.000000 6. "f_10" 1.000000 Variable Importance: NUM_NODES: 1. "f_8" 131.000000 ################ 2. "f_9" 84.000000 ######### 3. "f_4" 66.000000 ####### 4. "f_25" 59.000000 ###### 5. "f_24" 58.000000 ###### 6. "f_23" 52.000000 ##### 7. "f_10" 45.000000 #### 8. "f_21" 43.000000 #### 9. "f_22" 40.000000 #### 10. "f_18" 32.000000 ### 11. "f_6" 32.000000 ### 12. "f_19" 31.000000 ### 13. "f_12" 29.000000 ## 14. "f_20" 29.000000 ## 15. "f_15" 25.000000 ## 16. "f_17" 25.000000 ## 17. "f_5" 23.000000 ## 18. "f_3" 21.000000 # 19. "f_16" 17.000000 # 20. "f_7" 17.000000 # 21. "f_13" 13.000000 22. "f_14" 13.000000 23. "f_2" 10.000000 24. "f_11" 8.000000 25. "f_1" 6.000000 Variable Importance: SUM_SCORE: 1. "f_21" 3980.314344 ################ 2. "f_8" 3820.156056 ############### 3. "f_9" 3643.278123 ############## 4. "f_4" 3615.293880 ############## 5. "f_25" 2371.187642 ######### 6. "f_24" 2122.469166 ######## 7. "f_23" 1571.207252 ###### 8. "f_22" 1224.159489 #### 9. "f_3" 1056.801882 #### 10. "f_19" 888.917751 ### 11. "f_11" 873.622994 ### 12. "f_10" 753.403099 ## 13. "f_2" 674.616875 ## 14. "f_15" 537.348568 # 15. "f_12" 463.326223 # 16. "f_16" 453.069513 # 17. "f_6" 445.504624 # 18. "f_5" 427.831051 # 19. "f_18" 347.612284 # 20. "f_7" 309.098810 21. "f_20" 269.774860 22. "f_14" 246.340647 23. "f_13" 218.874545 24. "f_17" 204.018296 25. "f_1" 67.952118 Loss: LAMBDA_MART_NDCG5 Validation loss value: -0.497484 Number of trees per iteration: 1 Node format: NOT_SET Number of trees: 48 Total number of nodes: 1866 Number of nodes by tree: Count: 48 Average: 38.875 StdDev: 7.80391 Min: 21 Max: 51 Ignored: 0 ---------------------------------------------- [ 21, 22) 1 2.08% 2.08% # [ 22, 24) 4 8.33% 10.42% ##### [ 24, 25) 0 0.00% 10.42% [ 25, 27) 0 0.00% 10.42% [ 27, 28) 0 0.00% 10.42% [ 28, 30) 2 4.17% 14.58% ### [ 30, 31) 0 0.00% 14.58% [ 31, 33) 2 4.17% 18.75% ### [ 33, 34) 2 4.17% 22.92% ### [ 34, 36) 5 10.42% 33.33% ###### [ 36, 38) 3 6.25% 39.58% #### [ 38, 39) 0 0.00% 39.58% [ 39, 41) 3 6.25% 45.83% #### [ 41, 42) 5 10.42% 56.25% ###### [ 42, 44) 6 12.50% 68.75% ######## [ 44, 45) 0 0.00% 68.75% [ 45, 47) 8 16.67% 85.42% ########## [ 47, 48) 3 6.25% 91.67% #### [ 48, 50) 2 4.17% 95.83% ### [ 50, 51] 2 4.17% 100.00% ### Depth by leafs: Count: 957 Average: 4.59457 StdDev: 0.751656 Min: 1 Max: 5 Ignored: 0 ---------------------------------------------- [ 1, 2) 3 0.31% 0.31% [ 2, 3) 21 2.19% 2.51% [ 3, 4) 74 7.73% 10.24% # [ 4, 5) 165 17.24% 27.48% ## [ 5, 5] 694 72.52% 100.00% ########## Number of training obs by leaf: Count: 957 Average: 515.361 StdDev: 1751.81 Min: 5 Max: 10042 Ignored: 0 ---------------------------------------------- [ 5, 506) 849 88.71% 88.71% ########## [ 506, 1008) 23 2.40% 91.12% [ 1008, 1510) 7 0.73% 91.85% [ 1510, 2012) 7 0.73% 92.58% [ 2012, 2514) 9 0.94% 93.52% [ 2514, 3016) 9 0.94% 94.46% [ 3016, 3518) 1 0.10% 94.57% [ 3518, 4020) 9 0.94% 95.51% [ 4020, 4522) 3 0.31% 95.82% [ 4522, 5024) 1 0.10% 95.92% [ 5024, 5525) 1 0.10% 96.03% [ 5525, 6027) 2 0.21% 96.24% [ 6027, 6529) 3 0.31% 96.55% [ 6529, 7031) 3 0.31% 96.87% [ 7031, 7533) 5 0.52% 97.39% [ 7533, 8035) 1 0.10% 97.49% [ 8035, 8537) 1 0.10% 97.60% [ 8537, 9039) 4 0.42% 98.01% [ 9039, 9541) 9 0.94% 98.96% [ 9541, 10042] 10 1.04% 100.00% Attribute in nodes: 131 : f_8 [NUMERICAL] 84 : f_9 [NUMERICAL] 66 : f_4 [NUMERICAL] 59 : f_25 [NUMERICAL] 58 : f_24 [NUMERICAL] 52 : f_23 [NUMERICAL] 45 : f_10 [NUMERICAL] 43 : f_21 [NUMERICAL] 40 : f_22 [NUMERICAL] 32 : f_6 [NUMERICAL] 32 : f_18 [NUMERICAL] 31 : f_19 [NUMERICAL] 29 : f_20 [NUMERICAL] 29 : f_12 [NUMERICAL] 25 : f_17 [NUMERICAL] 25 : f_15 [NUMERICAL] 23 : f_5 [NUMERICAL] 21 : f_3 [NUMERICAL] 17 : f_7 [NUMERICAL] 17 : f_16 [NUMERICAL] 13 : f_14 [NUMERICAL] 13 : f_13 [NUMERICAL] 10 : f_2 [NUMERICAL] 8 : f_11 [NUMERICAL] 6 : f_1 [NUMERICAL] Attribute in nodes with depth <= 0: 25 : f_8 [NUMERICAL] 12 : f_4 [NUMERICAL] 5 : f_21 [NUMERICAL] 3 : f_25 [NUMERICAL] 2 : f_3 [NUMERICAL] 1 : f_10 [NUMERICAL] Attribute in nodes with depth <= 1: 46 : f_8 [NUMERICAL] 28 : f_9 [NUMERICAL] 24 : f_4 [NUMERICAL] 7 : f_25 [NUMERICAL] 7 : f_21 [NUMERICAL] 6 : f_22 [NUMERICAL] 4 : f_5 [NUMERICAL] 4 : f_11 [NUMERICAL] 3 : f_6 [NUMERICAL] 3 : f_23 [NUMERICAL] 2 : f_3 [NUMERICAL] 2 : f_10 [NUMERICAL] 1 : f_7 [NUMERICAL] 1 : f_18 [NUMERICAL] 1 : f_16 [NUMERICAL] 1 : f_15 [NUMERICAL] 1 : f_1 [NUMERICAL] Attribute in nodes with depth <= 2: 74 : f_8 [NUMERICAL] 37 : f_9 [NUMERICAL] 34 : f_4 [NUMERICAL] 19 : f_25 [NUMERICAL] 17 : f_21 [NUMERICAL] 13 : f_22 [NUMERICAL] 12 : f_6 [NUMERICAL] 12 : f_24 [NUMERICAL] 12 : f_23 [NUMERICAL] 12 : f_15 [NUMERICAL] 8 : f_10 [NUMERICAL] 7 : f_7 [NUMERICAL] 6 : f_5 [NUMERICAL] 6 : f_12 [NUMERICAL] 5 : f_20 [NUMERICAL] 5 : f_19 [NUMERICAL] 5 : f_16 [NUMERICAL] 4 : f_3 [NUMERICAL] 4 : f_18 [NUMERICAL] 4 : f_17 [NUMERICAL] 4 : f_11 [NUMERICAL] 3 : f_14 [NUMERICAL] 1 : f_2 [NUMERICAL] 1 : f_13 [NUMERICAL] 1 : f_1 [NUMERICAL] Attribute in nodes with depth <= 3: 96 : f_8 [NUMERICAL] 61 : f_9 [NUMERICAL] 51 : f_4 [NUMERICAL] 40 : f_24 [NUMERICAL] 37 : f_25 [NUMERICAL] 28 : f_23 [NUMERICAL] 25 : f_22 [NUMERICAL] 23 : f_10 [NUMERICAL] 21 : f_21 [NUMERICAL] 19 : f_12 [NUMERICAL] 18 : f_6 [NUMERICAL] 18 : f_15 [NUMERICAL] 17 : f_5 [NUMERICAL] 16 : f_19 [NUMERICAL] 16 : f_18 [NUMERICAL] 14 : f_17 [NUMERICAL] 12 : f_20 [NUMERICAL] 10 : f_7 [NUMERICAL] 10 : f_16 [NUMERICAL] 9 : f_3 [NUMERICAL] 6 : f_11 [NUMERICAL] 5 : f_14 [NUMERICAL] 4 : f_2 [NUMERICAL] 4 : f_13 [NUMERICAL] 2 : f_1 [NUMERICAL] Attribute in nodes with depth <= 5: 131 : f_8 [NUMERICAL] 84 : f_9 [NUMERICAL] 66 : f_4 [NUMERICAL] 59 : f_25 [NUMERICAL] 58 : f_24 [NUMERICAL] 52 : f_23 [NUMERICAL] 45 : f_10 [NUMERICAL] 43 : f_21 [NUMERICAL] 40 : f_22 [NUMERICAL] 32 : f_6 [NUMERICAL] 32 : f_18 [NUMERICAL] 31 : f_19 [NUMERICAL] 29 : f_20 [NUMERICAL] 29 : f_12 [NUMERICAL] 25 : f_17 [NUMERICAL] 25 : f_15 [NUMERICAL] 23 : f_5 [NUMERICAL] 21 : f_3 [NUMERICAL] 17 : f_7 [NUMERICAL] 17 : f_16 [NUMERICAL] 13 : f_14 [NUMERICAL] 13 : f_13 [NUMERICAL] 10 : f_2 [NUMERICAL] 8 : f_11 [NUMERICAL] 6 : f_1 [NUMERICAL] Condition type in nodes: 909 : HigherCondition Condition type in nodes with depth <= 0: 48 : HigherCondition Condition type in nodes with depth <= 1: 141 : HigherCondition Condition type in nodes with depth <= 2: 306 : HigherCondition Condition type in nodes with depth <= 3: 562 : HigherCondition Condition type in nodes with depth <= 5: 909 : HigherCondition