top of page

[Python] Conditionally fitting


Overview


If you want to do fitting, you can do it with scipy.optimize.leastsq etc. in python.

However, when doing fitting, there are many cases where you want to condition the fitting parameters.

For example, as shown below, both parameters a and b are in the positive range to find the optimum value.

f(x, a, b)=a*x^2+b (a>0 and b>0)

This time, I will introduce such a method.



Method


When fitting, pass the difference between the fitting function and the actual data as the first argument of scipy.optimize.leastsq.


def func(param, x):
    return param[0]*x**2+param[1]
    
def fit(param, x, y):
    
    def residual(param, x, y):
        return y-func(param, x)
        
    return optimize.leastsq(residual, param, args=(x, y))

If you want to perform conditional fitting, you can minimize the function that increases the difference between the actual data and the function if the parameter does not meet the condition.


def residual(param, x, y):
    return y-func(param, x) + param_condition(param)
    
def param_condition(param):
    
    if (param meet the condition):
        return 0
    else:
        return np.inf         

※Caution

Since the objective function becomes non-differentiable, the fitting time will be considerably longer.

(I haven't looked closely at the source code, but I think we usually use the gradient of the objective function to find the optimal parameters.)

Recent Posts

See All

[Python] Output pandas.DataFrame as json

Summary Data analysis is performed using python. The analysis itself is performed using pandas, and the final results are stored in pandas.DataFrame format. I want to output this result to a file in j

Comments


Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page