梯度提升树模型
- 梯度提升树模型
- activation
- add_tree
- analyze
- analyze_prediction
- benchmark
- data_spec
- describe
- distance
- evaluate
- feature_selection_logs
- force_engine
- get_all_trees
- get_tree
- hyperparameter_optimizer_logs
- initial_predictions
- input_feature_names
- input_features
- input_features_col_idxs
- iter_trees
- label
- label_classes
- label_col_idx
- list_compatible_engines
- metadata
- name
- num_trees
- num_trees_per_iteration
- plot_tree
- predict
- predict_class
- predict_leaves
- print_tree
- remove_tree
- save
- self_evaluation
- serialize
- set_data_spec
- set_feature_selection_logs
- set_initial_predictions
- set_metadata
- set_node_format
- set_tree
- task
- to_cpp
- to_docker
- to_jax_function
- to_tensorflow_function
- to_tensorflow_saved_model
- update_with_jax_params
- validation_evaluation
- validation_loss
- variable_importances
GradientBoostedTreesModel ¶
用于预测和检查的梯度提升树模型。
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
benchmark ¶
benchmark(
ds: InputDataset,
benchmark_duration: float = 3,
warmup_duration: float = 1,
batch_size: int = 100,
num_threads: Optional[int] = None,
) -> BenchmarkInferenceCCResult
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
|
可选[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
get_tree ¶
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
|
可选[int]
|
绘制的最大树深度。设置为 None 表示完整深度。 |
None
|
options
|
可选[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
|
可选[int]
|
运行模型使用的线程数。 |
None
|
返回值
类型 | 描述 |
---|---|
ndarray
|
每个样本最有可能的预测类别。 |
predict_leaves ¶
获取每棵树中活动叶节点的索引。
活动叶节点是在推理过程中接收样本的叶节点。
返回值 "leaves[i,j]" 是第 i 个样本和第 j 棵树的活动叶节点索引。叶节点按深度优先遍历进行索引,其中先访问负子节点再访问正子节点。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
data
|
InputDataset
|
数据集。 |
必需 |
返回值
类型 | 描述 |
---|---|
ndarray
|
模型中每棵树的活动叶节点索引。 |
print_tree ¶
在终端中打印树。
使用示例
# 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
|
可选[int]
|
绘制的最大树深度。设置为 None 表示完整深度。 |
6
|
file
|
Any
|
打印树的位置。默认情况下,打印到终端标准输出。 |
stdout
|
self_evaluation ¶
self_evaluation() -> Optional[Evaluation]
返回模型的自评估。
对于梯度提升树模型,自评估是在验证数据集上的评估。请注意,如果未明确给出验证数据集,则会自动提取。如果停用验证数据集,则不计算自评估。
不同的模型使用不同的方法进行自评估。值得注意的是,随机森林使用最后的袋外(Out-Of-Bag)评估。因此,不同模型类型的自评估结果不可比较。
如果未计算自评估,则返回 None。
使用示例
set_feature_selection_logs ¶
set_feature_selection_logs(
value: Optional[FeatureSelectorLogs],
) -> None
set_initial_predictions ¶
设置模型的初始预测(即模型偏差)。
set_node_format ¶
set_node_format(node_format: NodeFormat) -> None
set_tree ¶
to_docker ¶
将模型导出为可在云端部署的 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