跳到内容

GenericModel

GenericModel

基类:ABC

所有 YDF 模型的抽象超类。

analyze 抽象方法

analyze(
    data: InputDataset,
    sampling: float = 1.0,
    num_bins: int = 50,
    partial_dependence_plot: bool = True,
    conditional_expectation_plot: bool = True,
    permutation_variable_importance_rounds: int = 1,
    num_threads: Optional[int] = None,
    maximum_duration: Optional[float] = 20,
) -> Analysis

在测试数据集上分析模型。

分析包含模型的结构信息(例如,变量重要性)以及模型在给定数据集上的应用信息(例如,部分依赖图)。

对于大型数据集(许多示例和/或特征),计算分析可能需要大量时间。

虽然某些信息可能有效,但通常不建议在训练数据集上分析模型。

使用示例

import pandas as pd
import ydf

# Train model
train_ds = pd.read_csv("train.csv")
model = ydf.RandomForestLearner(label="label").train(train_ds)

test_ds = pd.read_csv("test.csv")
analysis = model.analyze(test_ds)

# Display the analysis in a notebook.
analysis

参数

名称 类型 描述 默认值
data InputDataset

数据集。支持的格式:VerticalDataset,(类型化)路径,(类型化)路径列表,Pandas DataFrame,Xarray Dataset,TensorFlow Dataset,PyGrain DataLoader 和 Dataset(实验性,仅限 Linux),字符串到 NumPy 数组或列表的字典。

必需
sampling float

用于分析的示例比例。分析计算可能很昂贵。在大型数据集上,请使用较小的采样值,例如 0.01。

1.0
num_bins int

用于累积统计数据的 bin 数量。较大的值会增加图的分辨率,但计算时间更长。

50
partial_dependence_plot bool

计算部分依赖图 (a.k.a. PDPs)。计算成本高。

True
conditional_expectation_plot bool

计算条件期望图 (a.k.a. CEP)。计算成本低。

True
permutation_variable_importance_rounds int

如果 >1,则使用 "permutation_variable_importance_rounds" 轮次计算排列变量重要性。轮次越多结果越准确。使用单轮通常是可以接受的,即 permutation_variable_importance_rounds=1。如果 permutation_variable_importance_rounds=0,则禁用排列变量重要性的计算。

1
num_threads Optional[int]

用于计算分析的线程数。

None
maximum_duration Optional[float]

分析的最大持续时间(秒)。请注意,实际分析时间可能比此值稍长。

20

返回值

类型 描述
Analysis

模型分析。

analyze_prediction 抽象方法

analyze_prediction(
    single_example: InputDataset,
) -> PredictionAnalysis

理解模型的单个预测。

注意:要解释整个模型,请使用 model.analyze

使用示例

import pandas as pd
import ydf

# Train model
train_ds = pd.read_csv("train.csv")
model = ydf.RandomForestLearner(label="label").train(train_ds)

test_ds = pd.read_csv("test.csv")

# We want to explain the model prediction on the first test example.
selected_example = test_ds.iloc[:1]

analysis = model.analyze_prediction(selected_example, test_ds)

# Display the analysis in a notebook.
analysis

参数

名称 类型 描述 默认值
single_example InputDataset

要解释的示例。支持的格式:VerticalDataset,(类型化)路径,(类型化)路径列表,Pandas DataFrame,Xarray Dataset,TensorFlow Dataset,PyGrain DataLoader 和 Dataset(实验性,仅限 Linux),字符串到 NumPy 数组或列表的字典。

必需

返回值

类型 描述
PredictionAnalysis

预测解释。

benchmark 抽象方法

benchmark(
    ds: InputDataset,
    benchmark_duration: float = 3,
    warmup_duration: float = 1,
    batch_size: int = 100,
    num_threads: Optional[int] = None,
) -> BenchmarkInferenceCCResult

在给定数据集上对模型的推理速度进行基准测试。

此基准测试使用 Yggdrasil Decision Forests 的 C++ API 在给定数据集上创建批量预测。请注意,使用其他 API 或在不同机器上的推理时间会有所不同。可以使用 model.to_cpp() 生成 C++ API 的服务模板。

参数

名称 类型 描述 默认值
ds InputDataset

用于执行基准测试的数据集。

必需
benchmark_duration float

基准测试的总持续时间(秒)。请注意,此数值仅供参考,实际基准测试持续时间可能更短或更长。此参数必须 > 0。

3
warmup_duration float

基准测试前的预热运行总持续时间(秒)。在预热阶段,基准测试运行但不计时。这允许预热缓存。基准测试将始终运行至少一个批次进行预热。此参数必须 > 0。

1
batch_size int

向推理引擎馈送示例时的批次大小。此参数对结果的影响取决于运行基准测试的架构(特别是缓存大小)。

100
num_threads Optional[int]

用于多线程基准测试的线程数。如果未指定,线程数将设置为 CPU 核心数。

None

返回值

类型 描述
BenchmarkInferenceCCResult

基准测试结果。

data_spec 抽象方法

data_spec() -> DataSpecification

返回用于训练模型的数据规范。

describe 抽象方法

describe(
    output_format: Literal[
        "auto", "text", "notebook", "html"
    ] = "auto",
    full_details: bool = False,
) -> Union[str, HtmlNotebookDisplay]

模型描述。

参数

名称 类型 描述 默认值
output_format Literal['auto', 'text', 'notebook', 'html']

显示格式: - auto:如果在 IPython notebook / Colab 中执行,则使用 "notebook" 格式。否则,使用 "text" 格式。 - text:模型的文本描述。 - html:模型的 Html 描述。 - notebook:在 notebook 单元格中显示的模型的 Html 描述。

'auto'
full_details bool

是否应打印完整的模型。这可能很大。

False

返回值

类型 描述
Union[str, HtmlNotebookDisplay]

模型描述。

evaluate 抽象方法

evaluate(
    data: InputDataset,
    *,
    weighted: Optional[bool] = None,
    task: Optional[Task] = None,
    label: Optional[str] = None,
    group: Optional[str] = None,
    bootstrapping: Union[bool, int] = False,
    ndcg_truncation: int = 5,
    mrr_truncation: int = 5,
    evaluation_task: Optional[Task] = None,
    use_slow_engine: bool = False,
    num_threads: Optional[int] = None
) -> Evaluation

