gpt4 book ai didi

Julia:不能将 `convert` Array{Number,1} 类型的对象转换为 GLM.LmResp 类型的对象

转载 作者:行者123 更新时间:2023-12-05 06:33:11 25 4
gpt4 key购买 nike

我正在逐行构建一个 DataFrame,然后对其进行回归。为简单起见,代码为:

using DataFrames
using GLM

df = DataFrame(response = Number[])
for i in 1:10
df = vcat(df, DataFrame(response = rand()))
end

fit(LinearModel, @formula(response ~ 1), df)

我得到错误:

ERROR: LoadError: MethodError: Cannot `convert` an object of type Array{Number,1} to an object of type GLM.LmResp
This may have arisen from a call to the constructor GLM.LmResp(...),
since type constructors fall back to convert methods.
Stacktrace:
[1] fit(::Type{GLM.LinearModel}, ::Array{Float64,2}, ::Array{Number,1}) at ~/.julia/v0.6/GLM/src/lm.jl:140
[2] #fit#44(::Dict{Any,Any}, ::Array{Any,1}, ::Function, ::Type{GLM.LinearModel}, ::StatsModels.Formula, ::DataFrames.DataFrame) at ~/.julia/v0.6/StatsModels/src/statsmodel.jl:72
[3] fit(::Type{GLM.LinearModel}, ::StatsModels.Formula, ::DataFrames.DataFrame) at ~/.julia/v0.6/StatsModels/src/statsmodel.jl:66
[4] include_from_node1(::String) at ./loading.jl:576
[5] include(::String) at ./sysimg.jl:14
while loading ~/test.jl, in expression starting on line 10

对线性回归的调用与 regression in "Introducing Julia" 非常相似:

linearmodel = fit(LinearModel, @formula(Y1 ~ X1), anscombe)

问题是什么?

最佳答案

几个小时后,我意识到 GLM 需要具体类型,而 Number 是一种抽象类型(尽管 documentation for GLM.LmResp 在撰写本文时对此只字未提,仅“封装了线性模型的响应”) .解决方案是将声明更改为具体类型,例如 Float64:

using DataFrames
using GLM

df = DataFrame(response = Float64[])
for i in 1:10
df = vcat(df, DataFrame(response = rand()))
end

fit(LinearModel, @formula(response ~ 1), df)

输出:

StatsModels.DataFrameRegressionModel{GLM.LinearModel{GLM.LmResp{Array{Float64,1}},GLM.DensePredChol{Float64,Base.LinAlg.Cholesky{Float64,Array{Float64,2}}}},Array{Float64,2}}

Formula: response ~ +1

Coefficients:
Estimate Std.Error t value Pr(>|t|)
(Intercept) 0.408856 0.0969961 4.21518 0.0023

类型必须是具体的,例如带有 df = DataFrame(response = Real[]) 的抽象类型 Real 失败并显示更有用的错误消息:

ERROR: LoadError: `float` not defined on abstractly-typed arrays; please convert to a more specific type

或者,您可以在构建数据框后转换为 Real:

using DataFrames
using GLM

df = DataFrame(response = Number[])
for i in 1:10
df = vcat(df, DataFrame(response = rand()))
end

df2 = DataFrame(response = map(Real, df[:response]))

fit(LinearModel, @formula(response ~ 1), df2)

之所以可行,是因为转换为 Real 实际上会转换为 Float64:

julia> typeof(df2[:response])
Array{Float64,1}

我提交了一份 issue with GLM改进错误消息。

关于Julia:不能将 `convert` Array{Number,1} 类型的对象转换为 GLM.LmResp 类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50874295/

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