使用功能视图训练模型

特征视图使您能够训练模型,并按时间点正确计算特征,同时在推理时自动查找特征。 有关定义功能视图的信息,请参阅 功能视图。

要求

API 方法

create_training_set()

创建功能视图后,下一步是为模型创建训练数据。 为此,请将标记的数据集传递给create_training_set,这会自动确保每个特征值的计算在时间点上准确无误。

例如:

FeatureEngineeringClient.create_training_set(
    df: DataFrame,                                # DataFrame with training data
    features: Optional[List[Feature]],            # List of Feature objects
    label: Union[str, List[str], None],           # Label column name(s)
    exclude_columns: Optional[List[str]] = None,  # Optional: columns to exclude
) -> TrainingSet

调用 TrainingSet.load_df 将原始训练数据与时间点动态计算特征联接。

该 df 参数必须满足以下要求:

  • 必须包含功能定义引用的所有实体列。
  • 必须包含特征定义中引用的时序列列。
  • 必须包含在任何 RequestSource 架构中声明的所有列。 类型将根据已声明的架构进行验证。 不匹配会引发错误(无隐式强制转换)。
  • 应包含一个或多个标签列。
  • 实体列名、时间系列列名称和请求功能列名称集在所有源中必须全局唯一。

时间点正确性:对于聚合和ColumnSelection以表源支持的特征,特征仅使用每行时间戳之前可用的源数据计算,以防止未来数据泄漏到模型训练中。 对于 RequestSource 功能,该值直接从标记的 DataFrame 行获取。

log_model()

使用 MLflow 记录具有特征元数据的模型,以便进行溯源跟踪和推理时自动特征查找。

FeatureEngineeringClient.log_model(
    model,                                    # Trained model object
    artifact_path: str,                       # Path to store model artifact
    flavor: ModuleType,                       # MLflow flavor module (e.g., mlflow.sklearn)
    training_set: TrainingSet,                # TrainingSet used for training
    registered_model_name: Optional[str],     # Optional: register model in Unity Catalog
    extra_pip_requirements: Optional[List[str]] = None, # Optional: Additional serving dependencies
)

该 flavor 参数指定要使用的 MLflow 模型风格 模块,例如 mlflow.sklearn 或 mlflow.xgboost。

使用 TrainingSet 记录的模型会自动跟踪训练中使用的功能世系。 训练集包含 RequestSource 特征时,这些 RequestSource 列将作为所需的输入添加到 MLflow 模型签名中。 这可确保服务终结点的 API 架构反映调用方在推理时必须提供的字段。 有关详细信息,请参阅 使用特征表训练模型。

对于FeatureViewSource,请先注册派生特征及其上游特征,然后再记录模型。 传递依赖所需的请求输入在推理时同样是必需的。 关于模型包的需求,请参见 自定义 UDF 依赖 。

score_batch()

使用自动特征查找执行批量推理

FeatureEngineeringClient.score_batch(
    model_uri: str,                           # URI of logged model
    df: DataFrame,                            # DataFrame with entity keys and timestamps
) -> DataFrame

score_batch 利用随模型存储的特征元数据,自动计算出用于推断的时间点正确的特征,确保与训练保持一致。 有关详细信息,请参阅 使用特征表训练模型。

示例工作流

import mlflow
from databricks.feature_engineering import FeatureEngineeringClient
from sklearn.ensemble import RandomForestClassifier

fe = FeatureEngineeringClient()

# Assume features are registered in UC
# labeled_df should have columns "user_id", "transaction_time", and "is_fraud"

# 1. Create training set using Feature Views
training_set = fe.create_training_set(
    df=labeled_df,
    features=features,
    label="is_fraud",
)

# 2. Load training data with computed features
training_df = training_set.load_df()
X = training_df.drop("is_fraud").toPandas()
y = training_df.select("is_fraud").toPandas().values.ravel()

# 3. Train model
model = RandomForestClassifier().fit(X, y)

# 4. Log model with feature metadata
with mlflow.start_run():
    fe.log_model(
        model=model,
        artifact_path="fraud_model",
        flavor=mlflow.sklearn,
        training_set=training_set,
        registered_model_name="main.ecommerce.fraud_model",
    )

# 5. Batch scoring with automatic feature lookup
# inference_df must contain the same entity and timeseries columns
# used during training. Features are automatically computed.
predictions = fe.score_batch(
    model_uri="models:/main.ecommerce.fraud_model/1",
    df=inference_df,
)
predictions.display()

使用 RequestSource 功能进行训练

当模型需要在推理时提供的数据(例如 API 调用中的交易记录详细信息)时,使用 RequestSource 功能以及表支持的功能。 在训练期间,将从标记的 DataFrame 中提取 RequestSource 列。