评估模型在数据集上的质量。

使用示例

import pandas as pd
import ydf

# Train model
train_ds = pd.read_csv("train.csv")
model = ydf.RandomForestLearner(label="label").train(train_ds)

test_ds = pd.read_csv("test.csv")
evaluation = model.evaluates(test_ds)

在 notebook 中,如果一个单元格返回一个评估对象,则该评估将以包含图的富 HTML 形式显示。

evaluation = model.evaluate(test_ds)
# If model is an anomaly detection model:
# evaluation = model.evaluate(test_ds,
                              evaluation_task=ydf.Task.CLASSIFICATION)
evaluation

可以以与训练时不同的方式评估模型。例如,可以更改标签、任务和组。

...
# Train a regression model
model = ydf.RandomForestLearner(label="label",
task=ydf.Task.REGRESSION).train(train_ds)

# Evaluate the model as a regressive model
regressive_evaluation = model.evaluates(test_ds)

# Evaluate the model as a ranking model model
regressive_evaluation = model.evaluates(test_ds,
  task=ydf.Task.RANKING, group="group_column")

参数

名称 类型 描述 默认值
data InputDataset

数据集。支持的格式:VerticalDataset,(类型化)路径,(类型化)路径列表,Pandas DataFrame,Xarray Dataset,TensorFlow Dataset,PyGrain DataLoader 和 Dataset(实验性,仅限 Linux),字符串到 NumPy 数组或列表的字典。

必需
weighted Optional[bool]

如果为 true,则评估会根据训练权重进行加权。如果为 false,则评估不加权。b/351279797:将默认值更改为 weights=True。

None
task Optional[Task]

在评估期间覆盖模型的任务。如果为 None(默认值),则根据其训练任务评估模型。

None
label Optional[str]

覆盖用于评估模型的标签。如果为 None(默认值),则使用模型的标签。

None
group Optional[str]

覆盖用于评估模型的组。如果为 None(默认值),则使用模型的组。仅用于排序模型。

None
bootstrapping Union[bool, int]

控制是否使用 bootstrapping 来评估置信区间和统计测试(即,所有以 "[B]" 结尾的指标)。如果设置为 false,则禁用 bootstrapping。如果设置为 true,则启用 bootstrapping 并使用 2000 个 bootstrapping 样本。如果设置为整数,则指定要使用的 bootstrapping 样本数。在这种情况下,如果数值小于 100,则会引发错误,因为 bootstrapping 不会产生有用的结果。

False
ndcg_truncation int

控制 NDCG 指标应在哪个排序位置截断。默认为 5。非排序模型忽略此参数。

5
mrr_truncation int

控制 MRR 指标损失应在哪个排序位置截断。默认为 5。非排序模型忽略此参数。

5
evaluation_task Optional[Task]

已弃用。请改用 task

None
use_slow_engine bool

如果为 true,则使用慢速引擎进行预测。YDF 的慢速引擎比其他预测引擎慢一个数量级。在极少数边缘情况下,使用常规引擎进行预测会失败,例如,具有非常多类别条件的模型。只有在这种情况下,用户才应该使用慢速引擎并向 YDF 开发者报告问题。

False
num_threads Optional[int]

运行模型使用的线程数。

None

返回值

类型 描述
Evaluation

模型评估。

feature_selection_logs 抽象方法

feature_selection_logs() -> Optional[FeatureSelectorLogs]

获取特征选择日志。

force_engine 抽象方法

force_engine(engine_name: Optional[str]) -> None

强制模型使用的引擎。

如果未指定(即 None;默认值),则所有模型推理(例如 model.predict、model.evaluate)都使用最快的兼容引擎(即 "list_compatible_engines" 返回的第一个值)。

如果传递了不存在或不兼容的引擎名称,则下一次模型推理(例如 model.predict、model.evaluate)将失败。

参数

名称 类型 描述 默认值
engine_name Optional[str]

兼容引擎的名称,或者 None 表示自动选择最快的引擎。

必需

hyperparameter_optimizer_logs 抽象方法

hyperparameter_optimizer_logs() -> Optional[OptimizerLogs]

返回超参数调优日志。

如果模型未进行超参数调优训练,则返回 None。

input_feature_names

input_feature_names() -> List[str]

返回输入特征的名称。

特征按 column_idx 升序排序。

input_features

input_features() -> Sequence[InputFeature]

返回模型的输入特征。

特征按 column_idx 升序排序。

input_features_col_idxs 抽象方法

input_features_col_idxs() -> Sequence[int]

label

label() -> str

标签列的名称。

label_classes

label_classes() -> List[str]

返回分类模型的标签类别;否则失败。

label_col_idx 抽象方法

label_col_idx() -> int

list_compatible_engines 抽象方法

list_compatible_engines() -> Sequence[str]

列出与模型兼容的推理引擎。

引擎按可能最快到可能最慢的顺序排序。

返回值

类型 描述
Sequence[str]

兼容引擎列表。

metadata 抽象方法

metadata() -> ModelMetadata

与模型关联的元数据。

模型的元数据包含与模型一起存储但不影响模型预测的信息(例如创建日期)。在广泛分发模型时,使用 model.set_metadata(ydf.ModelMetadata()) 清除/修改模型元数据可能很有用。

返回值

类型 描述
ModelMetadata

模型的元数据。

name 抽象方法

name() -> str

返回模型类型的名称。

predict 抽象方法

predict(
    data: InputDataset,
    *,
    use_slow_engine: bool = False,
    num_threads: Optional[int] = None
) -> ndarray

返回模型在给定数据集上的预测。

使用示例

import pandas as pd
import ydf

# Train model
train_ds = pd.read_csv("train.csv")
model = ydf.RandomForestLearner(label="label").train(train_ds)

test_ds = pd.read_csv("test.csv")
predictions = model.predict(test_ds)

预测结果是一个包含 float32 值的 NumPy 数组。此数组的结构取决于模型的任务,在某些情况下还取决于类别的数量。

分类 (model.task() == ydf.Task.CLASSIFICATION)

  • 二分类: 对于有两个类别的模型 (len(model.label_classes()) == 2),输出是一个形状为 [num_examples] 的数组。每个值代表正类别 (model.label_classes()[1]) 的预测概率。要获取负类别的概率,请使用 1 - model.predict(dataset)

