【发布时间】:2023-04-09 17:05:01
【问题描述】:
我对 Julia 很陌生。
Julia 中是否有一个包可以帮助自动向后或向前消除多元线性回归问题的特征。
我在 python here 和 here 中找到了代码,但在 Julia 中找不到任何代码。
提前致谢!
【问题讨论】:
标签: regression julia linear-regression
我对 Julia 很陌生。
Julia 中是否有一个包可以帮助自动向后或向前消除多元线性回归问题的特征。
我在 python here 和 here 中找到了代码,但在 Julia 中找不到任何代码。
提前致谢!
【问题讨论】:
标签: regression julia linear-regression
如果没有回应,可能不支持:)。原因很可能是通常 Lasso 等比向前/向后选择更受欢迎。并且您支持正则化,例如在 Regression.jl 中。
但是,编写自己的逐步选择非常简单:
using DataFrames
using RDatasets
using StatsBase
using GLM
function compose(lhs::Symbol, rhs::AbstractVector{Symbol})
Formula(lhs, Expr(:call, :+, [1;rhs]...))
end
function step(df, lhs::Symbol, rhs::AbstractVector{Symbol},
forward::Bool, use_aic::Bool)
options = forward ? setdiff(names(df), [lhs; rhs]) : rhs
fun = use_aic ? aic : bic
isempty(options) && return (rhs, false)
best_fun = fun(lm(compose(lhs, rhs), df))
improved = false
best_rhs = rhs
for opt in options
this_rhs = forward ? [rhs; opt] : setdiff(rhs, [opt])
this_fun = fun(lm(compose(lhs, this_rhs), df))
if this_fun < best_fun
best_fun = this_fun
best_rhs = this_rhs
improved = true
end
end
(best_rhs, improved)
end
function stepwise(df, lhs::Symbol, forward::Bool, use_aic::Bool)
rhs = forward ? Symbol[] : setdiff(names(df), [lhs])
while true
rhs, improved = step(df, lhs, rhs, forward, use_aic)
improved || return lm(compose(lhs, sort(rhs)), df)
end
end
上面的两个关键参数是forward(我们是向前还是向后选择)和use_aic(我们使用AIC还是BIC)。当然,这一切都可以很容易地改变。该实现并未针对速度进行优化,但在简单情况下应该足够好。
这里是你如何使用它:
df = dataset("datasets", "swiss")[2:end]
stepwise(df, :Fertility, true, false)
stepwise(df, :Fertility, true, true)
stepwise(df, :Fertility, false, true)
stepwise(df, :Fertility, false, false)
(所有选项都返回相同的模型,并且与 R 中的参考示例一致)
【讨论】:
compose 函数会不同,2)模型估计会不同,3)停止标准会不同。但总的来说,您所说的要求非常不寻常,可能不是最优的(一个特定的问题是应该如何计算分类变量)。