数据建模与机器学习集成

数据建模入门数据建模数据仓库机器学习

问题

数据仓库如何支持机器学习?Feature Store是什么?

答题要点

设计ML友好的特征表:

特征工程表设计

-- 客户特征表(用于客户流失预测模型)
CREATE TABLE ml_customer_features (
    customer_id VARCHAR(50) PRIMARY KEY,
    feature_version DATE,  -- 特征快照日期

    -- 人口统计特征
    age INT,
    gender VARCHAR(10),
    region VARCHAR(100),
    registration_days INT,  -- 注册天数

    -- 行为特征
    total_orders INT,
    total_revenue DECIMAL(12,2),
    avg_order_value DECIMAL(10,2),
    days_since_last_order INT,

    -- RFM特征
    recency INT,  -- 最近一次购买距今天数
    frequency INT,  -- 购买频次
    monetary DECIMAL(12,2),  -- 总消费金额

    -- 趋势特征
    revenue_last_30days DECIMAL(12,2),
    revenue_last_90days DECIMAL(12,2),
    revenue_growth_rate DECIMAL(5,2),  -- 收入增长率

    -- 互动特征
    email_open_rate DECIMAL(5,2),
    support_ticket_count INT,

    -- 标签(用于训练)
    is_churned BOOLEAN,  -- 流失标签(未来30天无购买)

    -- 审计
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);

-- Point-in-Time特征(避免数据泄露)
-- 确保特征只使用截止时间点之前的数据
CREATE TABLE ml_features_snapshot AS
SELECT
    customer_id,
    '2024-06-01' AS feature_date,
    -- 只使用2024-06-01之前的数据计算特征
    SUM(CASE WHEN order_date < '2024-06-01' THEN order_amount ELSE 0 END) AS total_revenue,
    MAX(CASE WHEN order_date < '2024-06-01' THEN order_date END) AS last_order_date,
    DATEDIFF('2024-06-01', MAX(CASE WHEN order_date < '2024-06-01' THEN order_date END)) AS days_since_last_order,
    -- 标签: 未来30天是否有购买
    CASE
        WHEN MAX(CASE WHEN order_date BETWEEN '2024-06-01' AND '2024-07-01' THEN 1 ELSE 0 END) = 0
        THEN TRUE
        ELSE FALSE
    END AS is_churned_30d
FROM fact_sales
GROUP BY customer_id;

Feature Store架构

# 使用Feast Feature Store
from feast import FeatureStore, Entity, Feature, FeatureView, FileSource
from feast.value_type import ValueType
from datetime import timedelta

# 定义实体
customer = Entity(
    name="customer_id",
    value_type=ValueType.STRING,
    description="客户ID"
)

# 定义特征视图
customer_features_view = FeatureView(
    name="customer_features",
    entities=["customer_id"],
    ttl=timedelta(days=1),  # 特征新鲜度
    features=[
        Feature(name="total_orders", dtype=ValueType.INT64),
        Feature(name="total_revenue", dtype=ValueType.DOUBLE),
        Feature(name="days_since_last_order", dtype=ValueType.INT64),
        Feature(name="recency", dtype=ValueType.INT64),
        Feature(name="frequency", dtype=ValueType.INT64),
        Feature(name="monetary", dtype=ValueType.DOUBLE),
    ],
    online=True,  # 支持在线推理
    batch_source=FileSource(
        path="s3://features/customer_features.parquet",
        event_timestamp_column="event_timestamp"
    ),
    tags={"team": "data_science", "project": "churn_prediction"}
)

# Feature Store
fs = FeatureStore(repo_path=".")

# 离线特征获取(训练)
entity_df = pd.DataFrame({
    "customer_id": ["C001", "C002", "C003"],
    "event_timestamp": pd.to_datetime(["2024-06-01", "2024-06-01", "2024-06-01"])
})

training_df = fs.get_historical_features(
    entity_df=entity_df,
    features=[
        "customer_features:total_orders",
        "customer_features:total_revenue",
        "customer_features:recency",
    ],
).to_df()

# 在线特征获取(推理)
online_features = fs.get_online_features(
    features=[
        "customer_features:total_orders",
        "customer_features:recency",
    ],
    entity_rows=[{"customer_id": "C001"}]
).to_dict()

dbt + ML集成

-- models/ml/ml_customer_features.sql
{{
  config(
    materialized='table',
    tags=['ml', 'features']
  )
}}

WITH customer_aggregates AS (
    SELECT
        customer_id,
        COUNT(order_id) AS total_orders,
        SUM(sales_amount) AS total_revenue,
        AVG(sales_amount) AS avg_order_value,
        MAX(order_date) AS last_order_date,
        MIN(order_date) AS first_order_date
    FROM {{ ref('fact_sales') }}
    GROUP BY customer_id
),

customer_demographics AS (
    SELECT
        customer_id,
        EXTRACT(YEAR FROM AGE(CURRENT_DATE, birth_date)) AS age,
        gender,
        region
    FROM {{ ref('dim_customer') }}
    WHERE is_current = TRUE
)

SELECT
    d.customer_id,
    d.age,
    d.gender,
    d.region,
    a.total_orders,
    a.total_revenue,
    a.avg_order_value,
    DATE_PART('day', CURRENT_DATE - a.last_order_date) AS days_since_last_order,
    DATE_PART('day', a.last_order_date - a.first_order_date) AS customer_lifetime_days
FROM customer_demographics d
LEFT JOIN customer_aggregates a ON d.customer_id = a.customer_id

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题