IsolationForestModel
- IsolationForestModel
- add_tree
- analyze
- analyze_prediction
- benchmark
- data_spec
- describe
- distance
- evaluate
- feature_selection_logs
- force_engine
- get_all_trees
- get_tree
- hyperparameter_optimizer_logs
- input_feature_names
- input_features
- input_features_col_idxs
- iter_trees
- label
- label_classes
- label_col_idx
- list_compatible_engines
- metadata
- name
- num_examples_per_tree
- num_trees
- plot_tree
- predict
- predict_class
- predict_leaves
- print_tree
- remove_tree
- save
- self_evaluation
- serialize
- set_data_spec
- set_feature_selection_logs
- 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
- variable_importances
IsolationForestModel ¶
用于预测和检查的 Isolation Forest 模型。
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
|
Optional[InputDataset]
|
数据集。可以是列表或 numpy 数组值的字典、Pandas DataFrame 或 VerticalDataset。 |
无
|
返回值
类型 | 描述 |
---|---|
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
|
Optional[int]
|
绘图的最大树深度。设置为 None 表示完整深度。 |
无
|
options
|
Optional[PlotOptions]
|
高级绘图选项。设置为 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]
|
运行模型使用的线程数。 |
无
|
返回值
类型 | 描述 |
---|---|
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
|
Optional[int]
|
绘图的最大树深度。设置为 None 表示完整深度。 |
6
|
file
|
Any
|
打印树的位置。默认情况下,打印到终端标准输出。 |
stdout
|
self_evaluation ¶
返回模型的自评估结果。
不同的模型使用不同的方法进行自评估。值得注意的是,随机森林使用 OOB 评估,而梯度提升树使用验证数据集上的评估。因此,不同模型类型之间的自评估结果不可比较。
使用示例
set_feature_selection_logs ¶
set_feature_selection_logs(
value: Optional[FeatureSelectorLogs],
) -> None
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