以下是获取最可能类别的示例

prediction_proba = model.predict(test_ds)
predicted_classes = np.take(model.label_classes(), prediction_proba
>= 0.5)

# Or simply
predicted_classes = model.predict_class(test_ds)
  • 多分类: 对于有两个以上类别的模型,输出是一个形状为 [num_examples, num_classes] 的数组。索引 [i, j] 处的值是示例 i 的类别 j 的概率。

以下是获取最可能类别的示例

prediction_proba = model.predict(test_ds)
prediction_class_idx = np.argmax(prediction_proba, axis=1)
predicted_classes = np.take(model.label_classes(),
prediction_class_idx)

# Or simply
predicted_classes = model.predict_class(test_ds)

回归 (model.task() == ydf.Task.REGRESSION)

输出是一个形状为 [num_examples] 的数组,其中每个值是对应示例的预测值。

排序 (model.task() == ydf.Task.RANKING)

输出是一个形状为 [num_examples] 的数组,其中每个值代表对应示例的得分。得分越高表示排名越高。

类别提升 (model.task() == ydf.Task.CATEGORICAL_UPLIFT)

输出是一个形状为 [num_examples] 的数组,其中每个值代表预测的提升值。正值表示治疗对结果有积极影响,而接近零的值表示效果很小或没有效果。

数值提升 (model.task() == ydf.Task.NUMERICAL_UPLIFT)

输出是一个形状为 [num_examples] 的数组,其解释与类别提升相同。

异常检测 (model.task() == ydf.Task.ANOMALY_DETECTION)

输出是一个形状为 [num_examples] 的数组,其中每个值是对应示例的异常分数。分数范围从 0(最正常)到 1(最异常)。

参数

名称 类型 描述 默认值
data InputDataset

数据集。支持的格式:VerticalDataset,(类型化)路径,(类型化)路径列表,Pandas DataFrame,Xarray Dataset,TensorFlow Dataset,PyGrain DataLoader 和 Dataset(实验性,仅限 Linux),字符串到 NumPy 数组或列表的字典。如果数据集包含标签列,则忽略该列。

必需
use_slow_engine bool

如果为 true,则使用慢速引擎进行预测。YDF 的慢速引擎比其他预测引擎慢一个数量级。在极少数边缘情况下,使用常规引擎进行预测会失败,例如,具有非常多类别条件的模型。只有在这种情况下,用户才应该使用慢速引擎并向 YDF 开发者报告问题。

False
num_threads Optional[int]

运行模型使用的线程数。

None

返回值

类型 描述
ndarray

模型在给定数据集上的预测。

predict_class

predict_class(
    data: InputDataset,
    *,
    use_slow_engine: bool = False,
    num_threads: Optional[int] = None
) -> ndarray

返回分类模型最可能预测的类别。

使用示例

import pandas as pd
import ydf

# Train model
train_ds = pd.read_csv("train.csv")
model = ydf.RandomForestLearner(label="label").train(train_ds)

test_ds = pd.read_csv("test.csv")
predictions = model.predict_class(test_ds)

此方法返回一个形状为 [num_examples] 的字符串 numpy 数组。每个值代表对应示例最可能预测的类别。此方法仅可用于分类模型。

如果出现平局,则返回 model.label_classes() 中的第一个类别。

请参阅 model.predict 生成完整的预测概率。

参数

名称 类型 描述 默认值
data InputDataset

数据集。支持的格式:VerticalDataset,(类型化)路径,(类型化)路径列表,Pandas DataFrame,Xarray Dataset,TensorFlow Dataset,PyGrain DataLoader 和 Dataset(实验性,仅限 Linux),字符串到 NumPy 数组或列表的字典。如果数据集包含标签列,则忽略该列。

必需
use_slow_engine bool

如果为 true,则使用慢速引擎进行预测。YDF 的慢速引擎比其他预测引擎慢一个数量级。在极少数边缘情况下,使用常规引擎进行预测会失败,例如,具有非常多类别条件的模型。只有在这种情况下,用户才应该使用慢速引擎并向 YDF 开发者报告问题。

False
num_threads Optional[int]

运行模型使用的线程数。

None

返回值

类型 描述
ndarray

每个示例最可能预测的类别。

save 抽象方法

save(
    path: str,
    advanced_options: ModelIOOptions = ModelIOOptions(),
    *,
    pure_serving: bool = False
) -> None

将模型保存到磁盘。

YDF 使用专有模型格式保存模型。一个模型由位于同一目录中的多个文件组成。一个目录只应包含一个 YDF 模型。有关详细信息,请参阅 advanced_options

YDF 模型也可以导出为其他格式,有关详细信息,请参阅 to_tensorflow_saved_model()to_cpp()

YDF 在模型内部保存了一些元数据,有关详细信息,请参阅 model.metadata()。在向外分发模型之前,考虑使用 model.set_metadata(ydf.ModelMetadata()) 删除元数据。

使用示例

import pandas as pd
import ydf

# Train a Random Forest model
df = pd.read_csv("my_dataset.csv")
model = ydf.RandomForestLearner().train(df)

# Save the model to disk
model.save("/models/my_model")

参数

名称 类型 描述 默认值
path str

模型存储目录的路径。

必需
advanced_options ModelIOOptions

保存模型的高级选项。

ModelIOOptions()
pure_serving bool

如果为 true,则保存模型时不包含调试信息,以节省磁盘空间。请注意,此选项在保存期间可能需要额外的内存,即使结果模型在磁盘上会显著减小。

False

self_evaluation

self_evaluation() -> Evaluation

返回模型的自评估。

不同模型使用不同的自评估方法。值得注意的是,随机森林使用 OOB 评估,梯度提升树在验证数据集上进行评估。因此,不同模型类型之间的自评估不可比较。

使用示例

import pandas as pd
import ydf

# Train model
train_ds = pd.read_csv("train.csv")
model = ydf.GradientBoostedTreesLearner(label="label").train(train_ds)

self_evaluation = model.self_evaluation()
# In an interactive Python environment, print a rich evaluation report.
self_evaluation

serialize 抽象方法

serialize() -> bytes

将模型序列化为字节序列(即 bytes)。

