How to fit datasets so that they share some (but not all) parameter values

104 views Asked by At

Say I want to fit two arrays x_data_one and y_data_one with an exponential function. In order to do that I might use the following code (in which x_data_one and y_data_one are given dummy definitions):

import numpy as np
from scipy.optimize import curve_fit

def power_law(x, a, b, c):
    return a * (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 I want to fit a 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 could I perform these two fits such that they were constrained to have a_one == a_two and b_one == b_two, but not necessarily c_one == c_two? I don't want to constrain a_one or b_one to a particular value; I want to find values that provide the best fit for both datasets.

1

There are 1 answers

0
AudioBubble On BEST ANSWER

You could simply overwrite your function for the 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 you could use this (it finds optimal a,b for all data and optimal c1 for data_one and c2 for data_two):

def power_law(x, a, b, c1, c2):
    l = len(x_data_one)
    return a * 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 my opinion second code much nicer and pythonic :)