如何在 BigQuery 中执行线性回归?
Posted
技术标签:
【中文标题】如何在 BigQuery 中执行线性回归?【英文标题】:How to perform linear regression in BigQuery? 【发布时间】:2016-09-13 04:46:12 【问题描述】:BigQuery 具有一些统计聚合函数,例如 STDDEV(X) 和 CORR(X, Y),但它不提供直接执行线性回归的函数。
如何使用确实存在的函数计算线性回归?
【问题讨论】:
嗨链轮!您能否将接受的答案更改为现在的原生支持? 【参考方案1】:编辑编辑:请参阅next answer,BigQuery 现在原生支持线性回归。 --Fh
以下查询使用数值稳定且易于修改以适用于任何输入表的计算执行线性回归。它使用内置函数 CORR 生成最适合模型 Y = SLOPE * X + INTERCEPT 和 Pearson 相关系数的斜率和截距。
例如,我们使用公共出生数据集将出生体重计算为怀孕持续时间的线性函数,按州细分。你可以写得更紧凑,但是我们使用了几层子查询来突出这些部分是如何组合在一起的。要将其应用于另一个数据集,您只需替换最里面的查询。
SELECT Bucket,
SLOPE,
(SUM_OF_Y - SLOPE * SUM_OF_X) / N AS INTERCEPT,
CORRELATION
FROM (
SELECT Bucket,
N,
SUM_OF_X,
SUM_OF_Y,
CORRELATION * STDDEV_OF_Y / STDDEV_OF_X AS SLOPE,
CORRELATION
FROM (
SELECT Bucket,
COUNT(*) AS N,
SUM(X) AS SUM_OF_X,
SUM(Y) AS SUM_OF_Y,
STDDEV_POP(X) AS STDDEV_OF_X,
STDDEV_POP(Y) AS STDDEV_OF_Y,
CORR(X,Y) AS CORRELATION
FROM (SELECT state AS Bucket,
gestation_weeks AS X,
weight_pounds AS Y
FROM [publicdata.samples.natality])
WHERE Bucket IS NOT NULL AND
X IS NOT NULL AND
Y IS NOT NULL
GROUP BY Bucket));
与将 X 和 Y 的乘积相加然后取差和除法相比,使用 STDDEV_POP 和 CORR 函数提高了此查询的数值稳定性,但是如果您在表现良好的数据集上使用这两种方法,则可以验证它们以高精度产生相同的结果。
【讨论】:
【参考方案2】:好消息! BigQuery 现在原生支持 ML。
产生一个线性回归CREATE MODEL
,然后用SELECT FROM ML.PREDICT
进行预测。
文档:
https://cloud.google.com/bigquery/docs/bigqueryml有趣的例子:When will Stack Overflow reply
【讨论】:
【参考方案3】:这里的代码使用关于出生(活产)的公共数据集创建线性回归模型,并将其生成到名为 demo_ml_bq 的数据集中。这必须在运行以下语句之前创建。
%%bq query
CREATE or REPLACE MODEL demo_bq_ml.babyweight_model_asis
OPTIONS
(model_type='linear_reg', labels=['weight_pounds']) AS
WITH natality_data AS (
SELECT
weight_pounds, -- this is the label; because it is continuous, we need to use regression
CAST(is_male AS STRING) AS is_male,
mother_age,
CAST(plurality AS STRING) AS plurality,
gestation_weeks,
CAST(alcohol_use AS STRING) AS alcohol_use,
CAST(year AS STRING) AS year,
ABS(FARM_FINGERPRINT(CONCAT(CAST(YEAR AS STRING), CAST(month AS STRING)))) AS hashmonth
FROM
publicdata.samples.natality
WHERE
year > 2000
AND gestation_weeks > 0
AND mother_age > 0
AND plurality > 0
AND weight_pounds > 0
)
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
alcohol_use,
year
FROM
natality_data
WHERE
MOD(hashmonth, 4) < 3 -- select 75% of the data as training
【讨论】:
以上是关于如何在 BigQuery 中执行线性回归?的主要内容,如果未能解决你的问题,请参考以下文章