序列化的模型等同于使用 model.save 保存的模型。它可能包含与模型训练和解释相关的元数据。为了最小化序列化模型的大小,通过将参数 pure_serving_model=True 传递给 train 方法来移除此元数据。

使用示例

import pandas as pd
import ydf

# Create a model
dataset = pd.DataFrame({"feature": [0, 1], "label": [0, 1]})
learner = ydf.RandomForestLearner(label="label")
model = learner.train(dataset)

# Serialize model
# Note: serialized_model is a bytes.
serialized_model = model.serialize()

# Deserialize model
deserialized_model = ydf.deserialize_model(serialized_model)

# Make predictions
model.predict(dataset)
deserialized_model.predict(dataset)

返回值

类型 描述
bytes

序列化的模型。

set_data_spec

set_data_spec(data_spec: DataSpecification) -> None

更改模型的数据规范 (dataspec)。

此操作面向高级用户。

参数

名称 类型 描述 默认值
data_spec DataSpecification

新的数据规范 (dataspec)。

必需

set_feature_selection_logs 抽象方法

set_feature_selection_logs(
    value: Optional[FeatureSelectorLogs],
) -> None

记录特征选择日志。

set_metadata 抽象方法

set_metadata(metadata: ModelMetadata)

设置模型元数据。

task 抽象方法

task() -> Task

模型解决的任务。

to_cpp 抽象方法

to_cpp(key: str = 'my_model') -> str

生成 .h 文件的代码,用于在 C++ 中运行模型。

如何使用此函数

  1. 将此函数的输出复制到一个新的 .h 文件中。open("model.h", "w").write(model.to_cpp())
  2. 如果您使用 Bazel/Blaze,请创建一个规则,其依赖项为://third_party/absl/status:statusor //third_party/absl/strings //external/ydf_cc/yggdrasil_decision_forests/api:serving
  3. 在您的 C++ 代码中,包含 .h 文件并使用以下代码调用模型:// 加载模型(只需执行一次)。namespace ydf = yggdrasil_decision_forests; const auto model = ydf::exported_model_123::Load(); // 运行模型 predictions = model.Predict();
  4. 生成的 "Predict" 函数不接受输入。相反,它使用占位符值填充输入特征。因此,您需要将输入作为参数添加到 "Predict" 函数中,并相应地使用它来填充 "examples->Set..." 部分。
  5. (额外提示)通过预分配并重用每个运行模型的线程的示例和预测,可以进一步优化推理速度。

此文档也包含在生成内容的头文件中,以获取更多详细信息。

参数

名称 类型 描述 默认值
key str

模型名称。用于定义模型的 C++ 命名空间。

'my_model'

返回值

类型 描述
str

包含用于在 C++ 中运行模型的示例头文件的字符串。

to_jax_function 抽象方法

to_jax_function(
    jit: bool = True,
    apply_activation: bool = True,
    leaves_as_params: bool = False,
    compatibility: Union[str, Compatibility] = "XLA",
) -> JaxModel

将 YDF 模型转换为 JAX 函数。

使用示例

import ydf
import numpy as np
import jax.numpy as jnp

# Train a model.
model = ydf.GradientBoostedTreesLearner(label="l").train({
    "f1": np.random.random(size=100),
    "f2": np.random.random(size=100),
    "l": np.random.randint(2, size=100),
})

# Convert model to a JAX function.
jax_model = model.to_jax_function()

# Make predictions with the JAX function.
jax_predictions = jax_model.predict({
    "f1": jnp.array([0, 0.5, 1]),
    "f2": jnp.array([1, 0, 0.5]),
})

TODO:文档中加入 encoder 和 jax params 的说明。

参数

名称 类型 描述 默认值
jit bool

如果为 true,则使用 @jax.jit 编译函数。

True
apply_activation bool

是否应将激活函数(如果存在)应用于模型输出。

True
leaves_as_params bool

如果为 true,则将叶子值导出为可学习参数。在这种情况下,返回值的 params 会被设置,并且应该传递给 predict(feature_values, params)

False
compatibility Union[str, Compatibility]

对 YDF 到 JAX 转换的运行时兼容性限制。可以是 "XLA"(默认)和 "TFL"(用于 TensorFlow Lite)。

'XLA'

返回值

类型 描述
JaxModel

包含 JAX 预测函数 (predict) 的数据类,以及

JaxModel

可选的模型参数 (params) 和特征编码器

JaxModel

(encoder)。

to_tensorflow_function 抽象方法

to_tensorflow_function(
    temp_dir: Optional[str] = None,
    can_be_saved: bool = True,
    squeeze_binary_classification: bool = True,
    force: bool = False,
) -> Module

将 YDF 模型转换为可调用的 @tf.function TensorFlow Module。

输出模块可以与其他 TensorFlow 操作组合,包括使用 to_tensorflow_function 序列化的其他模型。

此函数需要安装 TensorFlow 和 TensorFlow Decision Forests。可以使用命令 pip install tensorflow_decision_forests 进行安装。生成的 SavedModel 模型依赖于 TensorFlow Decision Forests 自定义推理操作 (Custom Inference Op)。此操作在 Servomatic、TensorFlow Serving、Vertex AI 和 TensorFlow.js 等各种平台中默认可用。

使用示例

!pip install tensorflow_decision_forests

import ydf
import numpy as np
import tensorflow as tf

# Train a model.
model = ydf.RandomForestLearner(label="l").train({
    "f1": np.random.random(size=100),
    "f2": np.random.random(size=100),
    "l": np.random.randint(2, size=100),
})

# Convert model to a TF module.
tf_model = model.to_tensorflow_function()

# Make predictions with the TF module.
tf_predictions = tf_model({
    "f1": tf.constant([0, 0.5, 1]),
    "f2": tf.constant([1, 0, 0.5]),
})

参数

名称 类型 描述 默认值
temp_dir Optional[str]

转换期间使用的临时目录。如果为 None(默认),则使用 tempfile.mkdtemp 默认临时目录。

None
can_be_saved bool

如果 can_be_saved = True(默认值),则返回的模块可以使用 tf.saved_model.save 保存。在这种情况下,转换期间在临时目录中创建的文件在 to_tensorflow_function 退出时不会被删除,并且在调用 tf.saved_model.save 时这些文件应该仍然存在。如果 can_be_saved = False,则转换期间在临时目录中创建的文件会立即删除,并且返回的对象不能使用 tf.saved_model.save 序列化。