from databricks.feature_engineering import FeatureEngineeringClient
from databricks.feature_engineering.entities import (
    DeltaTableSource, Feature, FieldDefinition, RequestSource,
    ScalarDataType, ColumnSelection,
)

fe = FeatureEngineeringClient()

# RequestSource provides transaction data at inference time
request_source = RequestSource(
    schema=[
        FieldDefinition(name="transaction_amount", data_type=ScalarDataType.DOUBLE),
        FieldDefinition(name="vendor_id", data_type=ScalarDataType.STRING),
        FieldDefinition(name="transaction_id", data_type=ScalarDataType.STRING),
        FieldDefinition(name="transaction_time", data_type=ScalarDataType.DATE),
    ]
)

delta_source = DeltaTableSource(
    catalog_name="catalog",
    schema_name="schema",
    table_name="vendor_data",
)

# A column selection feature from the request source (pass-through)
latest_transaction_amount = Feature(
    source=request_source,
    function=ColumnSelection("transaction_amount"),
    name="latest_transaction_amount",
)

# A lookup feature from a delta table
vendor_category = Feature(
    source=delta_source,
    function=ColumnSelection("vendor_category"),
    entity=["vendor_id"],
    timeseries_column="transaction_time",
    name="vendor_category",
)

# labels_df must contain: transaction_id, transaction_time, vendor_id,
# transaction_amount, and the label column.
ts = fe.create_training_set(
    df=labels_df,
    features=[latest_transaction_amount, vendor_category],
    label="is_fraud",
    exclude_columns=["card_id"],
)

import mlflow
from sklearn.ensemble import RandomForestClassifier

with mlflow.start_run():
    training_df = ts.load_df().toPandas()
    X = training_df.drop(columns=["is_fraud"])
    y = training_df["is_fraud"]
    model = RandomForestClassifier().fit(X, y)

    # log_model() adds RequestSource columns to the MLflow model signature
    fe.log_model(
        model=model,
        artifact_path="fraud_model",
        flavor=mlflow.sklearn,
        training_set=ts,
        registered_model_name="catalog.schema.fraud_model",
    )

使用 CustomUDF 进行变换请求值

要转换请求数据,请用 CustomUDF 代替 ColumnSelection。 本例使用了 事务日志对数变换功能:

log_transaction_amount = fe.get_feature(
    full_name="main.ecommerce.log_transaction_amount"
)
request_df = spark.createDataFrame(
    [(0.0, 0), (99.0, 1)],
    "transaction_amount DOUBLE, label INT",
)

transaction_training_set = fe.create_training_set(
    df=request_df,
    features=[log_transaction_amount],
    label="label",
)
transaction_training_set.load_df().show()

结果包括原始的 transaction_amount 和 label 列,以及 log_transaction_amount。 UDF 从每一行读取 transaction_amount。 计算所需的请求列不能在 exclude_columns中列出。

使用管道源特征进行训练

训练和批量评分会从 SdpSource 读取特征,但它们不会运行其流水线。 要基于最新的流水线输出进行训练,请先运行这组特征对应的流水线:

fe.refresh_sdp_source(features=features, wait=True)

使用 FeatureViewSource 特征进行训练

FeatureViewSource 让 CustomUDF 使用其他特征输出,包括派生特征。 将所需的输出传递给 create_training_set。 你不需要列出它们的中间依赖关系。

对于每个输入行,Azure Databricks 解析完整的依赖图:

  1. 根据实体键、时间戳和窗口定义计算由表支持的上游特征。 在可用时,它会使用兼容的离线物化结果。
  2. 从输入 DataFrame 读取所需的请求列,并评估请求支持的功能。
  3. 按依赖顺序评估衍生特征,使每个UDF都能接收其上游结果。

该衍生特征不会引入另一个时间窗口或时点查找。 其上游特征保留了各自的时间语义。 数据框必须包含这些上游依赖所需的实体、时间戳和请求列,即使仅请求最终派生特征也是如此。

例如,使用已注册的边距功能,它结合了cost_sum_7d和revenue_sum_7d:

from databricks.feature_engineering import FeatureEngineeringClient

fe = FeatureEngineeringClient()
margin = fe.get_feature(full_name="main.ecommerce.margin")

# labeled_df contains customer_id, event_time, and label.
training_set = fe.create_training_set(
    df=labeled_df,
    features=[margin],
    label="label",
    exclude_columns=["customer_id", "event_time"],
)
training_df = training_set.load_df()

