12-04 更新 实时
首页/ 技术栈/ 正文

使用 Genie Code 构建端到端 ML 工作流

技术栈 来源:Databricks Blog 2026-12-04 03:20 2 阅读 机器翻译
使用 Genie Code 构建端到端 ML 工作流

生产级机器学习不仅仅需要模型训练。团队还必须管理特征、部署、自动化和监控。

Genie Code 帮助开发者在 Databricks 上构建机器学习工作流,涵盖从数据准备、模型调优到模型服务和 MLOps。

通过一个贷款违约示例,了解如何使用 Genie Code 提示词,从最初的 notebook 走到一个已部署且受监控的工作流。

构建机器学习模型只是将机器学习投入生产的一部分。数据科学家还需要进行特征工程、跟踪实验、部署模型、自动化流水线,并长期监控性能。管理这些相互关联的工作流需要大量的工程投入,往往还要跨多个工具进行。

Genie Code 帮助数据科学家使用自然语言贯穿机器学习生命周期开展工作。借助对 Databricks 工具和工作区上下文的访问,它可以帮助开发者探索数据、构建模型、识别潜在问题,并搭建部署和运行这些模型所需的基础设施。开发者无需手动连接每个组件,而是可以引导 Genie Code 完成工作流,审查其决策,并在过程中不断迭代。

在这篇文章中,我们将使用一个贷款违约预测模型来演示这一过程。从原始数据集开始,我们将使用 Genie Code 经历三个阶段:crawl(构建一个可运行的模型)、walk(改进并部署它)和 run(自动化重新训练并监控模型健康状况)。在此过程中,你会看到 Genie Code 不仅是代码生成器,还是建模和架构选择的设计伙伴。

Genie Code 将 AI 辅助开发引入 Databricks Platform,把编码能力与对组织数据和业务上下文的理解相结合。由 Genie Ontology 驱动,它可以使用来自 Unity Catalog 和工作区的上下文,理解数据含义、资产之间如何关联以及已经构建了什么。这有助于 Genie Code 基于你的具体环境给出更有依据的建议,而不是孤立地生成代码。

Genie Code 还适用于 Databricks ML 能力,包括 MLflow、Feature Store 和 Model Serving。这使开发者可以在从实验走向部署和监控的过程中基于已有工作继续构建,而不是把每个阶段当作独立项目。

在整个过程中,数据科学家始终掌控局面。他们可以检查生成的代码、验证决策,并随着需求变化优化工作流。

我们将通过“爬行、行走、奔跑”的渐进式路径来实现这一点:

爬行——从原始数据得到一个可用的模型。使用 Genie Code 探索数据集、识别潜在数据泄漏、进行特征工程、训练模型,并用 MLflow 跟踪实验。

行走——将实验转化为可部署的 ML 解决方案。添加可复用的 Feature Views,调优模型性能,生成解释,并通过 Model Serving 部署模型。

奔跑——自动化并监控工作流。使用 Genie Code 配置定时重新训练、部署工作流和监控,为生产级 MLOps 奠定基础。

我们使用的是每个 Databricks 工作区都自带的原始 Lending Club 贷款数据(位于 samples/databricks/datasets/lending-club-loan-stats)。Lending Club 是一个消费者贷款市场平台。我们将用它的样本贷款数据训练一个二分类器,用来预测借款人是否会违约。该数据集包含 145 列,其中有些信息如果在没有谨慎进行特征选择的情况下使用,可能会引入目标泄漏。

构建之前:先探查已有内容

在编写一行建模代码之前,最好先花点时间审视一下工作区里已经有什么。Genie Code 可以访问 Unity Catalog、你现有的笔记本,以及平台中可信资产的完整图本体,这意味着它能告诉你,针对类似你的问题已经构建了什么。像下面这样简单的提示词就是很好的起点:

我想构建一个分类器来预测贷款违约。有没有可复用的现有特征或表,有没有已经清洗或增强贷款数据的流水线,或者有没有解决类似问题的已注册模型或笔记本?