True
squeeze_binary_classification bool

如果为 true(默认值),对于二分类,输出形状为 [num examples] 的张量,其中包含正类别的概率。如果为 false,对于二分类,输出形状为 [num examples, 2] 的 TensorFlow 张量,其中包含负类别和正类别的概率。对非二分类模型没有影响。

True
force bool

即使在当前不支持的环境中也尝试导出。

False

返回值

类型 描述
Module

一个 TensorFlow @tf.function。

to_tensorflow_saved_model 抽象方法

to_tensorflow_saved_model(
    path: str,
    input_model_signature_fn: Any = None,
    *,
    mode: Literal["keras", "tf"] = "keras",
    feature_dtypes: Dict[str, TFDType] = {},
    servo_api: bool = False,
    feed_example_proto: bool = False,
    pre_processing: Optional[Callable] = None,
    post_processing: Optional[Callable] = None,
    temp_dir: Optional[str] = None,
    tensor_specs: Optional[Dict[str, Any]] = None,
    feature_specs: Optional[Dict[str, Any]] = None,
    force: bool = False
) -> None

将模型导出为 TensorFlow SavedModel。

此函数需要安装 TensorFlow 和 TensorFlow Decision Forests。可以通过运行命令 pip install tensorflow_decision_forests 进行安装。生成的 SavedModel 模型依赖于 TensorFlow Decision Forests 自定义推理操作 (Custom Inference Op)。此操作在 Servomatic、TensorFlow Serving、Vertex AI 和 TensorFlow.js 等各种平台中默认可用。

使用示例

!pip install tensorflow_decision_forests

import ydf
import numpy as np
import tensorflow as tf

# Train a model.
model = ydf.RandomForestLearner(label="l").train({
    "f1": np.random.random(size=100),
    "f2": np.random.random(size=100).astype(dtype=np.float32),
    "l": np.random.randint(2, size=100),
})

# Export the model to the TensorFlow SavedModel format.
# The model can be executed with Servomatic, TensorFlow Serving and
# Vertex AI.
model.to_tensorflow_saved_model(path="/tmp/my_model", mode="tf")

# The model can also be loaded in TensorFlow and executed locally.

# Load the TensorFlow Saved model.
tf_model = tf.saved_model.load("/tmp/my_model")

# Make predictions
tf_predictions = tf_model({
    "f1": tf.constant(np.random.random(size=10)),
    "f2": tf.constant(np.random.random(size=10), dtype=tf.float32),
})

TensorFlow SavedModel 不会自动转换特征值。例如,对于使用 dtype=float32 semantic=numerical 特征训练的模型,在推理期间需要将此特征作为 float32 数值馈送。您可以使用 feature_dtypes 参数覆盖特征的 dtype。

model.to_tensorflow_saved_model(
    path="/tmp/my_model",
    mode="tf",
    # "f1" is fed as an tf.int64 instead of tf.float64
    feature_dtypes={"f1": tf.int64},
)

一些 TensorFlow Serving 或 Servomatic 管道依赖于将示例作为序列化的 TensorFlow Example proto(而不是原始张量值)馈送,并且/或将模型的原始输出(例如概率预测)封装到特殊结构(称为 Serving API)中。您可以使用 feed_example_proto=Trueservo_api=True 分别创建与这两种约定兼容的模型。

model.to_tensorflow_saved_model(
    path="/tmp/my_model",
    mode="tf",
    feed_example_proto=True,
    servo_api=True
)

如果您的模型需要一些数据预处理或后处理,您可以将它们表示为 @tf.function 或 tf 模块,并分别将它们传递给 pre_processingpost_processing 参数。

警告:导出 SavedModel 时,YDF 会根据训练期间观察到的特征的 dtype 推断模型签名。如果 pre_processing 函数的签名与模型签名不同(例如,处理会创建一个新特征),您需要指定张量规范 (tensor_specs;如果 feed_example_proto=False) 或特征规范 (feature_specs;如果 feed_example_proto=True) 参数。

# Define a pre-processing function
@tf.function
def pre_processing(raw_features):
  features = {**raw_features}
  # Create a new feature.
  features["sin_f1"] = tf.sin(features["f1"])
  # Remove a feature
  del features["f1"]
  return features

# Create Numpy dataset
raw_dataset = {
    "f1": np.random.random(size=100),
    "f2": np.random.random(size=100),
    "l": np.random.randint(2, size=100),
}

# Apply the preprocessing on the training dataset.
processed_dataset = (
    tf.data.Dataset.from_tensor_slices(raw_dataset)
    .batch(128)  # The batch size has no impact on the model.
    .map(preprocessing)
    .prefetch(tf.data.AUTOTUNE)
)

# Train a model on the pre-processed dataset.
ydf_model = specialized_learners.RandomForestLearner(
    label="l",
    task=generic_learner.Task.CLASSIFICATION,
).train(processed_dataset)

# Export the model to a raw SavedModel model with the pre-processing
model.to_tensorflow_saved_model(
    path="/tmp/my_model",
    mode="tf",
    feed_example_proto=False,
    pre_processing=pre_processing,
    tensor_specs{
        "f1": tf.TensorSpec(shape=[None], name="f1", dtype=tf.float64),
        "f2": tf.TensorSpec(shape=[None], name="f2", dtype=tf.float64),
    }
)

# Export the model to a SavedModel consuming serialized tf examples with the
# pre-processing
model.to_tensorflow_saved_model(
    path="/tmp/my_model",
    mode="tf",
    feed_example_proto=True,
    pre_processing=pre_processing,
    feature_specs={
        "f1": tf.io.FixedLenFeature(
            shape=[], dtype=tf.float32, default_value=math.nan
        ),
        "f2": tf.io.FixedLenFeature(
            shape=[], dtype=tf.float32, default_value=math.nan
        ),
    }
)

为了获得更大的灵活性,请使用 to_tensorflow_function 方法而不是 to_tensorflow_saved_model

参数

名称 类型 描述 默认值
path str

存储 TensorFlow Decision Forests 模型的路径。

必需
input_model_signature_fn Any