结果包含 label 和 margin。 收入和成本特征会被计算出来,但不会以额外列的形式返回。 要将营收纳入训练数据,请使用 revenue = fe.get_feature(full_name="main.ecommerce.revenue_sum_7d") 获取它,并传递 features=[margin, revenue]。 这同样适用于多级链:请求最终功能不会返回每个中间输出。

你可以在同一列表中将请求支持、表支持和衍生功能合并。features 要在一个 UDF 中合并这些值,可将请求中的值表示为特征,并在 FeatureViewSource 中将其与由表支持的特征一并引用。

实验时,构造局部 Feature 对象,包括其上游图,但不注册它们。 使用 create_training_set,并可选择配合 label=None,以查看结果。 compute_features 不支持 RequestSource 或 FeatureViewSource。

Note

每个查询最多调用五次Unity Catalog UDF的限制也适用于训练查询。 统计整个依赖关系图所需的 UDF 调用次数,而不仅仅是被请求作为输出的特征。 该查询极限与图的深度极限是分开的。

要在查询中调用超过五个UDF,请使用运行Databricks Runtime 18.1及以上版本的经典计算。 在无服务器计算以及专业版和无服务器 SQL 仓库中,将依赖关系图中的每个 UDF 定义的environment_version设置为6或更高。

自定义UDF依赖

离线计算时,请在 Unity 目录 UDF ENVIRONMENT 的条款中声明 Python 包。 仅在笔记本中安装包并不能将其安装到UDF环境中。

对于模型服务,也要显式地将所需的包传递给 log_model。 无论是UDF ENVIRONMENT 还是包含特征视图的命名特征规范,都不会自动满足这些模型需求。 包括上游 UDF 所需的依赖项以及所请求的特征输出。

使用 transaction_training_set.load_df() 训练 scikit-learn 模型后,使用同一个训练集记录该模型。 包括 NumPy 和兼容的查找软件包:

import mlflow

fe.log_model(
    model=model,
    artifact_path="transaction_model",
    flavor=mlflow.sklearn,
    training_set=transaction_training_set,
    registered_model_name="main.ecommerce.transaction_model",
    extra_pip_requirements=[
        "numpy==1.26.4",
        "databricks-feature-lookup>=1.15.0",
    ],
)

服务端点应自动采用 databricks-feature-lookup 1.15.0 或更高版本,该版本支持对 RequestSource 特征进行按需的 Unity Catalog UDF 计算。 保持 UDF 包版本在离线环境和服务环境中保持一致,以避免计算值差异。 对于没有模型的特征服务端点,请改为在 create_feature_spec 上声明包。 参见添加 Python 依赖。

使用流式功能进行训练

定义 流时,Databricks 管理将流数据写入 Delta 表的引入管道。 create_training_set 从这个摄取表读取数据,并对你标记的数据帧进行时间点联接,就像来自 DeltaTableSource 的批量特征一样。 有关数据引入配置、回填和去重的详细信息,请参见数据引入和回填。

示例:

from databricks.feature_engineering import FeatureEngineeringClient
from databricks.feature_engineering.entities import (
    StreamSource,
    Feature,
    AggregationFunction,
    Sum,
    RollingWindow,
)
from datetime import timedelta

fe = FeatureEngineeringClient()

# Define a streaming feature
stream_source = StreamSource(full_name="my_catalog.my_schema.my_stream")

streaming_feature = Feature(
    name="user_purchase_sum",
    source=stream_source,
    entity=["value.user_id"],
    timeseries_column="value.event_time",
    function=AggregationFunction(
        operator=Sum(input="value.amount"),
        time_window=RollingWindow(window_duration=timedelta(hours=1)),
    ),
)

# Create training set — reads from the ingestion table
# labeled_df must contain "user_id", "event_time", and label columns.
# Entity and timeseries columns use leaf node names (not value. prefixes).
training_set = fe.create_training_set(
    df=labeled_df,
    features=[streaming_feature],
    label="is_fraud",
)

training_df = training_set.load_df()

混合批处理和流式处理功能

批处理和流式处理功能可以一起使用在同一训练集和模型中。 在服务时间,从脱机或联机存储查找批处理特征,并从联机存储中查找流式处理特征。

training_set = fe.create_training_set(
    df=labeled_df,
    features=[batch_feature, streaming_feature],
    label="is_fraud",
)

使用 log_model() 记录的模型会从联机存储中查找特征,并为这两种源类型配置模型签名。

在服务时到达原始模型的内容

功能存储模型包装器会在将列传递到原始模型之前,先筛选这些列:

列类型 到达内部模型?
显式特征输出(ColumnSelection,聚合) 是的
RequestSource 列被声明为特征 是的
实体列(查找键) 否(除非显式声明为特征)
时间序列列 否(除非显式声明为特征)