gpt4 book ai didi

sql - 需要 SQL Server 查询来求解三阶多项式回归

转载 作者:行者123 更新时间:2023-12-03 03:11:42 26 4
gpt4 key购买 nike

任何人都可以帮助编写一些 SQL 查询代码来提供三阶多项式回归的系数估计吗?

请假设我有一个 X 和 Y 数据值表,并且想要估计 a、b 和 c:

Y(X) = aX + bX^2 + cX^3 + E 

最佳答案

近似但快速的解决方案是从数据中采样 4 个代表点并求解这些点的多项式方程。

  1. 对于采样,您可以将数据分割成相等的扇区,并计算每个扇区的 X 和 Y 的平均值 - 可以使用 X 的四分位数来完成分割值、X 值的平均值、min(x)+(max(x)-min(x))/4 或您认为最合适的任何值

    为了说明按四分位数采样(即按行号):illustration of solving 3rd order polynomial by sampling 4 points

  2. 至于求解,我用了numberempire.com求解变量k,a,b,c的这些*方程:

    k + a*X1 + b*X1^2 + c*X1^3 - Y1 = 0,
    k + a*X2 + b*X2^2 + c*X2^3 - Y2 = 0,
    k + a*X3 + b*X3^2 + c*X3^3 - Y3 = 0,
    k + a*X4 + b*X4^2 + c*X4^3 - Y4 = 0

    *由于 Y(X) = 0 + ax bx^2 + cx^3 + ϵ 隐式包含 [0, 0] 点作为样本点之一,因此它会为不包含 [0, 0] 的数据集。我冒昧地解决了 Y(X) = k + ax bx^2 + cx^3 + ϵ

实际的 SQL 是这样的:

select
-- returns 1 row with columns labeled K, A, B and C = coefficients in 3rd order polynomial equation for the 4 sample points
-(X1*(X2p2*(X3p3*Y4-X4p3*Y3)+X2p3*(X4p2*Y3-X3p2*Y4)+(X3p2*X4p3-X3p3*X4p2)*Y2)+X1p2*(X2*(X4p3*Y3-X3p3*Y4)+X2p3*(X3*Y4-X4*Y3)+(X3p3*X4-X3*X4p3)*Y2)+X1p3*(X2*(X3p2*Y4-X4p2*Y3)+X2p2*(X4*Y3-X3*Y4)+(X3*X4p2-X3p2*X4)*Y2)+(X2*(X3p3*X4p2-X3p2*X4p3)+X2p2*(X3*X4p3-X3p3*X4)+X2p3*(X3p2*X4-X3*X4p2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p2)+X1p2*(X3*X4p3+X2*(X3p3-X4p3)+X2p3*(X4-X3)-X3p3*X4)+X2p2*(X3p3*X4-X3*X4p3)+X1p3*(X2*(X4p2-X3p2)-X3*X4p2+X3p2*X4+X2p2*(X3-X4))+X2p3*(X3*X4p2-X3p2*X4)) as b,
(X1*(X2p2*(Y4-Y3)-X3p2*Y4+X4p2*Y3+(X3p2-X4p2)*Y2)+X2*(X3p2*Y4-X4p2*Y3)+X1p2*(X3*Y4+X2*(Y3-Y4)-X4*Y3+(X4-X3)*Y2)+X2p2*(X4*Y3-X3*Y4)+(X3*X4p2-X3p2*X4)*Y2+(X2*(X4p2-X3p2)-X3*X4p2+X3p2*X4+X2p2*(X3-X4))*Y1)/(X1*(X2p2*(X4p3-X3p3)-X3p2*X4p3+X3p3*X4p2+X2p3*(X3p2-X4p2))+X2*(X3p2*X4p3-X3p3*X4p2)+X1p2*(X3*X4p3+X2*(X3p3-X4p3)+X2p3*(X4-X3)-X3p3*X4)+X2p2*(X3p3*X4-X3*X4p3)+X1p3*(X2*(X4p2-X3p2)-X3*X4p2+X3p2*X4+X2p2*(X3-X4))+X2p3*(X3*X4p2-X3p2*X4)) as c
from (select
samples.*,
-- precomputing the powers should give better performance (at least i hope it would)
power(X1,2) X1p2, power(X2,2) X2p2, power(X3,2) X3p2, power(X4,2) X4p2,
power(Y1,3) Y1p3, power(Y2,3) Y2p3, power(Y3,3) Y3p3, power(Y4,3) Y4p3
from (select
avg(case when sector = 1 then x end) X1,
avg(case when sector = 2 then x end) X2,
avg(case when sector = 3 then x end) X3,
avg(case when sector = 4 then x end) X4,
avg(case when sector = 1 then y end) Y1,
avg(case when sector = 2 then y end) Y2,
avg(case when sector = 3 then y end) Y3,
avg(case when sector = 4 then y end) Y4
from (select x, y,
-- splitting to sectors 1 - 4 by row number (SQL Server version)
ceiling(row_number() OVER (ORDER BY x asc) / count(*) * 4) sector
from original_data
)
) samples
)

根据developer.mimer.com ,需要在 SQL Server 中启用这些可选功能:

T611, "Elementary OLAP operations"
F591, "Derived tables"

关于sql - 需要 SQL Server 查询来求解三阶多项式回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9292209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com