You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Julia的curve_fit中传递非拟合额外参数?

在Julia中使用curve_fit拟合含非拟合参数的自定义函数

完全可以实现这种需求,核心思路是将非拟合的模型选择参数从待优化参数列表中剥离,通过包装函数让curve_fit只处理需要拟合的参数。以下是具体实现步骤:

1. 重构自定义函数,分离非拟合参数

将原函数中作为模型选择器的typ单独作为参数传入,而非放在拟合参数数组里,明确区分固定参数和待优化参数:

function pbase(d, p, typ)
    pimb = fill(-5.81, length(d))
    # 根据拟合参数数量计算x:p是待优化参数数组,长度为1或2
    @. x = length(p) == 2 ? p[1]*(log10(d)-log10(p[2])) : p[1]*log10(d)
    if typ == "tanh"
        @. pimb *= tanh(x)
    elseif typ == "arctan"
        @. pimb *= atan(x)
    end
    pimb
end

2. 创建包装函数,固定非拟合参数

针对选定的模型类型(比如tanh或arctan),创建只接受自变量和待优化参数的包装函数,供curve_fit调用:

# 固定模型为tanh
model_tanh(d, p) = pbase(d, p, "tanh")

# 固定模型为arctan
model_arctan(d, p) = pbase(d, p, "arctan")

如果需要动态选择模型类型,可通过闭包生成包装函数:

function create_model(typ)
    return (d, p) -> pbase(d, p, typ)
end

# 运行时指定模型
selected_model = create_model("arctan")

3. 使用curve_fit执行拟合

借助LsqFit包的curve_fit函数进行拟合,传入包装后的模型、数据集和初始参数猜测:

using LsqFit

# 示例数据集(替换为你的真实数据)
d_data = [1.0, 2.0, 3.0, 4.0, 5.0]
y_data = [-5.81*tanh(0.5*(log10(d)-log10(2.0))) for d in d_data]

# 初始参数猜测:根据模型需求,长度为1或2
p0 = [0.5, 2.0]  # 对应原pars[2]和pars[3]

# 执行拟合
fit_result = curve_fit(model_tanh, d_data, y_data, p0)

# 获取拟合后的参数
p_fit = fit_result.param

关键说明

curve_fit默认会优化传入模型函数的所有参数,因此必须把不需要拟合的模型选择器(typ)从参数数组中移除,通过包装函数固定它,这样工具就只会优化我们指定的p[1]、p[2]参数。

内容的提问来源于stack exchange,提问作者TomR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:33:27