本文整理汇总了Python中symfit.Fit.execute方法的典型用法代码示例。如果您正苦于以下问题:Python Fit.execute方法的具体用法?Python Fit.execute怎么用?Python Fit.execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类symfit.Fit
的用法示例。
在下文中一共展示了Fit.execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_simple_kinetics
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_simple_kinetics(self):
"""
Simple kinetics data to test fitting
"""
tdata = np.array([10, 26, 44, 70, 120])
adata = 10e-4 * np.array([44, 34, 27, 20, 14])
a, b, t = variables('a, b, t')
k, a0 = parameters('k, a0')
k.value = 0.01
# a0.value, a0.min, a0.max = 54 * 10e-4, 40e-4, 60e-4
a0 = 54 * 10e-4
model_dict = {
D(a, t): - k * a**2,
D(b, t): k * a**2,
}
ode_model = ODEModel(model_dict, initial={t: 0.0, a: a0, b: 0.0})
# Analytical solution
model = GradientModel({a: 1 / (k * t + 1 / a0)})
fit = Fit(model, t=tdata, a=adata)
fit_result = fit.execute()
fit = Fit(ode_model, t=tdata, a=adata, b=None, minimizer=MINPACK)
ode_result = fit.execute()
self.assertAlmostEqual(ode_result.value(k) / fit_result.value(k), 1.0, 4)
self.assertAlmostEqual(ode_result.stdev(k) / fit_result.stdev(k), 1.0, 4)
self.assertAlmostEqual(ode_result.r_squared / fit_result.r_squared, 1, 4)
fit = Fit(ode_model, t=tdata, a=adata, b=None)
ode_result = fit.execute()
self.assertAlmostEqual(ode_result.value(k) / fit_result.value(k), 1.0, 4)
self.assertAlmostEqual(ode_result.stdev(k) / fit_result.stdev(k), 1.0, 4)
self.assertAlmostEqual(ode_result.r_squared / fit_result.r_squared, 1, 4)
示例2: test_chained_min_signature
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_chained_min_signature(self):
"""
Test the automatic generation of the signature for ChainedMinimizer
"""
minimizers = [
BFGS, DifferentialEvolution, BFGS, DifferentialEvolution, BFGS
]
fit = Fit(self.model, self.xx, self.yy, self.ydata,
minimizer=minimizers)
names = [
'BFGS', 'DifferentialEvolution', 'BFGS_2',
'DifferentialEvolution_2', 'BFGS_3'
]
for name, param_name in zip(names, fit.minimizer.__signature__.parameters):
self.assertEqual(name, param_name)
# Check for equal lengths because zip is slippery that way
self.assertEqual(len(names), len(fit.minimizer.__signature__.parameters))
for param in fit.minimizer.__signature__.parameters.values():
self.assertEqual(param.kind, inspect_sig.Parameter.KEYWORD_ONLY)
# Make sure keywords end up at the right minimizer.
with self.assertRaises(TypeError):
# This is not a valid kwarg to DiffEvo, but it is to BFGS. Check if
# we really go by name of the Minimizer, not by order.
fit.execute(DifferentialEvolution={'return_all': False})
示例3: test_full_eval_range
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_full_eval_range(self):
"""
Test if ODEModels can be evaluated at t < t_initial.
A bit of a no news is good news test.
"""
tdata = np.array([0, 10, 26, 44, 70, 120])
adata = 10e-4 * np.array([54, 44, 34, 27, 20, 14])
a, b, t = variables('a, b, t')
k, a0 = parameters('k, a0')
k.value = 0.01
t0 = tdata[2]
a0 = adata[2]
b0 = 0.02729855 # Obtained from evaluating from t=0.
model_dict = {
D(a, t): - k * a**2,
D(b, t): k * a**2,
}
ode_model = ODEModel(model_dict, initial={t: t0, a: a0, b: b0})
fit = Fit(ode_model, t=tdata, a=adata, b=None)
ode_result = fit.execute()
self.assertGreater(ode_result.r_squared, 0.95, 4)
# Now start from a timepoint that is not in the t-array such that it
# triggers another pathway to be taken in integrating it.
# Again, no news is good news.
ode_model = ODEModel(model_dict, initial={t: t0 + 1e-5, a: a0, b: b0})
fit = Fit(ode_model, t=tdata, a=adata, b=None)
ode_result = fit.execute()
self.assertGreater(ode_result.r_squared, 0.95, 4)
示例4: test_known_solution
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_known_solution(self):
p, c1 = parameters('p, c1')
y, t = variables('y, t')
p.value = 3.0
model_dict = {
D(y, t): - p * y,
}
# Lets say we know the exact solution to this problem
sol = Model({y: exp(- p * t)})
# Generate some data
tdata = np.linspace(0, 3, 10001)
ydata = sol(t=tdata, p=3.22)[0]
ydata += np.random.normal(0, 0.005, ydata.shape)
ode_model = ODEModel(model_dict, initial={t: 0.0, y: ydata[0]})
fit = Fit(ode_model, t=tdata, y=ydata)
ode_result = fit.execute()
c1.value = ydata[0]
fit = Fit(sol, t=tdata, y=ydata)
fit_result = fit.execute()
self.assertAlmostEqual(ode_result.value(p) / fit_result.value(p), 1, 2)
self.assertAlmostEqual(ode_result.r_squared / fit_result.r_squared, 1, 4)
self.assertAlmostEqual(ode_result.stdev(p) / fit_result.stdev(p), 1, 3)
示例5: test_minimize
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_minimize(self):
"""
Tests maximizing a function with and without constraints, taken from the
scipy `minimize` tutorial. Compare the symfit result with the scipy
result.
https://docs.scipy.org/doc/scipy-0.18.1/reference/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize
"""
x = Parameter(value=-1.0)
y = Parameter(value=1.0)
# Use an unnamed Variable on purpose to test the auto-generation of names.
model = Model(2 * x * y + 2 * x - x ** 2 - 2 * y ** 2)
constraints = [
Ge(y - 1, 0), # y - 1 >= 0,
Eq(x**3 - y, 0), # x**3 - y == 0,
]
def func(x, sign=1.0):
""" Objective function """
return sign*(2*x[0]*x[1] + 2*x[0] - x[0]**2 - 2*x[1]**2)
def func_deriv(x, sign=1.0):
""" Derivative of objective function """
dfdx0 = sign*(-2*x[0] + 2*x[1] + 2)
dfdx1 = sign*(2*x[0] - 4*x[1])
return np.array([ dfdx0, dfdx1 ])
cons = (
{'type': 'eq',
'fun' : lambda x: np.array([x[0]**3 - x[1]]),
'jac' : lambda x: np.array([3.0*(x[0]**2.0), -1.0])},
{'type': 'ineq',
'fun' : lambda x: np.array([x[1] - 1]),
'jac' : lambda x: np.array([0.0, 1.0])})
# Unconstrained fit
res = minimize(func, [-1.0,1.0], args=(-1.0,), jac=func_deriv,
method='BFGS', options={'disp': False})
fit = Fit(model=- model)
self.assertIsInstance(fit.objective, MinimizeModel)
self.assertIsInstance(fit.minimizer, BFGS)
fit_result = fit.execute()
self.assertAlmostEqual(fit_result.value(x) / res.x[0], 1.0, 6)
self.assertAlmostEqual(fit_result.value(y) / res.x[1], 1.0, 6)
# Same test, but with constraints in place.
res = minimize(func, [-1.0,1.0], args=(-1.0,), jac=func_deriv,
constraints=cons, method='SLSQP', options={'disp': False})
from symfit.core.minimizers import SLSQP
fit = Fit(- model, constraints=constraints)
self.assertEqual(fit.constraints[0].constraint_type, Ge)
self.assertEqual(fit.constraints[1].constraint_type, Eq)
fit_result = fit.execute()
self.assertAlmostEqual(fit_result.value(x), res.x[0], 6)
self.assertAlmostEqual(fit_result.value(y), res.x[1], 6)
示例6: test_simple_sigma
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_simple_sigma(self):
"""
Make sure we produce the same results as scipy's curve_fit, with and
without sigmas, and compare the results of both to a known value.
"""
t_data = np.array([1.4, 2.1, 2.6, 3.0, 3.3])
y_data = np.array([10, 20, 30, 40, 50])
sigma = 0.2
n = np.array([5, 3, 8, 15, 30])
sigma_t = sigma / np.sqrt(n)
# We now define our model
y = Variable()
g = Parameter()
t_model = (2 * y / g)**0.5
fit = Fit(t_model, y_data, t_data) # , sigma=sigma_t)
fit_result = fit.execute()
# h_smooth = np.linspace(0,60,100)
# t_smooth = t_model(y=h_smooth, **fit_result.params)
# Lets with the results from curve_fit, no weights
popt_noweights, pcov_noweights = curve_fit(lambda y, p: (2 * y / p)**0.5, y_data, t_data)
self.assertAlmostEqual(fit_result.value(g), popt_noweights[0])
self.assertAlmostEqual(fit_result.stdev(g), np.sqrt(pcov_noweights[0, 0]))
# Same sigma everywere
fit = Fit(t_model, y_data, t_data, 0.0031, absolute_sigma=False)
fit_result = fit.execute()
popt_sameweights, pcov_sameweights = curve_fit(lambda y, p: (2 * y / p)**0.5, y_data, t_data, sigma=0.0031, absolute_sigma=False)
self.assertAlmostEqual(fit_result.value(g), popt_sameweights[0], 4)
self.assertAlmostEqual(fit_result.stdev(g), np.sqrt(pcov_sameweights[0, 0]), 4)
# Same weight everywere should be the same as no weight when absolute_sigma=False
self.assertAlmostEqual(fit_result.value(g), popt_noweights[0], 4)
self.assertAlmostEqual(fit_result.stdev(g), np.sqrt(pcov_noweights[0, 0]), 4)
# Different sigma for every point
fit = Fit(t_model, y_data, t_data, 0.1*sigma_t, absolute_sigma=False)
fit_result = fit.execute()
popt, pcov = curve_fit(lambda y, p: (2 * y / p)**0.5, y_data, t_data, sigma=.1*sigma_t)
self.assertAlmostEqual(fit_result.value(g), popt[0])
self.assertAlmostEqual(fit_result.stdev(g), np.sqrt(pcov[0, 0]))
# according to Mathematica
self.assertAlmostEqual(fit_result.value(g), 9.095, 3)
self.assertAlmostEqual(fit_result.stdev(g), 0.102, 3)
示例7: test_gaussian_2d_fitting
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_gaussian_2d_fitting(self):
"""
Tests fitting to a scalar gaussian function with 2 independent
variables. Very sensitive to initial guesses, and if they are chosen too
restrictive Fit actually throws a tantrum.
It therefore appears to be more sensitive than NumericalLeastSquares.
"""
mean = (0.6, 0.4) # x, y mean 0.6, 0.4
cov = [[0.2**2, 0], [0, 0.1**2]]
np.random.seed(0)
data = np.random.multivariate_normal(mean, cov, 100000)
# Insert them as y,x here as np fucks up cartesian conventions.
ydata, xedges, yedges = np.histogram2d(data[:, 0], data[:, 1], bins=100,
range=[[0.0, 1.0], [0.0, 1.0]])
xcentres = (xedges[:-1] + xedges[1:]) / 2
ycentres = (yedges[:-1] + yedges[1:]) / 2
# Make a valid grid to match ydata
xx, yy = np.meshgrid(xcentres, ycentres, sparse=False, indexing='ij')
x0 = Parameter(value=mean[0], min=0.0, max=1.0)
sig_x = Parameter(value=0.2, min=0.0, max=0.3)
y0 = Parameter(value=mean[1], min=0.0, max=1.0)
sig_y = Parameter(value=0.1, min=0.0, max=0.3)
A = Parameter(value=np.mean(ydata), min=0.0)
x = Variable('x')
y = Variable('y')
g = Variable('g')
model = Model({g: A * Gaussian(x, x0, sig_x) * Gaussian(y, y0, sig_y)})
fit = Fit(model, x=xx, y=yy, g=ydata)
fit_result = fit.execute()
self.assertAlmostEqual(fit_result.value(x0), np.mean(data[:, 0]), 3)
self.assertAlmostEqual(fit_result.value(y0), np.mean(data[:, 1]), 3)
self.assertAlmostEqual(np.abs(fit_result.value(sig_x)), np.std(data[:, 0]), 2)
self.assertAlmostEqual(np.abs(fit_result.value(sig_y)), np.std(data[:, 1]), 2)
self.assertGreaterEqual(fit_result.r_squared, 0.96)
# Compare with industry standard MINPACK
fit_std = Fit(model, x=xx, y=yy, g=ydata, minimizer=MINPACK)
fit_std_result = fit_std.execute()
self.assertAlmostEqual(fit_std_result.value(x0), fit_result.value(x0), 4)
self.assertAlmostEqual(fit_std_result.value(y0), fit_result.value(y0), 4)
self.assertAlmostEqual(fit_std_result.value(sig_x), fit_result.value(sig_x), 4)
self.assertAlmostEqual(fit_std_result.value(sig_y), fit_result.value(sig_y), 4)
self.assertAlmostEqual(fit_std_result.r_squared, fit_result.r_squared, 4)
示例8: test_fitting
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_fitting(self):
xdata = np.linspace(1,10,10)
ydata = 3*xdata**2
a = Parameter() #3.1, min=2.5, max=3.5
b = Parameter()
x = Variable()
new = a*x**b
fit = Fit(new, xdata, ydata, minimizer=MINPACK)
fit_result = fit.execute()
self.assertIsInstance(fit_result, FitResults)
self.assertAlmostEqual(fit_result.value(a), 3.0)
self.assertAlmostEqual(fit_result.value(b), 2.0)
self.assertIsInstance(fit_result.stdev(a), float)
self.assertIsInstance(fit_result.stdev(b), float)
self.assertIsInstance(fit_result.r_squared, float)
self.assertEqual(fit_result.r_squared, 1.0) # by definition since there's no fuzzyness
# Test several illegal ways to access the data.
self.assertRaises(AttributeError, getattr, *[fit_result.params, 'a_fdska'])
self.assertRaises(AttributeError, getattr, *[fit_result.params, 'c'])
self.assertRaises(AttributeError, getattr, *[fit_result.params, 'a_stdev_stdev'])
self.assertRaises(AttributeError, getattr, *[fit_result.params, 'a_stdev_'])
self.assertRaises(AttributeError, getattr, *[fit_result.params, 'a__stdev'])
示例9: test_fitting
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_fitting(self):
"""
Tests fitting with NumericalLeastSquares. Makes sure that the resulting
objects and values are of the right type, and that the fit_result does
not have unexpected members.
"""
xdata = np.linspace(1, 10, 10)
ydata = 3*xdata**2
a = Parameter() # 3.1, min=2.5, max=3.5
b = Parameter()
x = Variable()
new = a*x**b
fit = Fit(new, xdata, ydata, minimizer=MINPACK)
fit_result = fit.execute()
self.assertIsInstance(fit_result, FitResults)
self.assertAlmostEqual(fit_result.value(a), 3.0)
self.assertAlmostEqual(fit_result.value(b), 2.0)
self.assertIsInstance(fit_result.stdev(a), float)
self.assertIsInstance(fit_result.stdev(b), float)
self.assertIsInstance(fit_result.r_squared, float)
self.assertEqual(fit_result.r_squared, 1.0) # by definition since there's no fuzzyness
示例10: test_gaussian_fitting
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_gaussian_fitting(self):
"""
Tests fitting to a gaussian function and fit_result.params unpacking.
"""
xdata = 2*np.random.rand(10000) - 1 # random betwen [-1, 1]
ydata = 5.0 * scipy.stats.norm.pdf(xdata, loc=0.0, scale=1.0)
x0 = Parameter()
sig = Parameter()
A = Parameter()
x = Variable()
g = A * Gaussian(x, x0, sig)
fit = Fit(g, xdata, ydata)
fit_result = fit.execute()
self.assertAlmostEqual(fit_result.value(A), 5.0)
self.assertAlmostEqual(np.abs(fit_result.value(sig)), 1.0)
self.assertAlmostEqual(fit_result.value(x0), 0.0)
# raise Exception([i for i in fit_result.params])
sexy = g(x=2.0, **fit_result.params)
ugly = g(
x=2.0,
x0=fit_result.value(x0),
A=fit_result.value(A),
sig=fit_result.value(sig),
)
self.assertEqual(sexy, ugly)
示例11: test_vector_fitting
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_vector_fitting(self):
"""
Tests fitting to a 3 component vector valued function, without bounds
or guesses.
"""
a, b, c = parameters('a, b, c')
a_i, b_i, c_i = variables('a_i, b_i, c_i')
model = {a_i: a, b_i: b, c_i: c}
xdata = np.array([
[10.1, 9., 10.5, 11.2, 9.5, 9.6, 10.],
[102.1, 101., 100.4, 100.8, 99.2, 100., 100.8],
[71.6, 73.2, 69.5, 70.2, 70.8, 70.6, 70.1],
])
fit = Fit(
model=model,
a_i=xdata[0],
b_i=xdata[1],
c_i=xdata[2],
minimizer = MINPACK
)
fit_result = fit.execute()
self.assertAlmostEqual(fit_result.value(a) / 9.985691, 1.0, 5)
self.assertAlmostEqual(fit_result.value(b) / 1.006143e+02, 1.0, 4)
self.assertAlmostEqual(fit_result.value(c) / 7.085713e+01, 1.0, 5)
示例12: test_vector_fitting_bounds
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_vector_fitting_bounds(self):
"""
Tests fitting to a 3 component vector valued function, with bounds.
"""
a, b, c = parameters('a, b, c')
a.min = 0
a.max = 25
b.min = 0
b.max = 500
a_i, b_i, c_i = variables('a_i, b_i, c_i')
model = {a_i: a, b_i: b, c_i: c}
xdata = np.array([
[10.1, 9., 10.5, 11.2, 9.5, 9.6, 10.],
[102.1, 101., 100.4, 100.8, 99.2, 100., 100.8],
[71.6, 73.2, 69.5, 70.2, 70.8, 70.6, 70.1],
])
fit = Fit(
model=model,
a_i=xdata[0],
b_i=xdata[1],
c_i=xdata[2],
)
fit_result = fit.execute()
self.assertAlmostEqual(fit_result.value(a), np.mean(xdata[0]), 4)
self.assertAlmostEqual(fit_result.value(b), np.mean(xdata[1]), 4)
self.assertAlmostEqual(fit_result.value(c), np.mean(xdata[2]), 4)
示例13: test_likelihood_fitting_exponential
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_likelihood_fitting_exponential(self):
"""
Fit using the likelihood method.
"""
b = Parameter(value=4, min=3.0)
x, y = variables('x, y')
pdf = {y: Exp(x, 1/b)}
# Draw points from an Exp(5) exponential distribution.
np.random.seed(100)
xdata = np.random.exponential(5, 1000000)
# Expected parameter values
mean = np.mean(xdata)
stdev = np.std(xdata)
mean_stdev = stdev / np.sqrt(len(xdata))
with self.assertRaises(NotImplementedError):
fit = Fit(pdf, x=xdata, sigma_y=2.0, objective=LogLikelihood)
fit = Fit(pdf, xdata, objective=LogLikelihood)
fit_result = fit.execute()
self.assertAlmostEqual(fit_result.value(b) / mean, 1, 3)
self.assertAlmostEqual(fit_result.value(b) / stdev, 1, 3)
self.assertAlmostEqual(fit_result.stdev(b) / mean_stdev, 1, 3)
示例14: test_likelihood_fitting_gaussian
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_likelihood_fitting_gaussian(self):
"""
Fit using the likelihood method.
"""
mu, sig = parameters('mu, sig')
sig.min = 0.01
sig.value = 3.0
mu.value = 50.
x = Variable()
pdf = Gaussian(x, mu, sig)
np.random.seed(10)
xdata = np.random.normal(51., 3.5, 10000)
# Expected parameter values
mean = np.mean(xdata)
stdev = np.std(xdata)
mean_stdev = stdev/np.sqrt(len(xdata))
fit = Fit(pdf, xdata, objective=LogLikelihood)
fit_result = fit.execute()
self.assertAlmostEqual(fit_result.value(mu) / mean, 1, 6)
self.assertAlmostEqual(fit_result.stdev(mu) / mean_stdev, 1, 3)
self.assertAlmostEqual(fit_result.value(sig) / np.std(xdata), 1, 6)
示例15: test_constraint_types
# 需要导入模块: from symfit import Fit [as 别名]
# 或者: from symfit.Fit import execute [as 别名]
def test_constraint_types(self):
x = Parameter(value=-1.0)
y = Parameter(value=1.0)
z = Variable()
model = Model({z: 2*x*y + 2*x - x**2 - 2*y**2})
# These types are not allowed constraints.
for relation in [Lt, Gt, Ne]:
with self.assertRaises(ModelError):
Fit(model, constraints=[relation(x, y)])
# Should execute without problems.
for relation in [Eq, Ge, Le]:
Fit(model, constraints=[relation(x, y)])
fit = Fit(model, constraints=[Le(x, y)])
# Le should be transformed to Ge
self.assertIs(fit.constraints[0].constraint_type, Ge)
# Redo the standard test as a Le
constraints = [
Le(- y + 1, 0), # y - 1 >= 0,
Eq(x**3 - y, 0), # x**3 - y == 0,
]
std_constraints = [
Ge(y - 1, 0), # y - 1 >= 0,
Eq(x**3 - y, 0), # x**3 - y == 0,
]
fit = Fit(- model, constraints=constraints)
std_fit = Fit(- model, constraints=std_constraints)
self.assertEqual(fit.constraints[0].constraint_type, Ge)
self.assertEqual(fit.constraints[1].constraint_type, Eq)
self.assertEqual(fit.constraints[0].params, [x, y])
self.assertEqual(fit.constraints[1].params, [x, y])
self.assertEqual(fit.constraints[0].jacobian_model.params, [x, y])
self.assertEqual(fit.constraints[1].jacobian_model.params, [x, y])
self.assertEqual(fit.constraints[0].hessian_model.params, [x, y])
self.assertEqual(fit.constraints[1].hessian_model.params, [x, y])
self.assertEqual(fit.constraints[0].__signature__,
fit.constraints[1].__signature__)
fit_result = fit.execute()
std_result = std_fit.execute()
self.assertAlmostEqual(fit_result.value(x), std_result.value(x))
self.assertAlmostEqual(fit_result.value(y), std_result.value(y))