在更大规模的项目中,花时间做这种初步探查可以节省数天的工作。Genie Code 可以找出你可以复用而不必重建的 Feature Views、已经在类似数据上运行的增强流水线,甚至已经解决类似问题的模型。在本演练中,我们将从零开始构建工作流,而不是复用现有资产,但在处理你自己的数据时,检查已经有哪些可用内容是有用的第一步。

Crawl:从原始数据到可用模型

我在 /Volumes/samples/databricks/datasets/lending-club-loan-stats/ 中有原始的 Lending Club 贷款数据。我想构建一个二分类器,预测借款人是否会违约。你能探索数据,根据 loan status 字段构造一个合适的标签,清理掉在预测时不可用或有泄漏的特征,然后拟合几个模型以找出最佳模型吗?将所有内容记录到 MLflow,以便我比较各次运行。写入任何表时都使用 insert_catalog_here。

就这样。别忘了插入你的 catalog。我会逐一讲解它生成的内容。如果你想跟着代码一起操作,我把所有资源和提示词都放在这里的一个 repo 中。

标签工程与特征清理

下表显示了样本中的六种贷款状态:

贷款处于活跃状态,结果未知

近期有应付款,结果可能朝任一方向发展

如果你直接把分类器套用到全部 130k 行数据上,你就犯了一个关键错误:“Current” 贷款尚未有最终结果。你不知道它们是否会违约,因此它们实际上就是未标注数据。

Genie Code 立刻发现了这一点。它排除了 “Current” 和 “In Grace Period” 贷款(结果不明确),然后为剩余列创建了映射。这说明了 Genie Code 如何将针对具体问题的推理应用于标签工程,而不是依赖预定义的建模步骤。

值得指出的是,对于这样的贷款数据,你通常会按时间划分训练集和测试集,以免把未来信息泄漏到过去。由于这个样本是单季度的发放贷款,没有足够的时间窗口让时间划分有多大意义,所以我们改为随机划分。Genie Code 很擅长揭示这类洞察,并能指出权衡取舍,而不是盲目行动。

对于面前众多潜在特征,它也做出了同样合理的决策。在 145 个原始列中,Genie Code 识别并移除了:

发放后的还款数据(total_pymnt、recoveries、last_pymnt_d 等)——这些数据之所以存在,是因为发生了还款。在申请时,它们并不存在。

标识符和无关文本(id、member_id、url)——对表格 ML 没有预测价值。

Hardship 与 settlement 列——只有在贷款变坏后才会填充。没有比这些更能说明目标泄漏的例子了。

联合申请字段——对于个人申请大多为空。

这样的领域推理有助于区分可用模型和误导性模型。Genie Code 帮助在训练开始前识别出可能损害结果的建模决策,包括未解决的标签和目标泄漏。

Genie Code 构建了带 ColumnTransformer 的 sklearn Pipelines:

树模型对类别特征使用 OrdinalEncoder(树按值分裂,顺序无关紧要)

线性模型使用 OneHotEncoder + StandardScaler(线性模型需要数值分离)

空值处理由 SimpleImputer 在管道内完成

我们可以追溯 Genie Code 在我们对话中所做的每一件事。

与任何 AI 生成的代码一样,执行并验证结果非常重要。你还可以让 Genie Code 解释其决策或修改其方法。在这里,Genie Code 遵循既定的 Databricks 开发模式,训练了三个模型并将结果记录到 MLflow,包括混淆矩阵和 ROC 曲线。

演练:调优、解释和部署

我们在单个 notebook 中训练了三个模型。接下来,我们将添加迈向部署所需的特征管理、调优、可解释性和服务能力。

训练与推理之间一致的转换(无训练/服务偏差)

恰当的超参数调优(以训练更好的模型)

可解释性(金融服务领域的监管机构通常要求具备可解释性)

一个通过 REST 提供预测服务的在线端点

提示词 1:调优并解释模型

