# Least squares with SciML NonlinearSolve.jl - how to?

**URL:** <https://discourse.julialang.org/t/least-squares-with-sciml-nonlinearsolve-jl-how-to/113074>\
**Category:** General Usage\
**Tags:** nonlinearsolve, least-squares\
**Created:** [April 17, 2024, 2:25pm UTC](https://discourse.julialang.org/t/least-squares-with-sciml-nonlinearsolve-jl-how-to/113074 "2024-04-17T14:25:02Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![Eben60](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/eben60/32/13475_2.png) [@Eben60](https://discourse.julialang.org/u/Eben60)\
**Post date:** [April 18, 2024, 9:18pm UTC](https://discourse.julialang.org/t/least-squares-with-sciml-nonlinearsolve-jl-how-to/113074/14 "2024-04-18T21:18:28Z")

</div>

OK, now I got it.

```julia
using NonlinearSolve, Plots

function curve_fit(model, u0, xdata, ydata, p)
    data = (xdata, ydata, p)

    function lossfn!(du, u, data)
        (xs, ys, p) = data   
        du .= model.(xs, Ref(u), Ref(p)) .- ys
        return nothing
    end

    prob = NonlinearLeastSquaresProblem(
        NonlinearFunction(lossfn!, resid_prototype = similar(ydata)), u0, data)
    sol = solve(prob)
    u = sol.u
    fit = model.(xdata, Ref(u), Ref(p))
    return (;sol, fit)
end

```

define a model:

```julia
function expmodel(x, u, t₀=0)
    y0 = u[1]
    a = u[2]
    τ = u[3]
    return y0 + a * exp(-(x-t₀)/τ)
end

```

synthesize data:

```julia
y0, a, τ, t₀ = 0.0, 1.0, 2.0, 0
xs = 0:0.1:3;
ys0 = expmodel.(xs, Ref([y0, a, τ]), Ref(t₀));
ys = @. ys0 + 0.02*randn()

```

Solve, plot:

```julia
(;sol, fit) = curve_fit(expmodel, [y0, a, τ], xs, ys, t₀)

plot(xs, [ys, fit])

```

 ![fit](https://global.discourse-cdn.com/julialang/original/3X/8/3/831ec37cdc7cc2059155bf129b9e9af64e93560c.png)  
and enjoy 🙂

---

_[View the full topic](https://discourse.julialang.org/t/least-squares-with-sciml-nonlinearsolve-jl-how-to/113074)._
