Fitting Parameters

Last updated: April 28th, 20202020-04-28Project preview

Before we start...

We need to install packages required to calculate. To do so, we need to use Terminal as following instruction.

It should be installed but just in case, if you attempt to execute this script at somewhere else

  1. (assuming you are in the same env as "open lab") Open Terminal from Launcher

image

  1. Click Terminal then in the prompt, type the followings

image

pip install scipy matplotlib ipywidgets ipympl

Or execute the following line:

In [3]:
!pip install scipy matplotlib ipywidgets ipympl
Collecting scipy
  Downloading scipy-1.4.1-cp38-cp38-manylinux1_x86_64.whl (26.0 MB)
     |████████████████████████████████| 26.0 MB 10.3 MB/s eta 0:00:01
Collecting matplotlib
  Downloading matplotlib-3.2.1-cp38-cp38-manylinux1_x86_64.whl (12.4 MB)
     |████████████████████████████████| 12.4 MB 45.5 MB/s eta 0:00:01
Collecting ipywidgets
  Downloading ipywidgets-7.5.1-py2.py3-none-any.whl (121 kB)
     |████████████████████████████████| 121 kB 55.1 MB/s eta 0:00:01
Collecting ipympl
  Downloading ipympl-0.5.6-py2.py3-none-any.whl (454 kB)
     |████████████████████████████████| 454 kB 49.4 MB/s eta 0:00:01
Collecting numpy>=1.13.3
  Downloading numpy-1.18.3-cp38-cp38-manylinux1_x86_64.whl (20.6 MB)
     |████████████████████████████████| 20.6 MB 44.3 MB/s eta 0:00:01
Collecting cycler>=0.10
  Downloading cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)
Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1
  Downloading pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)
     |████████████████████████████████| 67 kB 10.8 MB/s eta 0:00:01
Collecting kiwisolver>=1.0.1
  Downloading kiwisolver-1.2.0-cp38-cp38-manylinux1_x86_64.whl (92 kB)
     |████████████████████████████████| 92 kB 163 kB/s  eta 0:00:01
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.8/site-packages (from matplotlib) (2.8.1)
Collecting widgetsnbextension~=3.5.0
  Downloading widgetsnbextension-3.5.1-py2.py3-none-any.whl (2.2 MB)
     |████████████████████████████████| 2.2 MB 46.6 MB/s eta 0:00:01
