python - How to fit datasets so that they share some (but not all) parameter values -
say want fit 2 arrays x_data_one
, y_data_one
exponential function. in order might use following code (in x_data_one
, y_data_one
given dummy definitions):
import numpy np scipy.optimize import curve_fit def power_law(x, a, b, c): return * (x + c) ** b x_data_one = np.random.rand(10) y_data_one = np.random.rand(10) (a_one, b_one, c_one), _ = curve_fit(power_law, x_data_one, y_data_one)
now suppose want fit second dataset:
x_data_two = np.random.rand(10) y_data_two = np.random.rand(10) (a_two, b_two, c_two), _ = curve_fit(power_law, x_data_two, y_data_two)
how perform these 2 fits such constrained have a_one == a_two
, b_one == b_two
, not c_one == c_two
? don't want constrain a_one
or b_one
particular value; want find values provide best fit both datasets.
you overwrite function second data set:
def power_law2(x, c): return a_one * (x + c) ** b_one x_data_two = np.random.rand(10) y_data_two = np.random.rand(10) c_two = curve_fit(power_law2, x_data_two, y_data_two)[0][0]
or use (it finds optimal a,b data , optimal c1 data_one , c2 data_two):
def power_law(x, a, b, c1, c2): l = len(x_data_one) return * np.hstack([x[:l] + c1, x[l:] + c2]) ** b x_data_one_two = np.hstack([x_data_one,x_data_two]) y_data_one_two = np.hstack([y_data_one,y_data_two]) (a_one, b_one, c_one, c_two), _ = curve_fit(power_law, x_data_one_two, y_data_one_two)
in opinion second code nicer , pythonic :)
Comments
Post a Comment