与 Genie Code 协作是一个迭代过程。对于复杂任务,通常把工作拆分成更小的步骤、检查输出并细化指令会更有帮助。这里,我们将把多个任务合并到一个提示词中,以演示这一工作流程:

我在 src/crawl/ 中构建了一个基础的贷款违约分类器,但它需要达到生产级质量。我想把下一阶段拆分成 src/walk/ 中的三个 notebook:

特征工程:设置一个 Feature View,让我的训练和推理转换保持同步。

训练:对 crawl 中得出的最佳模型类型运行超参数搜索,并将所有试验记录到 MLflow。

原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。

查看英文原文(Build end-to-end ML workflows with Genie Code)

Production ML requires more than model training. Teams must also manage features, deployment, automation and monitoring.

Genie Code helps developers build ML workflows across Databricks, from data preparation and model tuning to serving and MLOps.

Follow a loan default example from an initial notebook to a deployed, monitored workflow using Genie Code prompts.

Building a machine learning model is only one part of putting ML into production. Data scientists also need to engineer features, track experiments, deploy models, automate pipelines and monitor performance over time. Managing these interconnected workflows requires significant engineering effort, often across multiple tools.

Genie Code helps data scientists work across the ML lifecycle using natural language. With access to Databricks tools and workspace context, it can help developers explore data, build models, identify potential issues and set up the infrastructure needed to deploy and operate them. Instead of manually connecting every component, developers can guide Genie Code through the workflow, review its decisions and iterate as they go.

In this post, we'll demonstrate that process using a loan default prediction model. Starting with a raw dataset, we'll use Genie Code to move through three stages: crawl (build a working model), walk (improve and deploy it) and run (automate retraining and monitor model health). Along the way, you'll see Genie Code act as a design partner for modeling and architecture choices, not just a code generator.

Genie Code brings AI-assisted development to the Databricks Platform, combining coding capabilities with an understanding of your organization's data and business context. Powered by Genie Ontology, it can use context from Unity Catalog and your workspace to understand what data means, how assets relate and what's already been built. This helps Genie Code make more informed recommendations based on your specific environment rather than generating code in isolation.

Genie Code also works across Databricks ML capabilities, including MLflow, Feature Store and Model Serving. This allows developers to build on their work as they move from experimentation to deployment and monitoring, rather than treating each stage as a separate project.

Throughout the process, data scientists stay in control. They can inspect generated code, validate decisions and refine the workflow as requirements evolve.

We'll do this with a crawl, walk, run progression:

Crawl — Get from raw data to a working model. Use Genie Code to explore the dataset, identify potential leakage, engineer features, train models and track experiments with MLflow.

Walk — Turn an experiment into a deployable ML solution. Add reusable Feature Views, tune model performance, generate explanations and deploy the model through Model Serving.

Run — Automate and monitor the workflow. Use Genie Code to configure scheduled retraining, deployment workflows and monitoring, establishing the foundation for production MLOps.

We're using raw Lending Club loan data that ships with every Databricks workspace (in samples/databricks/datasets/lending-club-loan-stats). Lending Club is a consumer lending marketplace. We'll use its sample loan data to train a binary classifier that predicts whether a borrower will default. The dataset contains 145 columns, including information that could introduce target leakage if used without careful feature selection.

Before you build: scout what already exists

Before writing a line of modeling code, it’s a good idea to take a second and survey what’s already in your workspace. Genie Code has access to Unity Catalog, your existing notebooks, and an entire graph ontology of trusted assets in the platform, which means it can tell you what's already been built for a problem like yours. A simple prompt like this is a great way to start:

I want to build a classifier to predict loan defaults. Are there existing features or tables I could reuse, any pipelines that already clean or augment lending data, or any registered models or notebooks that tackle a similar problem? 

In larger-scale projects, taking the time to do this initial exploration can save days of work. Genie Code can surface Feature Views you can reuse instead of rebuilding, augmentation pipelines already running on similar data, and even models that already solve a comparable problem. For this walkthrough, we'll build the workflow from scratch rather than reuse existing assets, but checking what's already available is a useful first step when working with your own data.