返回与模型输入签名对应的 (Dense,Sparse,Ragged)TensorSpec(或 TensorSpec 结构,例如字典、列表)的 lambda 函数。如果未指定,则输入模型签名由 tfdf.keras.build_default_input_model_signature 创建。例如,如果一个数值输入特征(默认为 DenseTensorSpec(float32))将以不同方式馈送(例如 RaggedTensor(int64)),则指定 input_model_signature_fn。仅兼容 mode="keras"。

None
mode Literal['keras', 'tf']

YDF 如何转换为 TensorFlow SavedModel。 1) mode = "keras"(默认):使用 TensorFlow Decision Forests 将模型转换为 Keras 2 模型,然后使用 tf_keras.models.save_model 保存。 2) mode = "tf"(推荐;将成为默认):将模型转换为 TensorFlow Module,然后使用 tf.saved_model.save 保存。

'keras'
feature_dtypes Dict[str, TFDType]

从特征名称到 TensorFlow dtype 的映射。使用此映射指定特征 dtype。例如,数值特征默认为 tf.float32 编码。如果您计划馈送 tf.float64 或 tf.int32,请使用 feature_dtype 指定。如果设置了 tensor_specs,则忽略 feature_dtypes。如果设置了此参数,则禁用对 pre_processing 的自动签名提取(如果也设置了 pre_processing)。仅兼容 mode="tf"。

{}
servo_api bool

如果为 true,则添加 SavedModel 签名,使模型与 ClassifyRegress servo API 兼容。仅兼容 mode="tf"。如果为 false,则输出原始模型预测。

False
feed_example_proto bool

如果为 false,模型期望输入特征作为 TensorFlow 值提供。这是进行预测最有效的方式。如果为 true,模型期望输入特征作为二进制序列化的 TensorFlow Example proto 提供。这是 VertexAI 和大多数 TensorFlow Serving 管道期望的格式。

False
pre_processing Optional[Callable]

可选的 TensorFlow 函数或模块,用于在应用模型之前应用于输入特征。如果 pre_processing 函数已被跟踪(即,该函数已使用实际数据调用一次并在其缓存中包含具体实例),则会提取此签名并用作 SavedModel 的签名。仅兼容 mode="tf"。

None
post_processing Optional[Callable]

可选的 TensorFlow 函数或模块,用于应用于模型预测。仅兼容 mode="tf"。

None
temp_dir Optional[str]

转换期间使用的临时目录。如果为 None(默认),则使用 tempfile.mkdtemp 默认临时目录。

None
tensor_specs Optional[Dict[str, Any]]

可选的 tf.TensorSpec 字典,定义要导出的模型的输入特征。如果未提供,则根据训练期间看到的模型特征自动生成 TensorSpecs。这意味着只有在使用期望特征与模型训练时不同的 "pre_processing" 参数时才需要 "tensor_specs"。当使用 feed_example_proto=True 导出模型时,此参数将被忽略,因为在这种情况下,TensorSpecs 由 tf.io.parse_example 解析特征规范定义。仅兼容 mode="tf"。

None
feature_specs Optional[Dict[str, Any]]

可选的 tf.io.parse_example 解析特征规范字典,例如 tf.io.FixedLenFeaturetf.io.RaggedFeature。如果未提供,则根据训练期间看到的模型特征自动生成解析特征规范。这意味着只有在使用期望特征与模型训练时不同的 "pre_processing" 参数时才需要 "feature_specs"。当使用 feed_example_proto=False 导出模型时,此参数将被忽略。仅兼容 mode="tf"。

None
force bool

即使在当前不支持的环境中也尝试导出。警告:将其设置为 true 可能会导致 Python 运行时崩溃。

False

update_with_jax_params 抽象方法

update_with_jax_params(params: Dict[str, Any])

使用由 to_jax_function 创建的 JAX 参数更新模型。

使用示例

import ydf
import numpy as np
import jax.numpy as jnp

# Train a model with YDF
dataset = {
    "f1": np.random.random(size=100),
    "f2": np.random.random(size=100),
    "l": np.random.randint(2, size=100),
}
model = ydf.GradientBoostedTreesLearner(label="l").train(dataset)

# Convert model to a JAX function with leave values as parameters.
jax_model = model.to_jax_function(
    leaves_as_params=True,
    apply_activation=True)
# Note: The learnable model parameter are in `jax_model.params`.

# Finetune the model parameters with your own logic.
jax_model.params = fine_tune_model(jax_model.params, ...)

# Update the YDF model with the finetuned parameters
model.update_with_jax_params(jax_model.params)

# Make predictions with the finetuned YDF model
predictions = model.predict(dataset)

# Save the YDF model
model.save("/tmp/my_ydf_model")

参数

名称 类型 描述 默认值
params Dict[str, Any]

使用 to_jax_function 生成的模型的可学习参数。

必需

variable_importances 抽象方法

variable_importances() -> (
    Dict[str, List[Tuple[float, str]]]
)

变量重要性,用于衡量特征对模型的影响。

变量重要性通常表示一个变量(特征)对模型预测或质量的贡献程度。不同的变量重要性具有不同的语义,通常不可比较。

variable_importances() 返回的变量重要性取决于学习算法及其超参数。例如,随机森林学习器的超参数 compute_oob_variable_importances=True 启用计算袋外排列变量重要性。

特征按重要性降序排序。

使用示例

# Train a Random Forest. Enable the computation of OOB (out-of-bag) variable
# importances.
model = ydf.RandomForestModel(compute_oob_variable_importances=True,
                              label=...).train(ds)
# List the available variable importances.
print(model.variable_importances().keys())

