gpt4 book ai didi

julia - 方法错误 : no method matching in user defined function

转载 作者:行者123 更新时间:2023-12-04 02:34:15 24 4
gpt4 key购买 nike

为了开始使用 Julia,我正在尝试构建一个非常简单的函数来获取后验分布:

grid_length = 20
k_successes = 6
n_trials = 9
prior = ones(grid_length)

function plot_posterior(grid_length::Int64 , k_successes::Int64 , n_trials::Int64 , prior::Any = nothing )

# define grid, possible parameter values ( our paremeter is the probability of success vs failure)
p_grid = collect(range(0, 1, length = grid_length))

# define uninformative prior if it is not specified
if isnothing(prior)
prior = ones(grid_length)
end

# compute likelihood at each value in grid
likelihood = [prob_binomial(k_successes , n_trials , prob) for prob in p_grid]
# compute product of likelihood and prior
unstd_posterior = likelihood .* prior
# standardize the posterior, so it sums to 1
posterior = unstd_posterior ./ sum(unstd_posterior)

x = p_grid; y = posterior
Plots.plot(x, y)

end

当我尝试

plot_posterior(grid_length=20 , k_successes=6 , n_trials=10 , prior = nothing )

我收到以下错误:

MethodError: 没有方法匹配 plot_posterior(; grid_length=20, k_successes=6, n_trials=10, prior=nothing)最接近的候选人是:plot_posterior(!Matched::Int64, !Matched::Int64, !Matched::Int64) 在 [6]:9 得到不支持的关键字参数“grid_length”、“k_successes”、“n_trials”、“prior”plot_posterior(!Matched::Int64, !Matched::Int64, !Matched::Int64, !Matched::Any) 在 [6]:9 得到不支持的关键字参数 "grid_length", "k_successes", "n_trials", "事先的”plot_posterior(!Matched::Any, !Matched::Any, !Matched::Any) 在 [3]:9 得到不支持的关键字参数“grid_length”、“k_successes”、“n_trials”、“prior”...

对可能发生的事情有什么帮助吗?

提前致谢

最佳答案

在签名中:

function plot_posterior(grid_length::Int64,
k_successes::Int64,
n_trials::Int64,
prior::Any = nothing)

您定义了位置参数,因此对您的函数的正确调用应该是:

plot_posterior(20, 6, 10, nothing)

如果您想在调用中使用参数名称,您需要将参数定义为关键字,如下所示:

function plot_posterior(;grid_length::Int64,
k_successes::Int64,
n_trials::Int64,
prior::Any = nothing)

请注意,我在参数列表前面添加了 ;

通常,您可以在单个函数定义中混合位置参数和关键字参数,例如:

f(a; b) = # your definition

现在 a 是位置参数,b 是关键字参数。您可以在 Julia 手册中阅读更多相关信息 here特别是关键字参数 here .

关于julia - 方法错误 : no method matching in user defined function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62592202/

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