Crawl: From raw data to a working model

I have raw Lending Club loan data in /Volumes/samples/databricks/datasets/lending-club-loan-stats/. I want to build a binary classifier that predicts whether a borrower will default. Can you explore the data, engineer a proper label from the loan status field, clean up features that wouldn't be available at prediction time or are leaky, and then fit a few models to find the best one? Log everything to MLflow so I can compare runs. Use insert_catalog_here for any tables you write.

That's it. Don’t forget to insert your catalog. I’ll walk through what it produced. If you’d like to follow along with the code, I put all of the assets and prompts in a repo here.

Label engineering and feature cleanup

The table below shows six loan statuses in the sample:

Loan is active, outcome unknown

Payment due recently, could go either way

If you just slap a classifier on all 130k rows, you're making a critical mistake: "Current" loans haven't been resolved yet. You don't know if they'll default, so they are effectively unlabeled data.

Genie Code caught this immediately. It excluded "Current" and "In Grace Period" loans (ambiguous), and then created a mapping for the remaining columns. This illustrates how Genie Code can apply problem-specific reasoning to label engineering rather than relying on predefined modeling steps.

It is worth pointing out that with loan data like this, you would normally split train and test by time so you don't leak the future into the past. Since this sample is a single quarter of originations, there isn't enough of a window for a temporal split to mean much, and we split randomly instead. Genie Code is great at surfacing insights like this and can flag trade-offs instead of blindly acting.

It made similarly reasonable decisions for the many potential features in front of it. Of the 145 original columns, Genie Code identified and removed:

Post-origination payment data (total_pymnt, recoveries, last_pymnt_d, etc.) - These exist because payments were made. At application time, they wouldn't exist.

Identifiers and unrelated text (id, member_id, url) - No predictive value for tabular ML.

Hardship and settlement columns - Only populated after a loan goes bad. No better example of target leakage than these.

Joint application fields - Mostly null for individual applications.

Domain reasoning like this helps distinguish a usable model from a misleading one. Genie Code helped identify modeling decisions that could have undermined the results before training began, including unresolved labels and target leakage.

Genie Code built sklearn Pipelines with ColumnTransformer:

Tree models get OrdinalEncoder for categoricals (trees split on values, ordering doesn't matter)

Linear models get OneHotEncoder + StandardScaler (linear models need the numeric separation)

Null handling lives inside the pipeline via SimpleImputer

We can trace everything Genie Code did in our conversation.

As with any AI-generated code, it's important to execute and validate the results. You can also ask Genie Code to explain its decisions or revise its approach. Here, Genie Code trained three models and logged their results to MLflow, including confusion matrices and ROC curves, following established Databricks development patterns.

Walk: Tune, explain, and deploy

We've trained three models in a single notebook. Next, we'll add the feature management, tuning, interpretability and serving capabilities needed to move toward deployment.

Consistent transformations between training and inference (no train/serve skew)

Proper hyperparameter tuning (to train a better model)

Explainability (often required by regulators in financial services)

A live endpoint that serves predictions over REST

Prompt 1: Tune and explain the model

Working with Genie Code is an iterative process. For complex tasks, it often helps to break the work into smaller steps, review the output and refine your instructions. Here, we'll combine several tasks into one prompt to demonstrate the workflow: 

I built a basic loan default classifier in src/crawl/, but it needs to be production-quality. I want to split the next stage into three notebooks in src/walk/:

Feature engineering: set up a Feature View so my training and inference transformations stay in sync.

Training: run a hyperparameter search over the best model type from crawl, log all trials to MLflow. 

Interpretability: in a separate notebook, load the best model from MLflow and run SHAP to explain its predictions

Use your_catalog_here.lending_club_walk for any feature views.

Feature Views: solving train/serve skew

A common production ML failure is a model that receives differently transformed data at inference time than it saw during training. You clean a column one way in your training notebook, a different way in your serving pipeline, and suddenly your model cannot understand its input data.

Genie Code solved this by wrapping all feature logic in a single compute_loan_features() function and writing the cleaned output to a Delta source table. It then registered each feature column in Unity Catalog (Databricks' ColumnSelection pattern), keyed on loan_id. The registered feature definitions support governance and discoverability, while compute_loan_features() remains the source of truth for how the features are computed. Reusing these definitions across training and inference helps reduce the risk of training-serving skew. The benefit extends beyond this model: reusable, governed feature definitions help teams build on existing work rather than recreate feature logic for every project.

Hyperparameter tuning: multiple trials for real improvement

In the initial modeling stage, we used default hyperparameters, and Random Forest technically won in terms of AUC. But its recall was near zero, which is bad: it was barely flagging any defaults. Gradient boosting has far more headroom under proper tuning; that's the model we selected for further tuning. The model tuning notebook runs an Optuna hyperparameter optimization study over the HistGradientBoostingClassifier search space: learning rate, max depth, regularization strength, leaf sizes. With our best model, we attain the following results.

The tuned gradient boosting model improved AUC modestly, from 0.707 to 0.721. The larger gains were in recall and F1: recall increased from 4.4% to 62.2%, while F1 improved from 0.083 to 0.469 compared with the initial Random Forest baseline. These improvements came at the expense of some precision. The right trade-off for a lending model depends on the business costs of missed defaults and false positives.

While this is a vast improvement on our original attempt, this would be a great place to iterate further. Finding the best trade-off between false positive and false negative rates requires business judgment and is an area where talking to Genie Code about your goals can shine.

SHAP: making the model explainable

A model that performs well isn't enough in regulated industries. Lending models must be explainable. The interpretability notebook loads the best model from MLflow and runs SHAP (SHapley Additive exPlanations) on a 1,000-row sample.

The SHAP analysis reveals which features the model relies on most. Interest rate, loan grade, and revolving utilization dominate the global importance. This makes intuitive sense: borrowers with high interest rates already got flagged as riskier by Lending Club's own underwriting. The waterfall plots for individual predictions show exactly how each feature pushed a specific loan toward or away from a default prediction.

Much like the performance measures, plots get logged as artifacts on the same MLflow run as the model, keeping explanations and predictions together.

Prompt 2: Deploy the model

With our tuned model and SHAP analysis in place, the next step is to deploy a Model Serving endpoint for real-time inference.

Register the best model from the walk experiment to Unity Catalog and stand up a Model Serving endpoint so I can hit it with REST calls. Put the deployment notebook in src/walk/04_deployment. Also add a 05_sample_inference notebook that loads the endpoint and tests running a sample of predictions on it.

Deployment: from notebook to REST endpoint

The deployment notebook does three things:

Registers the best model to Unity Catalog (stablebox_catalog.lending_club_walk.loan_default_classifier v1)

Sets the champion alias so downstream consumers always get the right version

Creates a Model Serving endpoint that auto-scales to zero

The endpoint was provisioned in under 10 minutes. Once ready, scoring a loan is your pick between an SDK call and a REST API call:

Model Serving handles the serving infrastructure, so developers can deploy models behind a REST API without manually provisioning compute. Endpoints can scale to accommodate changing inference demand.

The final notebook grabs 20 random loans from the source table, sends them to the live endpoint, and compares predictions to actual outcomes.

With two prompts, we generated five notebooks. Compared with the initial Random Forest baseline, the selected and tuned gradient boosting model increased recall from about 4% to 62%. It's explainable, versioned in Unity Catalog, and serving predictions over REST.

Run: Automate retraining and monitor model health

Our model is now deployed and serving predictions, but operationalizing ML also requires maintaining its performance over time. Changes in data distributions and business conditions can affect model quality, making automated workflows and ongoing monitoring essential.

I want to wrap the walk stage into a Declarative Automation Bundle (DAB) so the whole pipeline runs as an automated Databricks job. Put the bundle config in src/run/. The job should:

Run feature engineering first

Then training (depends on step 1)

Then deployment (depends on step 2)

Also add a schedule so it retrains weekly. Use your_catalog_here.lending_club_walk for everything.

Genie Code produced a databricks.yml that connects the feature engineering, model training and deployment notebooks into an automated workflow with explicit dependencies:

The bundle also includes dev and prod targets, a weekly schedule (Monday at 6 AM), and email notifications on failure. Running databricks bundle deploy deploys the workflow configuration and resources. The scheduled job orchestrates the existing feature engineering, training and deployment notebooks with defined dependencies and failure notifications. Instead of manually configuring the orchestration, we used Genie Code to build on the notebooks created during experimentation and make their execution repeatable.

One caveat is that this example is configured to retrain and redeploy every week without a model promotion gate. In a real pipeline, a better configuration would have a validation step that scores the new model on a held-out set and only promotes it if it beats the current champion. For something high-stakes like credit risk, a human approval step before it goes live is also warranted. There is nothing stopping us from working through this logic with Genie Code, though I exclude the steps for brevity.

Last piece: I need to know when this model goes stale. Build a monitoring dashboard in src/run/ that shows model health, including prediction distribution over time, drift metrics, and the latest accuracy against a holdout set.

I want to see when the input data shifts enough that I should retrain. It should be incorporated in the DAB.

When inference logging is enabled, inference tables can capture serving requests and responses with associated metadata. Actual outcomes, when available, must be supplied and joined separately to assess model accuracy. In this walkthrough, the monitoring notebook uses synthetic timestamps to simulate a week of inference traffic for Data Quality Monitoring.

Changes in interest rates or the borrower population can cause data drift and may affect model performance. Monitoring helps identify changes that warrant investigation and potentially retraining.

From prototype to an operational ML workflow

Let's recap what we did in this post:

Label engineering, leakage removal, 3 trained models, MLflow tracking

Feature Views, Optuna tuning (14x recall), SHAP explanations, live REST endpoint

Automated weekly retraining, daily drift monitoring, alerting

The walkthrough illustrates three practical benefits:

Move from experimentation toward production without starting over. Build on the work you've already done as you add deployment, automation and monitoring.

Spend less time connecting tools and workflows. Genie Code helps developers use integrated Databricks capabilities for feature management, experiment tracking, serving and MLOps.

Keep control of important decisions. Genie Code can help identify issues and recommend approaches, while data scientists review outputs, validate assumptions and refine the workflow based on business requirements.

The result is a foundation for an operational ML system, built incrementally through natural-language prompts and developer review.

Explore the companion repository to follow the walkthrough in your own Databricks workspace. You can also apply the same crawl, walk, run approach to your own dataset and use Genie Code to build out each stage of the ML lifecycle.

How does Genie Code help with machine learning development?

Genie Code helps data scientists build and iterate on ML workflows using natural language. It can assist with data preparation, feature engineering, model training, evaluation and deployment using Databricks capabilities.

Can Genie Code help build MLOps workflows?

Yes. Genie Code can help generate workflows for model registration, deployment, automated retraining and monitoring. In this walkthrough, it creates a Declarative Automation Bundle to orchestrate the ML pipeline and configure a recurring schedule.

How does Genie Code work with MLflow?

Genie Code can generate code that uses MLflow to track experiments, compare model performance, log artifacts and register trained models. This makes it easier to manage the transition from experimentation to deployment.

Can Genie Code help prevent training-serving skew?

Genie Code can help developers create reusable feature definitions using Databricks Feature Views. Sharing feature definitions across training and inference helps reduce the risk of inconsistencies between the data used to develop a model and the data used to generate predictions.

Is the workflow in this tutorial ready for production?

The walkthrough demonstrates several important components of a production ML workflow, including model serving, automation and monitoring. Real-world deployments may also require additional validation, approval gates and governance controls, particularly for high-stakes applications.

Get the latest posts in your inbox

原文为英文,正文由自动抓取并保留原文。

本文由采集器自动同步

原文发布于 Databricks Blog(Build end-to-end ML workflows with Genie Code),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。

阅读原文 ↗