# Show a specific variable importance.
model.variable_importances()["MEAN_DECREASE_IN_ACCURACY"]
>> [("bill_length_mm", 0.0713061951754389),
    ("island", 0.007298519736842035),
    ("flipper_length_mm", 0.004505893640351366),
...

返回值

类型 描述
Dict[str, List[Tuple[float, str]]]

变量重要性。

DecisionForestModel

DecisionForestModel(raw_model: GenericCCModel)

基类:GenericCCModel

用于预测和检查的通用决策森林模型。

add_tree

add_tree(tree: Tree) -> None

向模型添加单个树。

参数

名称 类型 描述 默认值
tree Tree

新树。

必需

analyze

analyze(
    data: InputDataset,
    sampling: float = 1.0,
    num_bins: int = 50,
    partial_dependence_plot: bool = True,
    conditional_expectation_plot: bool = True,
    permutation_variable_importance_rounds: int = 1,
    num_threads: Optional[int] = None,
    maximum_duration: Optional[float] = 20,
) -> Analysis

analyze_prediction

analyze_prediction(
    single_example: InputDataset,
) -> PredictionAnalysis

benchmark

benchmark(
    ds: InputDataset,
    benchmark_duration: float = 3,
    warmup_duration: float = 1,
    batch_size: int = 100,
    num_threads: Optional[int] = None,
) -> BenchmarkInferenceCCResult

data_spec

data_spec() -> DataSpecification

describe

describe(
    output_format: Literal[
        "auto", "text", "notebook", "html"
    ] = "auto",
    full_details: bool = False,
) -> Union[str, HtmlNotebookDisplay]

distance

distance(
    data1: InputDataset,
    data2: Optional[InputDataset] = None,
) -> ndarray

计算 "data1" 和 "data2" 中示例之间的成对距离。

如果未提供 "data2",则计算 "data1" 中示例之间的成对距离。

使用示例

import pandas as pd
import ydf

# Train model
train_ds = pd.read_csv("train.csv")
model = ydf.RandomForestLearner(label="label").Train(train_ds)

test_ds = pd.read_csv("test.csv")
distances = model.distance(test_ds, train_ds)
# "distances[i,j]" is the distance between the i-th test example and the
# j-th train example.

不同模型可以自由实现具有不同定义的距离。因此,除非模型指示,否则不同模型之间的距离不可比较。

不保证距离满足度量距离的三角不等式性质。

并非所有模型都能计算距离。在这种情况下,此函数将引发异常。

参数

名称 类型 描述 默认值
data1 InputDataset

数据集。可以是值列表或 numpy 数组的字典、Pandas DataFrame 或 VerticalDataset。

必需
data2 Optional[InputDataset]

数据集。可以是值列表或 numpy 数组的字典、Pandas DataFrame 或 VerticalDataset。

None

返回值

类型 描述
ndarray

成对距离

evaluate

evaluate(
    data: InputDataset,
    *,
    weighted: Optional[bool] = None,
    task: Optional[Task] = None,
    label: Optional[str] = None,
    group: Optional[str] = None,
    bootstrapping: Union[bool, int] = False,
    ndcg_truncation: int = 5,
    mrr_truncation: int = 5,
    evaluation_task: Optional[Task] = None,
    use_slow_engine: bool = False,
    num_threads: Optional[int] = None
) -> Evaluation

feature_selection_logs

feature_selection_logs() -> Optional[FeatureSelectorLogs]

force_engine

force_engine(engine_name: Optional[str]) -> None

get_all_trees

get_all_trees() -> Sequence[Tree]

返回模型中的所有树。

get_tree

get_tree(tree_idx: int) -> Tree

获取模型的单个树。

参数

名称 类型 描述 默认值
tree_idx int

树的索引。应在 [0, num_trees()) 范围内。

必需

返回值

类型 描述
Tree

树。

hyperparameter_optimizer_logs

hyperparameter_optimizer_logs() -> Optional[OptimizerLogs]

input_feature_names

input_feature_names() -> List[str]

返回输入特征的名称。

特征按 column_idx 升序排序。

input_features

input_features() -> Sequence[InputFeature]

返回模型的输入特征。

特征按 column_idx 升序排序。

input_features_col_idxs

input_features_col_idxs() -> Sequence[int]

iter_trees

iter_trees() -> Iterator[Tree]

返回模型中所有树的迭代器。

label

label() -> str

标签列的名称。

label_classes

label_classes() -> List[str]

返回分类模型的标签类别;否则失败。

label_col_idx

label_col_idx() -> int

list_compatible_engines

list_compatible_engines() -> Sequence[str]

metadata

metadata() -> ModelMetadata

name

name() -> str

num_trees

num_trees()

返回决策森林中的树数量。

plot_tree

plot_tree(
    tree_idx: int = 0,
    max_depth: Optional[int] = None,
    options: Optional[PlotOptions] = None,
    d3js_url: str = "https://d3js.cn/d3.v6.min.js",
) -> TreePlot

绘制树的交互式 HTML 渲染图。

使用示例

# Create a dataset
train_ds = pd.DataFrame({
    "c1": [1.0, 1.1, 2.0, 3.5, 4.2] + list(range(10)),
    "label": ["a", "b", "b", "a", "a"] * 3,
})
# Train a CART model
model = ydf.CartLearner(label="label").train(train_ds)
# Make sure the model is a CART
assert isinstance(model, ydf.CARTModel)
# Plot the tree in Colab
model.plot_tree()

参数

名称 类型 描述 默认值
tree_idx int

树的索引。应在 [0, self.num_trees()) 范围内。

0
max_depth Optional[int]

绘制的最大树深度。设置为 None 表示完整深度。

None
options Optional[PlotOptions]

绘图的高级选项。设置为 None 使用默认样式。

None
d3js_url str

加载 d3.js 库的 URL。

'https://d3js.cn/d3.v6.min.js'

返回值

类型 描述
TreePlot

在交互式环境中,是一个交互式图。HTML 源代码也可以

TreePlot

导出到文件。

predict

predict(
    data: InputDataset,
    *,
    use_slow_engine: bool = False,
    num_threads: Optional[int] = None
) -> ndarray

predict_class

predict_class(
    data: InputDataset,
    *,
    use_slow_engine: bool = False,
    num_threads: Optional[int] = None
) -> ndarray

返回分类模型最可能预测的类别。

使用示例

import pandas as pd
import ydf

# Train model
train_ds = pd.read_csv("train.csv")
model = ydf.RandomForestLearner(label="label").train(train_ds)

test_ds = pd.read_csv("test.csv")
predictions = model.predict_class(test_ds)

此方法返回一个形状为 [num_examples] 的字符串 numpy 数组。每个值代表对应示例最可能预测的类别。此方法仅可用于分类模型。

如果出现平局,则返回 model.label_classes() 中的第一个类别。

请参阅 model.predict 生成完整的预测概率。

参数

名称 类型 描述 默认值
data InputDataset

数据集。支持的格式:VerticalDataset,(类型化)路径,(类型化)路径列表,Pandas DataFrame,Xarray Dataset,TensorFlow Dataset,PyGrain DataLoader 和 Dataset(实验性,仅限 Linux),字符串到 NumPy 数组或列表的字典。如果数据集包含标签列,则忽略该列。

必需
use_slow_engine bool

如果为 true,则使用慢速引擎进行预测。YDF 的慢速引擎比其他预测引擎慢一个数量级。在极少数边缘情况下,使用常规引擎进行预测会失败,例如,具有非常多类别条件的模型。只有在这种情况下,用户才应该使用慢速引擎并向 YDF 开发者报告问题。

False
num_threads Optional[int]

运行模型使用的线程数。

None

返回值

类型 描述
ndarray

每个示例最可能预测的类别。

predict_leaves

predict_leaves(data: InputDataset) -> ndarray

获取每棵树中活动叶子的索引。

活动叶子是推理期间接收示例的叶子。

返回的值 "leaves[i,j]" 是第 i 个示例和第 j 棵树的活动叶子的索引。叶子按照深度优先遍历进行索引,其中先访问负子节点,后访问正子节点。

参数

名称 类型 描述 默认值
data InputDataset

数据集。

必需

返回值

类型 描述
ndarray

模型中每棵树的活动叶子索引。

print_tree

print_tree(
    tree_idx: int = 0,
    max_depth: Optional[int] = 6,
    file: Any = stdout,
) -> None

在终端中打印树。

使用示例

# Create a dataset
train_ds = pd.DataFrame({
    "c1": [1.0, 1.1, 2.0, 3.5, 4.2] + list(range(10)),
    "label": ["a", "b", "b", "a", "a"] * 3,
})
# Train a CART model
model = ydf.CartLearner(label="label").train(train_ds)
# Make sure the model is a CART
assert isinstance(model, ydf.CARTModel)
# Print the tree
model.print_tree()

参数

名称 类型 描述 默认值
tree_idx int

树的索引。应在 [0, self.num_trees()) 范围内。

0
max_depth Optional[int]

绘制的最大树深度。设置为 None 表示完整深度。

6
file Any

打印树的位置。默认情况下,打印到终端标准输出。

stdout

remove_tree

remove_tree(tree_idx: int) -> None

移除模型的单个树。

参数

名称 类型 描述 默认值
tree_idx int

树的索引。应在 [0, num_trees()) 范围内。

必需

save

save(
    path: str,
    advanced_options=ModelIOOptions(),
    *,
    pure_serving=False
) -> None

self_evaluation

self_evaluation() -> Evaluation

返回模型的自评估。

不同模型使用不同的自评估方法。值得注意的是,随机森林使用 OOB 评估,梯度提升树在验证数据集上进行评估。因此,不同模型类型之间的自评估不可比较。

使用示例

import pandas as pd
import ydf

# Train model
train_ds = pd.read_csv("train.csv")
model = ydf.GradientBoostedTreesLearner(label="label").train(train_ds)

self_evaluation = model.self_evaluation()
# In an interactive Python environment, print a rich evaluation report.
self_evaluation

serialize

serialize() -> bytes

set_data_spec

set_data_spec(data_spec: DataSpecification) -> None

set_feature_selection_logs

set_feature_selection_logs(
    value: Optional[FeatureSelectorLogs],
) -> None

set_metadata

set_metadata(metadata: ModelMetadata)

set_node_format

set_node_format(node_format: NodeFormat) -> None

设置节点的序列化格式。

参数

名称 类型 描述 默认值
node_format NodeFormat

保存模型时使用的节点格式。

必需

set_tree

set_tree(tree_idx: int, tree: Tree) -> None

覆盖模型的单个树。

参数

名称 类型 描述 默认值
tree_idx int

树的索引。应在 [0, num_trees()) 范围内。

必需
tree Tree

新树。

必需

task

task() -> Task

to_cpp

to_cpp(key: str = 'my_model') -> str

to_docker

to_docker(path: str, exist_ok: bool = False) -> None

将模型导出为可在云端部署的 Docker 端点。

此函数创建一个包含 Dockerfile、模型和支持文件的目录。

使用示例

import ydf

# Train a model.
model = ydf.RandomForestLearner(label="l").train({
    "f1": np.random.random(size=100),
    "f2": np.random.random(size=100),
    "l": np.random.randint(2, size=100),
})

# Export the model to a Docker endpoint.
model.to_docker(path="/tmp/my_model")

# Print instructions on how to use the model
!cat /tmp/my_model/readme.md

# Test the end-point locally
docker build --platform linux/amd64 -t ydf_predict_image /tmp/my_model
docker run --rm -p 8080:8080 -d ydf_predict_image

# Deploy the model on Google Cloud
gcloud run deploy ydf-predict --source /tmp/my_model

# Check the automatically created utility scripts "test_locally.sh" and
# "deploy_in_google_cloud.sh" for more examples.

参数

名称 类型 描述 默认值
path str

创建 Docker 端点的目录

必需
exist_ok bool

如果为 false(默认值),则如果目录已存在,则失败。如果为 true,则覆盖目录内容(如果存在)。

False

to_jax_function

to_jax_function(
    jit: bool = True,
    apply_activation: bool = True,
    leaves_as_params: bool = False,
    compatibility: Union[str, Compatibility] = "XLA",
) -> JaxModel

to_tensorflow_function

to_tensorflow_function(
    temp_dir: Optional[str] = None,
    can_be_saved: bool = True,
    squeeze_binary_classification: bool = True,
    force: bool = False,
) -> Module

to_tensorflow_saved_model

to_tensorflow_saved_model(
    path: str,
    input_model_signature_fn: Any = None,
    *,
    mode: Literal["keras", "tf"] = "keras",
    feature_dtypes: Dict[str, TFDType] = {},
    servo_api: bool = False,
    feed_example_proto: bool = False,
    pre_processing: Optional[Callable] = None,
    post_processing: Optional[Callable] = None,
    temp_dir: Optional[str] = None,
    tensor_specs: Optional[Dict[str, Any]] = None,
    feature_specs: Optional[Dict[str, Any]] = None,
    force: bool = False
) -> None

update_with_jax_params

update_with_jax_params(params: Dict[str, Any])

variable_importances

variable_importances() -> (
    Dict[str, List[Tuple[float, str]]]
)