RandomForestLearner
RandomForestLearner ¶
RandomForestLearner(
label: str,
task: Task = CLASSIFICATION,
*,
weights: Optional[str] = None,
ranking_group: Optional[str] = None,
uplift_treatment: Optional[str] = None,
features: Optional[ColumnDefs] = None,
include_all_columns: bool = False,
max_vocab_count: int = 2000,
min_vocab_frequency: int = 5,
discretize_numerical_columns: bool = False,
num_discretized_numerical_bins: int = 255,
max_num_scanned_rows_to_infer_semantic: int = 100000,
max_num_scanned_rows_to_compute_statistics: int = 100000,
data_spec: Optional[DataSpecification] = None,
extra_training_config: Optional[TrainingConfig] = None,
adapt_bootstrap_size_ratio_for_maximum_training_duration: bool = False,
allow_na_conditions: bool = False,
bootstrap_size_ratio: float = 1.0,
bootstrap_training_dataset: bool = True,
categorical_algorithm: str = "CART",
categorical_set_split_greedy_sampling: float = 0.1,
categorical_set_split_max_num_items: int = -1,
categorical_set_split_min_item_frequency: int = 1,
compute_oob_performances: bool = True,
compute_oob_variable_importances: bool = False,
growing_strategy: str = "LOCAL",
honest: bool = False,
honest_fixed_separation: bool = False,
honest_ratio_leaf_examples: float = 0.5,
in_split_min_examples_check: bool = True,
keep_non_leaf_label_distribution: bool = True,
max_depth: int = 16,
max_num_nodes: Optional[int] = None,
maximum_model_size_in_memory_in_bytes: float = -1.0,
maximum_training_duration_seconds: float = -1.0,
mhld_oblique_max_num_attributes: Optional[int] = None,
mhld_oblique_sample_attributes: Optional[bool] = None,
min_examples: int = 5,
missing_value_policy: str = "GLOBAL_IMPUTATION",
num_candidate_attributes: Optional[int] = 0,
num_candidate_attributes_ratio: Optional[float] = None,
num_oob_variable_importances_permutations: int = 1,
num_trees: int = 300,
numerical_vector_sequence_num_examples: int = 1000,
numerical_vector_sequence_num_random_anchors: int = 100,
pure_serving_model: bool = False,
random_seed: int = 123456,
sampling_with_replacement: bool = True,
sorting_strategy: str = "PRESORT",
sparse_oblique_max_num_features: Optional[int] = None,
sparse_oblique_max_num_projections: Optional[
int
] = None,
sparse_oblique_normalization: Optional[str] = None,
sparse_oblique_num_projections_exponent: Optional[
float
] = None,
sparse_oblique_projection_density_factor: Optional[
float
] = None,
sparse_oblique_weights: Optional[str] = None,
sparse_oblique_weights_integer_maximum: Optional[
int
] = None,
sparse_oblique_weights_integer_minimum: Optional[
int
] = None,
sparse_oblique_weights_power_of_two_max_exponent: Optional[
int
] = None,
sparse_oblique_weights_power_of_two_min_exponent: Optional[
int
] = None,
split_axis: str = "AXIS_ALIGNED",
uplift_min_examples_in_treatment: int = 5,
uplift_split_score: str = "KULLBACK_LEIBLER",
winner_take_all: bool = True,
working_dir: Optional[str] = None,
num_threads: Optional[int] = None,
tuner: Optional[AbstractTuner] = None,
feature_selector: Optional[
AbstractFeatureSelector
] = None,
explicit_args: Optional[Set[str]] = None
)
基类: GenericCCLearner
随机森林学习算法。
一个 随机森林 是一个包含多个深度 CART 决策树的集合,这些决策树独立训练且不进行剪枝。每棵树都在原始训练数据集的一个随机子集上训练(有放回抽样)。
该算法的独特之处在于它对过拟合具有鲁棒性,即使在极端情况下也是如此,例如特征数量多于训练样本时。
它可能是决策森林训练算法中最著名的。
使用示例
import ydf
import pandas as pd
dataset = pd.read_csv("project/dataset.csv")
model = ydf.RandomForestLearner().train(dataset)
print(model.describe())
超参数已配置为对典型数据集给出合理的结果。超参数也可以手动修改(参见下面的描述),或者通过应用 RandomForestLearner.hyperparameter_templates()
提供的超参数模板进行修改(详细信息请参阅此函数的文档)。
属性
名称 | 类型 | 描述 |
---|---|---|
label |
数据集的标签。标签列不应在 |
|
task |
要解决的任务(例如 Task.CLASSIFICATION、Task.REGRESSION、Task.RANKING、Task.CATEGORICAL_UPLIFT、Task.NUMERICAL_UPLIFT)。 |
|
weights |
标识每个示例权重的特征名称。如果未指定权重,则假定单位权重。权重列不应在 |
|
ranking_group |
仅用于 |
|
uplift_treatment |
仅用于 |
|
features |
如果为 None,则所有列都用作特征。特征的语义自动确定。否则,如果 include_all_columns=False(默认),则仅导入 |
|
include_all_columns |
请参阅 |
|
max_vocab_count |
存储为字符串的 CATEGORICAL 和 CATEGORICAL_SET 列的最大词汇量大小。如果存在更多唯一值,则仅保留最频繁的值,其余值视为词汇外(out-of-vocabulary)。 |
|
min_vocab_frequency |
CATEGORICAL 和 CATEGORICAL_SET 列中某个值的最小出现次数。出现次数少于 |
|
discretize_numerical_columns |
如果为 true,则在训练前对所有数值列进行离散化。离散化后的数值列训练速度更快,但可能对模型质量产生负面影响。使用 |
|
num_discretized_numerical_bins |
对数值列进行离散化时使用的 bin 数量。 |
|
max_num_scanned_rows_to_infer_semantic |
如果未明确指定,扫描多少行来推断列的语义。仅在从文件读取时使用,内存中的数据集总是完整读取。将其设置为较小的值会加快数据集读取速度,但可能导致列语义不正确。设置为 -1 以扫描整个数据集。 |
|
max_num_scanned_rows_to_compute_statistics |
计算列统计信息时扫描的行数。仅在从文件读取时使用,内存中的数据集总是完整读取。列的统计信息包括分类特征的字典和数值特征的均值/最小值/最大值。将其设置为较小的值会加快数据集读取速度,但会扭曲数据规范中的统计信息,从而可能损害模型质量(例如,如果分类特征的一个重要类别被视为 OOV)。设置为 -1 以扫描整个数据集。 |
|
data_spec |
要使用的数据规范(高级)。如果提供了数据规范,则 |
|
extra_training_config |
训练配置 proto(高级)。如果设置,此训练配置 proto 将与学习器隐式定义的配置合并。可用于设置未作为构造函数参数公开的内部或高级参数。extra_training_config 中的参数优先级高于构造函数参数。 |
|
adapt_bootstrap_size_ratio_for_maximum_training_duration |
控制如何应用最大训练时长(如果已设置)。如果为 false,则在时间用尽时停止训练。如果为 true,则调整用于训练每棵树的抽样数据集大小,以使 |
|
allow_na_conditions |
如果为 true,树训练会评估 |
|
bootstrap_size_ratio |
用于训练每棵树的示例数量;表示为训练数据集大小的比例。默认值:1.0。 |
|
bootstrap_training_dataset |
如果为 true(默认值),每棵树都在从原始数据集有放回抽样的单独数据集上训练。如果为 false,所有树都在整个相同数据集上训练。如果 bootstrap_training_dataset:false,则 OOB 指标不可用。bootstrap_training_dataset=false 用于“极端随机树”(https://link.springer.com/content/pdf/10.1007%2Fs10994-006-6226-1.pdf)。默认值:True。 |
|
categorical_algorithm |
如何在分类属性上学习分裂。- |
|
categorical_set_split_greedy_sampling |
用于分类集分裂,例如文本。某个分类值成为正集候选的概率。采样在每个节点应用一次(即不是在贪婪优化的每一步)。默认值:0.1。 |
|
categorical_set_split_max_num_items |
用于分类集分裂,例如文本。最大项目数(采样之前)。如果项目数更多,则忽略最不频繁的项目。更改此值类似于在加载数据集之前更改“max_vocab_count”,但有一个例外:使用 |
|
categorical_set_split_min_item_frequency |
用于分类集分裂,例如文本。考虑一个项目的最小出现次数。默认值:1。 |
|
compute_oob_performances |
如果为 true,则计算袋外评估(Out-of-bag evaluation),该评估可在摘要和模型检查器中查看。此评估是交叉验证评估的一种廉价替代方案。默认值:True。 |
|
compute_oob_variable_importances |
如果为 true,则计算袋外特征重要性,该重要性可在摘要和模型检查器中查看。请注意,OOB 特征重要性的计算可能很昂贵。默认值:False。 |
|
growing_strategy |
如何生长树。- |
|
honest |
在 honest 树中,使用不同的训练示例来推断结构和叶子值。这种正则化技术用示例来换取偏差估计。它可能会增加或降低模型质量。请参阅 Athey 等人的“Generalized Random Forests”。在这篇论文中,Honest 树是使用随机森林算法进行无放回抽样训练的。默认值:False。 |
|
honest_fixed_separation |
仅用于 honest 树,即 honest=true。如果为 true,则为每棵树生成新的随机划分。如果为 false,则所有树使用相同的划分(例如,在包含多棵树的梯度提升树中)。默认值:False。 |
|
honest_ratio_leaf_examples |
仅用于 honest 树,即 honest=true。用于设置叶子值的示例比例。默认值:0.5。 |
|
in_split_min_examples_check |
是否在分裂搜索中检查 |
|
keep_non_leaf_label_distribution |
是否保留非叶子节点的节点值(即训练示例标签的分布)。此信息在服务期间不使用,但可用于模型解释和超参数调优。这会占用大量空间,有时占模型大小的一半。默认值:True。 |
|
max_depth |
树的最大深度。 |
|
max_num_nodes |
树中的最大节点数。设置为 -1 以禁用此限制。仅适用于 |
|
maximum_model_size_in_memory_in_bytes |
限制模型存储在内存中的大小。不同的算法可能以不同的方式强制执行此限制。请注意,当模型编译为推理引擎时,推理引擎的大小通常远小于原始模型。默认值:-1.0。 |
|
maximum_training_duration_seconds |
以秒为单位表示的模型最大训练时长。每个学习算法可以根据需要自由使用此参数。启用最大训练时长会使模型训练变得不确定。默认值:-1.0。 |
|
mhld_oblique_max_num_attributes |
对于 MHLD 斜分裂,即 |
|
mhld_oblique_sample_attributes |
对于 MHLD 斜分裂,即 |
|
min_examples |
节点中的最小示例数。默认值:5。 |
|
missing_value_policy |
处理缺失属性值的方法。- |
|
num_candidate_attributes |
为每个节点测试的唯一有效属性数量。如果一个属性至少有一个有效分裂,则它是有效的。如果 |
|
num_candidate_attributes_ratio |
在每个节点测试的属性比例。如果设置,则等同于 |
|
num_oob_variable_importances_permutations |
重新洗牌数据集以计算置换变量重要性的次数。增加此值会增加训练时间(如果“compute_oob_variable_importances:true”)以及 oob 变量重要性指标的稳定性。默认值:1。 |
|
num_trees |
个体决策树的数量。增加树的数量可以提高模型质量,但会牺牲模型大小、训练速度和推理延迟。默认值:300。 |
|
numerical_vector_sequence_num_examples |
对于具有 NUMERICAL_VECTOR_SEQUENCE 特征的数据集(即固定大小数值向量序列)。用于查找分裂的最大示例数。较大的值可以提高模型质量,但训练时间更长。默认值:1000。 |
|
numerical_vector_sequence_num_random_anchors |
对于具有 NUMERICAL_VECTOR_SEQUENCE 特征的数据集(即固定大小数值向量序列)。随机生成的锚点值的数量。较大的值可以提高模型质量,但训练时间更长。默认值:100。 |
|
pure_serving_model |
清除模型中任何服务模型不需要的信息。这包括调试、模型解释和其他元数据。序列化模型的大小可以显著减小(减小 50% 是常见的)。此参数对模型服务的质量、服务速度或 RAM 使用没有影响。默认值:False。 |
|
random_seed |
模型训练的随机种子。学习器应通过随机种子实现确定性。默认值:123456。 |
|
sampling_with_replacement |
如果为 true,则有放回地对训练示例进行抽样。如果为 false,则无放回地对训练示例进行抽样。仅在“bootstrap_training_dataset=true”时使用。如果为 false(无放回抽样),并且“bootstrap_size_ratio=1”(默认值),则所有示例都用于训练所有树(您可能不希望这样)。默认值:True。 |
|
sorting_strategy |
如何对数值特征进行排序以查找分裂 - AUTO:在 IN_NODE、FORCE_PRESORT 和 LAYER 中选择最有效的方法。- IN_NODE:在节点中使用特征之前进行排序。此解决方案速度慢但消耗内存少。- FORCE_PRESORT:在训练开始时预先对特征进行排序。此解决方案速度快但消耗内存比 IN_NODE 多得多。- PRESORT:自动在 FORCE_PRESORT 和 IN_NODE 之间选择。默认值:“PRESORT”。 |
|
sparse_oblique_max_num_features |
对于稀疏斜分裂,即 |
|
sparse_oblique_max_num_projections |
对于稀疏斜分裂,即 |
|
sparse_oblique_normalization |
对于稀疏斜分裂,即 |
|
sparse_oblique_num_projections_exponent |
对于稀疏斜分裂,即 |
|
sparse_oblique_projection_density_factor |
投影密度,表示为特征数量的指数。对于每个投影独立地,每个特征有“projection_density_factor / num_features”的概率被考虑在投影中。论文“Sparse Projection Oblique Random Forests”(Tomita 等人,2020 年)将此参数称为 |
|
sparse_oblique_weights |
对于稀疏斜分裂,即 可能的值:- |
|
sparse_oblique_weights_integer_maximum |
对于稀疏斜分裂,即 |
|
sparse_oblique_weights_integer_minimum |
对于稀疏斜分裂,即 |
|
sparse_oblique_weights_power_of_two_max_exponent |
对于稀疏斜分裂,即 |
|
sparse_oblique_weights_power_of_two_min_exponent |
对于稀疏斜分裂,即 |
|
split_axis |
数值特征考虑的分裂结构。- |
|
uplift_min_examples_in_treatment |
仅用于提升模型。节点中每个干预的最小示例数。默认值:5。 |
|
uplift_split_score |
仅用于提升模型。分裂器分数,即分裂器优化的分数。这些分数由 Rzepakowski 等人在“Decision trees for uplift modeling with single and multiple treatments”中引入。符号: |
|
winner_take_all |
控制分类树如何投票。如果为 true,每棵树投票支持一个类别。如果为 false,每棵树投票支持一个类别分布。通常 prefer winner_take_all_inference=false。默认值:True。 |
|
working_dir |
可供学习算法存储中间计算结果的目录路径。根据学习算法和参数的不同,working_dir 可能是可选的、必需的或被忽略的。例如,分布式训练算法总是需要“working_dir”,并且如果提供,梯度提升树和超参数调优器会将工件导出到“working_dir”。 |
|
num_threads |
用于训练模型的线程数。不同的学习算法以不同的方式使用多线程,效率也不同。如果为 |
|
tuner |
如果设置,则使用提供的调优器自动选择最佳超参数。使用分布式训练时,调优是分布式的。 |
|
feature_selector |
如果设置,则使用指定的特征选择器自动选择模型的输入特征,通过自动化特征选择。 |
|
explicit_args |
内部使用的辅助参数。如果用户显式提供,则抛出错误。 |
hyperparameters property
¶
此学习器超参数的一个(可变)字典。
此对象可用于在创建学习器后检查或修改超参数。在构建学习器后修改超参数适用于一些高级用例。由于此方法绕过对给定超参数集的某些可行性检查,因此通常最好为每个模型重新创建学习器。当前超参数集可以使用 validate_hyperparameters()
手动验证。
cross_validation ¶
cross_validation(
ds: InputDataset,
folds: int = 10,
bootstrapping: Union[bool, int] = False,
parallel_evaluations: int = 1,
) -> Evaluation
hyperparameter_templates classmethod
¶
此学习器的超参数模板。
超参数模板是一组预定义的超参数,以便轻松访问学习器的不同变体。每个模板都映射到一组超参数,可以直接应用于学习器。
使用示例
templates = ydf.RandomForestLearner.hyperparameter_templates()
better_defaultv1 = templates["better_defaultv1"]
# Print a description of the template
print(better_defaultv1.description)
# Apply the template's settings on the learner.
learner = ydf.RandomForestLearner(label, **better_defaultv1)
返回值
类型 | 描述 |
---|---|
Dict[str, HyperparameterTemplate]
|
可用模板的字典 |
train ¶
train(
ds: InputDataset,
valid: Optional[InputDataset] = None,
verbose: Optional[Union[int, bool]] = None,
) -> RandomForestModel
在给定数据集上训练模型。
数据集读取选项在学习器上给出。有关 YDF 中数据集读取的更多信息,请参阅学习器或 ydf.create_vertical_dataset() 的文档。
使用示例
import ydf
import pandas as pd
train_ds = pd.read_csv(...)
learner = ydf.RandomForestLearner(label="label")
model = learner.train(train_ds)
print(model.summary())
如果训练被中断(例如,通过中断 Colab 中的单元格执行),模型将恢复到中断发生时的状态。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
ds
|
InputDataset
|
训练数据集。 |
必需 |
valid
|
Optional[InputDataset]
|
可选验证数据集。某些学习器(例如随机森林)不需要验证数据集。某些学习器(例如梯度提升树)如果在未提供验证数据集时会自动从训练数据集中提取验证数据集。 |
None
|
verbose
|
Optional[Union[int, bool]]
|
训练期间的详细级别。如果为 None,则使用 |
None
|
返回值
类型 | 描述 |
---|---|
RandomForestModel
|
训练好的模型。 |