Requirement already satisfied: ipython>=4.0.0; python_version >= "3.3" in /usr/local/lib/python3.8/site-packages (from ipywidgets) (7.13.0)
Requirement already satisfied: traitlets>=4.3.1 in /usr/local/lib/python3.8/site-packages (from ipywidgets) (4.3.3)
Requirement already satisfied: ipykernel>=4.5.1 in /usr/local/lib/python3.8/site-packages (from ipywidgets) (5.1.4)
Requirement already satisfied: nbformat>=4.2.0 in /usr/local/lib/python3.8/site-packages (from ipywidgets) (5.0.4)
Requirement already satisfied: six in /usr/local/lib/python3.8/site-packages (from cycler>=0.10->matplotlib) (1.14.0)
Requirement already satisfied: notebook>=4.4.1 in /usr/local/lib/python3.8/site-packages (from widgetsnbextension~=3.5.0->ipywidgets) (6.0.3)
Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /usr/local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (3.0.3)
Requirement already satisfied: pickleshare in /usr/local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (0.7.5)
Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (45.2.0)
Requirement already satisfied: pygments in /usr/local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (2.5.2)
Requirement already satisfied: jedi>=0.10 in /usr/local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (0.16.0)
Requirement already satisfied: pexpect; sys_platform != "win32" in /usr/local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (4.8.0)
Requirement already satisfied: decorator in /usr/local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (4.4.2)
Requirement already satisfied: backcall in /usr/local/lib/python3.8/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (0.1.0)
Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.8/site-packages (from traitlets>=4.3.1->ipywidgets) (0.2.0)
Requirement already satisfied: jupyter-client in /usr/local/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets) (6.0.0)
Requirement already satisfied: tornado>=4.2 in /usr/local/lib/python3.8/site-packages (from ipykernel>=4.5.1->ipywidgets) (6.0.3)
Requirement already satisfied: jupyter-core in /usr/local/lib/python3.8/site-packages (from nbformat>=4.2.0->ipywidgets) (4.6.3)
Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /usr/local/lib/python3.8/site-packages (from nbformat>=4.2.0->ipywidgets) (3.2.0)
Requirement already satisfied: Send2Trash in /usr/local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (1.5.0)
Requirement already satisfied: pyzmq>=17 in /usr/local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (19.0.0)
Requirement already satisfied: nbconvert in /usr/local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (5.6.1)
Requirement already satisfied: prometheus-client in /usr/local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (0.7.1)
Requirement already satisfied: jinja2 in /usr/local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (2.11.1)
Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.8/site-packages (from notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (0.8.3)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.8/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (0.1.8)
Requirement already satisfied: parso>=0.5.2 in /usr/local/lib/python3.8/site-packages (from jedi>=0.10->ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (0.6.2)
Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.8/site-packages (from pexpect; sys_platform != "win32"->ipython>=4.0.0; python_version >= "3.3"->ipywidgets) (0.6.0)
Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.8/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets) (19.3.0)
Requirement already satisfied: pyrsistent>=0.14.0 in /usr/local/lib/python3.8/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets) (0.15.7)
Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (0.3)
Requirement already satisfied: defusedxml in /usr/local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (0.6.0)
Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (0.8.4)
Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (1.4.2)
Requirement already satisfied: bleach in /usr/local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (3.1.1)
Requirement already satisfied: testpath in /usr/local/lib/python3.8/site-packages (from nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (0.4.4)
Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.8/site-packages (from jinja2->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (1.1.1)
Requirement already satisfied: webencodings in /usr/local/lib/python3.8/site-packages (from bleach->nbconvert->notebook>=4.4.1->widgetsnbextension~=3.5.0->ipywidgets) (0.5.1)
Installing collected packages: numpy, scipy, cycler, pyparsing, kiwisolver, matplotlib, widgetsnbextension, ipywidgets, ipympl
Successfully installed cycler-0.10.0 ipympl-0.5.6 ipywidgets-7.5.1 kiwisolver-1.2.0 matplotlib-3.2.1 numpy-1.18.3 pyparsing-2.4.7 scipy-1.4.1 widgetsnbextension-3.5.1
In [4]:
## These are the python libraries you will utilize for the calculation

import matplotlib.pylab as plt 
import matplotlib.pyplot as plt; plt.rcdefaults()

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

%matplotlib inline

import numpy as np
import scipy
from scipy.optimize import curve_fit
from scipy.integrate import odeint

Ordinary Differential Equation

image

$\dfrac{d[A]}{dt}=-k_1[A]+k_2[B]$

$\dfrac{d[B]}{dt}=-(k_2+k_3)[B]+k_1[A]+k_4[C]$

$\dfrac{d[C]}{dt}=-(k_4+k_5)[C]+k_3[B]+k_6[D]$

$\dfrac{d[D]}{dt}=-k_6[D]+k_5[C]$

  1. create a function to return $\dfrac{dy}{dt}$
  2. set parameters (ex. $k_1 = 1$)
  3. set length of calculation (this is a time-dependent)
  4. execute ode solver
  5. plot them
In [ ]:
def func1(y,t):
    
    k1 = 1
    k2 = 0.5
    k3 = 1.2
    k4 = 0.7
    k5 = 0.8
    k6 = 0.7
    
    dAdt = -k1*y[0] + k2*y[1]
    dBdt = -(k2+k3)*y[1] + k1*y[0] + k4*y[2]
    dCdt = -(k4+k5)*y[2] + k3*y[1] + k6*y[3]
    dDdt = -k6*y[3] + k5*y[2]
    
    dydt = [dAdt, dBdt, dCdt, dDdt]
    
    return dydt 
In [ ]:
def func2(y,t,k):
    
    k1 = k[0]
    k2 = k[1]
    k3 = k[2]
    k4 = k[3]
    k5 = k[4]
    k6 = k[5]
    
    dAdt = -k1*y[0] + k2*y[1]
    dBdt = -(k2+k3)*y[1] + k1*y[0] + k4*y[2]
    dCdt = -(k4+k5)*y[2] + k3*y[1] + k6*y[3]
    dDdt = -k6*y[3] + k5*y[2]
    
    dydt = [dAdt, dBdt, dCdt, dDdt]
    
    return dydt 
In [ ]:
def func3(y,t,k):
    
    A,B,C,D = y
    k1,k2,k3,k4,k5,k6 = k
    
    dAdt = -k1*A + k2*B
    dBdt = -(k2+k3)*B + k1*A + k4*C
    dCdt = -(k4+k5)*C + k3*B + k6*D
    dDdt = -k6*D + k5*C
    
    dydt = [dAdt, dBdt, dCdt, dDdt]
    
    return dydt 
In [ ]:
def func4(y,t,J):
    return np.dot(J,y)
In [ ]:
# Initial condition of calculation
y0 = [10,0,0,0]

# for function 1 
# the set of parameter is predetermined 

# for function 2,3
# k (reaction rate or transition rate) is one of input variables you need to specify before calculation
# function 2 and 3 handle the list of reaction rate
k = [1, 0.5, 1.2, 0.7, 0.8, 0.7]

# for function 4 
# we are using Jacobian method so we will introduce Jacobian matrix using np.array and the function will perform dot operation
k1 = k[0]
k2 = k[1]
k3 = k[2]
k4 = k[3]
k5 = k[4]
k6 = k[5]
Jacobian = np.array([[-k1, k2,       0, 0],
                     [k1, -(k2+k3), k4, 0],
                     [0, k3, -(k4+k5), k6],
                     [0, 0,       k5, -k6]])

print(Jacobian)
In [ ]:
# calculation time
time_start = 0
time_end = 10
NoOfSteps = 100
time = np.linspace(time_start,time_end,NoOfSteps)
In [ ]:
y1 = odeint(func1,y0,time)
y2 = odeint(func2,y0,time,args=(k,))
y3 = odeint(func3,y0,time,args=(k,))
y4 = odeint(func4,y0,time,args=(Jacobian,))
In [ ]:
print('shape of the outcome y1 =', np.shape(y1))
print('shape of the outcome y2 =', np.shape(y2))
print('shape of the outcome y3 =', np.shape(y3))
print('shape of the outcome y4 =', np.shape(y4))
In [ ]:
plt.figure(figsize=(6,4),dpi=100)
plt.tick_params(direction='in',labelsize=12)
plt.plot(time,y1[:,0],'r-',label='func1')
plt.plot(time,y2[:,0],'b-',label='func2')
plt.plot(time,y3[:,0],'g-',label='func3')
plt.plot(time,y4[:,0],'m-',label='func4')
plt.xlabel('Time [a.u.]',fontsize=12)
plt.ylabel('Conc. [a.u.]',fontsize=12)
plt.legend(loc='best',fontsize=10)
In [ ]:
plt.figure(figsize=(6,4),dpi=100)
plt.tick_params(direction='in',labelsize=12)
plt.plot(time,y1[:,0],'r-',label='A')
plt.plot(time,y1[:,1],'b-',label='B')
plt.plot(time,y1[:,2],'g-',label='C')
plt.plot(time,y1[:,3],'m-',label='D')
plt.xlabel('Time [a.u.]',fontsize=12)
plt.ylabel('Conc. [a.u.]',fontsize=12)
plt.legend(loc='best',fontsize=10)

Use of Dictionary

In [ ]:
def genJacobian(k):
    k1 = k['k1']
    k2 = k['k2']
    k3 = k['k3']
    k4 = k['k4']
    k5 = k['k5']
    k6 = k['k6']
    
    Jacobian = np.array([[-k1, k2,       0, 0],
                         [k1, -(k2+k3), k4, 0],
                         [0, k3, -(k4+k5), k6],
                         [0, 0,       k5, -k6]])
    
    return Jacobian
In [ ]:
kdict = {'k1':1,'k2':0.5,'k3':1.2,'k4':0.7,'k5':0.8,'k6':0.7}
J = genJacobian(kdict)

y4_1 = odeint(func4,y0,time,args=(J,))

plt.figure(figsize=(6,4),dpi=100)
plt.tick_params(direction='in',labelsize=12)
plt.plot(time,y4_1[:,0],'r-',label='A')
plt.plot(time,y4_1[:,1],'b-',label='B')
plt.plot(time,y4_1[:,2],'g-',label='C')
plt.plot(time,y4_1[:,3],'m-',label='D')
plt.xlabel('Time [a.u.]',fontsize=12)
plt.ylabel('Conc. [a.u.]',fontsize=12)
plt.legend(loc='best',fontsize=10)

Let's try something simpler

Creating your own library/package using .py file

In [ ]:
import functions as fn

y1 = odeint(fn.func1,y0,time)
y2 = odeint(fn.func2,y0,time,args=(k,))
y3 = odeint(fn.func3,y0,time,args=(k,))
y4 = odeint(fn.func4,y0,time,args=(Jacobian,))
In [ ]:
plt.figure(figsize=(6,4),dpi=100)
plt.tick_params(direction='in',labelsize=12)
plt.plot(time,y1[:,0],'r-',label='A')
plt.plot(time,y1[:,1],'b-',label='B')
plt.plot(time,y1[:,2],'g-',label='C')
plt.plot(time,y1[:,3],'m-',label='D')
plt.xlabel('Time [a.u.]',fontsize=12)
plt.ylabel('Conc. [a.u.]',fontsize=12)
plt.legend(loc='best',fontsize=10)

We are going to fit the curve using "scipy.optimize.curve_fit"

$\dfrac{d[Ca^{2+}]_i}{dt}$ = $\dfrac{-V_{max}}{1+\dfrac{k_d}{[Ca^{2+}]_i}} + LeakRate\times([Ca^{2+}]_{i,max}-[Ca^{2+}]_i$

  • $[Ca^{2+}]_i$ is the dependent variable
  • $V_{max}$: parameter, indicates the maximum extrusion rate of $[Ca^{2+}]_i$ via SERCA pump
  • $k_d$: parameter, is the soft threshold for the pump activation. If $[Ca^{2+}]_i$ is below the threshold then the whole denominator larger than numerator so the term is small. On the other hand, if $[Ca^{2+}]_i$ is above the threshold, then the whole $\dfrac{k_d}{[Ca^{2+}]_i}$ is small enough to result the denominator as zero so the whole term becomes $V_{max}$
  • LeakRate: parameter, determines how quick the $[Ca^{2+}]_i$ is being restored
  • $[Ca^{2+}]_{i,max}$: constant

Task: adjust the parameters to fit the curve

  1. manually
  2. via curve_fit
In [ ]:
## This is the experiment data: "Reference"
adtime = [0.,0.05263158,0.07894737,0.10526316,0.13157895,0.15789474,0.18421053,0.26315789,0.36842105,0.5,0.73684211,0.84210526,0.86842105]
adconc = [0.62,0.58941176,0.52313725,0.40078431,0.33960784,0.31411765, 0.27843137, 0.22745098, 0.17137255, 0.13058824, 0.10509804, 0.1, 0.1]

Manually fit the plot

  • This is where you probably have to guestimate the parameters manually.

In the middle of section, you will see 3 parameters:

  • Vmax_test
  • kd_test
  • leakRate_test

These are the parameters you want to make tweak to fit the equation to the experiment data

In [ ]:
### The expression of math equation you are interested in 
def func(Cai,t,Vmax,kd,leakRate):
    dCadt = -Vmax/(1+(kd/Cai)) + leakRate*(0.7-Cai)
    return dCadt

#### Tune this to get the best fit
Vmax_test = 5
kd_test = 0.1
leakRate_test = 2


####################################
Ca0 = adconc[0]
t = scipy.linspace(0,1,100)
####################################
Ca_estimated = odeint(func,Ca0,t,args=(Vmax_test,kd_test,leakRate_test,))

plt.figure(figsize=(6,6),dpi=100)
plt.tick_params(direction='in',labelsize=12)
plt.plot(adtime,adconc,'--om',label='Ref.')
plt.plot(t,Ca_estimated,'r-',label='Estimated')
plt.xlabel('Time(sec)',fontsize=12)
plt.ylabel('$[Ca^{2+}]_i$ (uM)',fontsize=12)
plt.legend(loc='best',fontsize=10)

Little fancy way to do this using "slider"

In this section, you will use a widget called "slider" so that instead of punching random values for each parameter, you will use slide bars. Python will automatically calculate and update the outcomes as you make adjustments.

  • This should work with Jupyter-Notebook, which is another platform provided by Anaconda.
In [ ]:
from ipywidgets import widgets, fixed, Layout ## Calling the package for slider 
from IPython.display import display
%matplotlib widget
In [ ]:
### The expression of math equation you are interested in 
def func(Cai,t,Vmax,kd,leakRate):
    # your differential equation 
    dCadt = -Vmax/(1+(kd/Cai)) + leakRate*(0.7-Cai)
    return dCadt


def runner(Vmax,kd,leakRate):

    ####################################
    Ca0 = adconc[0]
    t = scipy.linspace(0,1,100)
    ####################################
    Ca_estimated = odeint(func,Ca0,t,args=(Vmax,kd,leakRate,))

    plt.figure(figsize=(6,6),dpi=100)
    plt.tick_params(direction='in',labelsize=12)
    plt.plot(adtime,adconc,'--om',label='Ref.')
    plt.plot(t,Ca_estimated,'r-',label='Estimated')
    plt.xlabel('Time(sec)',fontsize=12)
    plt.ylabel('$[Ca^{2+}]_i$ (uM)',fontsize=12)
    plt.legend(loc='best',fontsize=10)
    
    return
In [ ]:
%%html
<style type='text/css'>
.widget-inline-hbox .widget-label {
      max-width: 250px;
      min-width: 250px;
}
</style>
In [ ]:
slider = widgets.interact(runner, isadaptive=fixed(True),
            Vmax=widgets.FloatSlider(min=0,max=20,step=0.1,value=5,description='Vmax',layout=Layout(width='70%'), continuous_update = True),
            kd=widgets.FloatSlider(min=0,max=10,step=0.05,value=0.1,description='kd',layout=Layout(width='70%'), continuous_update = True),
            leakRate=widgets.FloatSlider(min=0,max=10,step=0.1,value=2,description='leakRate',layout=Layout(width='70%'), continuous_update = True))

Fit the plot via scipy.optimize.curve_fit

In [ ]:
### Writing Platform of function to generate outcomes that you target
def fitfunc(t,Vmax, kd, leakRate):
    ## This is the actual function that is being solved
    def myode(Cai, t):
        dCadt = -Vmax/(1+(kd/Cai)) + leakRate*(0.7-Cai)
        return dCadt
    
    Ca0 = adconc[0]
    Casol = odeint(myode,Ca0,t)
    return Casol[:,0] # Outcome that will be compared 

##### INITIAL GUESS ######
guess = [10,0.5,0.1] ## Initial guess is important. If your guess is so wild, then fitting may fail.

##### Execution of Fitting Process #####
kfit,kcov = curve_fit(fitfunc,adtime,adconc,guess)
print(kfit) ## This is the fitted parameters. This is being printed 

tfit = np.linspace(0,1)
fit = fitfunc(tfit,kfit[0],kfit[1],kfit[2])  ## applying newly fitted parameters 

#### parameters before and after fitting 
## Before
Vmax_test1 = guess[0]
kd_test1 = guess[1]
leakRate_test1 = guess[2]
## After 
Vmax_test2 = kfit[0]
kd_test2 = kfit[1]
leakRate_test2 = kfit[2]

####################################
Ca0 = adconc[0]
t = scipy.linspace(0,1,100)
####################################
Ca_estimated1 = odeint(func,Ca0,t,args=(Vmax_test1,kd_test1,leakRate_test1,)) ### You are testing your initial guess for parameters before fitting
Ca_estimated2 = odeint(func,Ca0,t,args=(Vmax_test2,kd_test2,leakRate_test2,)) ### You are testing parameters fitted by Curve_fit -> You are repeating data generation of "fit"

plt.figure(figsize=(6,6),dpi=100)
plt.tick_params(direction='in',labelsize=12)
plt.plot(adtime,adconc,'--om',label='Ref.')
plt.plot(t,Ca_estimated1,'r-',label='with Guessed params')
plt.plot(t,Ca_estimated2,'g-',lw=3,label='with Fitted params')
plt.plot(tfit, fit, 'b-.', label='Fitted by curve_fit')
plt.xlabel('Time(sec)',fontsize=12)
plt.ylabel('$[Ca^{2+}]_i$ (uM)',fontsize=12)
plt.legend(loc='best',fontsize=10)

Easier version of Curve_fit example

In [5]:
def func(x, a, b, c):
     return a * np.exp(-b * x) + c
In [12]:
xdata1 = np.linspace(0, 4, 50)
y = func(xdata, 2.5, 1.3, 0.5)
np.random.seed(1729)
y_noise = 0.2 * np.random.normal(size=xdata.size)
ydata1 = y + y_noise
plt.plot(xdata1, ydata1, 'b-', label='data')
Out[12]:
[<matplotlib.lines.Line2D at 0x7fca711fe070>]
In [13]:
popt1, pcov2 = curve_fit(func, xdata1, ydata1)
print(popt1)
plt.plot(xdata1, func(xdata1, *popt1), 'r-',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
[2.55423706 1.35190947 0.47450618]
Out[13]:
[<matplotlib.lines.Line2D at 0x7fca711cd7c0>]
In [14]:
popt2, pcov2 = curve_fit(func, xdata1, ydata1, bounds=(0, [3., 1., 0.5]))
print(popt2)
plt.plot(xdata1, func(xdata1, *popt2), 'g--',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
[2.43708906 1.         0.35015434]
Out[14]:
[<matplotlib.lines.Line2D at 0x7fca711a0f40>]
In [16]:
plt.plot(xdata1, ydata1, 'b-', label='data')
plt.plot(xdata1, func(xdata1, *popt1), 'r-',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt1))
plt.plot(xdata1, func(xdata1, *popt2), 'g--',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt2))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
Out[16]:
<matplotlib.legend.Legend at 0x7fca7112e5e0>
In [ ]:
 
Notebooks AI
Notebooks AI Profile20060