Let's say you only want to optimize a few parameters in a function - not all of them.
In this case, you should pass the rest of the parameters through arguments.
Example:
The below function needs the data (time vector and observation vector) passed to it
def freqfitscore(inputs,timevec,obsvec):
Show full code for function
import math
import numpy as np
def freqfitscore(inputs,timevec,obsvec):
R=inputs[0]
fo=inputs[1]
def freq(t,fo,R):
#a:make sure exponential isn't too large
ex=-R*t
if ex>700.0:
ex=700.0
a=math.exp(ex)
#b: second term
b=(1.0-fo)
#dm: write full denominator and make sure not zero
dm=fo+b*a
if dm==0:
return 0.99
else:
return fo/dm
predvec=[freq(t,fo,R) for t in timevec]
predvec=np.array(predvec)
diff=(obsvec-predvec)
diffsq=diff*diff
return sum(diffsq)
We import the function as "score" and pass the data to it during the optimization by using the arguments slot
import numpy as np
from scipy.optimize import fmin
from freq_function import freqfitscore as score
#Data
#===============================================================================
##time points of each set of yes and no experiments (zeroed)
x=[0.0, 39.0, 82.0, 186.0, 255.0, 331.0]
#creating percentage of positive hits for each set
p=[0.0, 0.0, 0.05263157894736842, 0.42105263157894735, 0.8571428571428571, 0.9285714285714286]
#==================================================================================
#score a fit
timevec=np.array(x)
obsvec=np.array(p)
guess=(0.8,0.2)
a=fmin(score,guess,args=(timevec,obsvec),full_output=1)
No comments:
Post a Comment