How to minimise chi squared to optimise two parameters in Python

522 Views Asked by At

I am getting rather confused on the process of optimising the values of Two parameters I have given their estimated values.

import scipy.optimize as optimize

# Define the function you want to minimize
def my_function(x, y):
    return x**2 + y**2

# Use the fmin function to find the minimum of the function
result = optimize.fmin(my_function, x0=[0, 0])

# The result will be an array containing the values of the parameters that minimize the function
print(result)

I understand this example but for my case I want to minimise a chi Squared function chi_square = np.sum(((y - f1)/yerr)**2) where f1 is a function, dependent on two parameters, with inital guess values, that need to be optimised.

The input values of the function, f, which calculates the model are : two parameters C1, C2 and then time which is input as an array of data values.

C1 = 0.002 C2 = 0.003 f(C1,C2,t) f = some function including C1,C2 constants and time input t return f

time_input = data[:,0]

f1= f(C1,C2, time_input) to get model values in order to compare to y in the chi square for the same time data points[:,0].

I want to use optimize.fmin to essentially find values of C1 and C2 for a minimised chi_square but I am unsure of how to do this as in the optimize example given, it is for a function with parameters x and y, whereas my function is a chi square function where 'model' is the function that needs its input parameters C1,C2, to be optimised.

Said the number of positional arguments was incorrect, when I put the guess values of 0.002 and 0.003 in X0.

1

There are 1 best solutions below

0
On

I'm not sure where this example is from (maybe it's an older version). However, the current way of using the API is to define your variable for n-dimensional problems in an n-dimensional array. Your function should have the signature

def model(C: np.ndarray, *args):
    # Do something

Note that args is for your extra arguments. Example:

from scipy import optimize


optimize.fmin(fun=model, x0=[0, 0], agrs=([0, 1, 2,]))

I'm not sure if you are using fmin because you do want to use this specific algorithm, but in general, I recommend optimize.minimize unless you have a specific reason to not use it.