能否用单条CREATE/REPLACE命令在BigQuery ML中运行多周回归模型?
在BigQuery中按周批量训练线性回归模型
你可以使用BigQuery的**分区模型(Partitioned Models)**来实现按周训练独立的线性回归模型,无需手动为每个周创建单独的模型。这种方式既满足可扩展性需求,还能统一管理所有周的模型,后续查询结果时可直接按week分区筛选。
1. 创建分区线性回归模型
通过PARTITION BY子句指定按week字段分区,BigQuery会自动为每个唯一的week值训练独立模型:
CREATE OR REPLACE MODEL data_set.partitioned_weekly_model OPTIONS( model_type='linear_reg', input_label_cols=['dependant_variable'], partition_by='week' -- 按week字段分区,自动为每个周训练独立模型 ) AS SELECT week, dependant_variable, independent_variable_a, independent_variable_b FROM data_set.source_info;
注意:字段名建议统一格式,将带空格的名称(如dependant variable)改为下划线分隔(dependant_variable),避免语法错误。
2. 查询分区模型的结果
获取各周模型的权重系数
SELECT week, feature, weight FROM ML.WEIGHTS(MODEL data_set.partitioned_weekly_model) ORDER BY week, feature;
按周进行预测
SELECT week, dependant_variable AS actual_value, predicted_dependant_variable AS predicted_value FROM ML.PREDICT( MODEL data_set.partitioned_weekly_model, (SELECT * FROM data_set.source_info) ) ORDER BY week;
3. 方案优势
- 可扩展性:无需手动编写重复的模型创建语句,新增周数据后重新训练即可自动覆盖所有分区
- 统一管理:所有周的模型存储在一个对象中,便于维护和查询
- 高效查询:通过
week分区可快速筛选特定周的模型结果,避免全量扫描
内容的提问来源于stack exchange,提问作者emorgsssss
相关产品推荐
相关产品推荐

