Nonlinear fiting with posibility to fix some of the parameters

Dear all,

I am trying to figure out how to fit nonlinear function to my data using Optim package.

Here is example


# data x and y

using Optim

model(x,p) = p[1] .+ p[2] .* x .+ p[3] .*x.^2

loss_function(p) = sum((model(x,p) .- y).^2

p0 = [0., 0., 0.]

result =  optimize(loss_function, p0 ) 

Now I would like to fix one of the fitting parametrs, e.g. p[2] = 1.0
And fit the data just using parameters p[1] and p[3].

Is there any method to achieve it?

You could define a new loss_function for example

loss_function_projected(p2) = q -> loss_function( (q[1], p2, q[2]) )

q0 = [0.0, 0.0]
result =  optimize(loss_function_projected(1.0), q0 ) 

Oh thanks that is really nice. For fixing one of the parameter it works pretty nice.
But I don’t know how to fix more parametrs.



loss_function_projected(p2) = q -> loss_function( (p2[1], p2[2], q[2]) )

pp = [1, 2]
q0 = [0.0]
result =  optimize(loss_function_projected(pp), q0 ) 

gave me BoundsError: attempt to access 1-element Vector{Float64} at index [2]

So I probably miss the concept of the function projection.

The error was just that q is then only of length one, i.e. instead of using q[2] you need q[1]:

loss_function_projected(p12) = q -> loss_function( (p12[1], p12[2], q[1]) )

p12 = [1, 2]
q0 = [0.0]
result =  optimize(loss_function_projected(p12), q0 ) 
1 Like

I see, thank you very much.