本文整理汇总了Python中scipy.optimize.minimize_scalar方法的典型用法代码示例。如果您正苦于以下问题:Python optimize.minimize_scalar方法的具体用法?Python optimize.minimize_scalar怎么用?Python optimize.minimize_scalar使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.optimize
的用法示例。
在下文中一共展示了optimize.minimize_scalar方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _loglik_boxcox
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def _loglik_boxcox(self, x, bounds, options={'maxiter': 25}):
"""
Taken from the Stata manual on Box-Cox regressions, where this is the
special case of 'lhs only'. As an estimator for the variance, the
sample variance is used, by means of the well-known formula.
Parameters
----------
x : array_like
options : dict
The options (as a dict) to be passed to the optimizer.
"""
sum_x = np.sum(np.log(x))
nobs = len(x)
def optim(lmbda):
y, lmbda = self.transform_boxcox(x, lmbda)
return (1 - lmbda) * sum_x + (nobs / 2.) * np.log(np.var(y))
res = minimize_scalar(optim,
bounds=bounds,
method='bounded',
options=options)
return res.x
示例2: estimate_mode
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def estimate_mode(acc):
""" Estimate the mode of a set of float values between 0 and 1.
:param acc: Data.
:returns: The mode of the sample
:rtype: float
"""
# Taken from sloika.
if len(acc) > 1:
da = gaussian_kde(acc)
optimization_result = minimize_scalar(lambda x: -da(x), bounds=(0, 1), method='brent')
if optimization_result.success:
try:
mode = optimization_result.x[0]
except IndexError:
mode = optimization_result.x
except TypeError:
mode = optimization_result.x
else:
sys.stderr.write("Mode computation failed")
mode = 0
else:
mode = acc[0]
return mode
示例3: fit_z
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def fit_z(locs, info, calibration, magnification_factor, filter=2):
cx = _np.array(calibration["X Coefficients"])
cy = _np.array(calibration["Y Coefficients"])
z = _np.zeros_like(locs.x)
square_d_zcalib = _np.zeros_like(z)
sx = locs.sx
sy = locs.sy
for i in range(len(z)):
result = _minimize_scalar(_fit_z_target, args=(sx[i], sy[i], cx, cy))
z[i] = result.x
square_d_zcalib[i] = result.fun
z *= magnification_factor
locs = _lib.append_to_rec(locs, z, "z")
locs = _lib.append_to_rec(locs, _np.sqrt(square_d_zcalib), "d_zcalib")
locs = _lib.ensure_sanity(locs, info)
return filter_z_fits(locs, filter)
示例4: optimize_Tc
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def optimize_Tc(self):
'''
determines the coalescent time scale that optimizes the coalescent likelihood of the tree
'''
from scipy.optimize import minimize_scalar
initial_Tc = self.Tc
def cost(Tc):
self.set_Tc(Tc)
return -self.total_LH()
sol = minimize_scalar(cost, bounds=[ttconf.TINY_NUMBER,10.0])
if "success" in sol and sol["success"]:
self.set_Tc(sol['x'])
else:
self.logger("merger_models:optimize_Tc: optimization of coalescent time scale failed: " + str(sol), 0, warn=True)
self.set_Tc(initial_Tc.y, T=initial_Tc.x)
示例5: bruteforce_isotropic_relax
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def bruteforce_isotropic_relax(eptm, geom, model):
def to_minimize(scale):
return scaled_unscaled(model.compute_energy, scale, eptm, geom, args=[eptm])
optim_res = optimize.minimize_scalar(
to_minimize, method="bounded", bounds=[1e-6, 1e2]
)
if optim_res["success"]:
log.info("Scaling by factor {:.3f}".format(optim_res["x"]))
scale = optim_res["x"]
geom.scale(eptm, scale, eptm.coords)
geom.update_all(eptm)
else:
warnings.warn("Optimisation failed")
return optim_res
示例6: fit_E_binom
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def fit_E_binom(nd, na, noprint=False, method='c', **kwargs):
"""Fit the E with MLE using binomial distribution.
method ('a','b', or 'c') choose how to handle negative (nd,na) values.
"""
assert method in ['a', 'b', 'c']
nd, na = np.round(nd).astype(int), np.round(na).astype(int)
# The binomial distribution can not handle negative values
# so we must find a way to "remove" the negativa values
# a. remove bursts with neg. values, but we can skew the fit
# b. remove bursts with nd < nd[na<0].max(), but few bursts left
# c. remove bursts with na+nd < max(nd[na<0].max(),na[nd<0].max())
# giving a bit more bursts
# NOTE: b and c have corner cases in which there are neg. bursts left
pos_bursts = (nd>=0)*(na>=0)
if (-pos_bursts).any():
if not noprint: print("WARNING: Discarding negative burst sizes.")
if method == 'a':
# a. remove bursts with neg. values
nd, na = nd[pos_bursts], na[pos_bursts]
elif method == 'b':
# b. Cut all the part with na<0 to have a less skewed estimation
if (na < 0).any():
nd_min = nd[na<0].max()
nd, na = nd[nd>nd_min], na[nd>nd_min]
elif method == 'c':
# c. remove bursts with na+nd < max(nd[na<0].max(),na[nd<0].max())
nt_min = 0
if (na < 0).any():
nt_min = nd[na<0].max()
if (nd < 0).any():
nt_min = max([na[nd<0].max(), nt_min])
nd, na = nd[nd+na>nt_min], na[nd+na>nt_min]
if not noprint: print(" - Bursts left:", nd.size)
assert (nd>=0).all() and (na>=0).all()
min_kwargs = dict(bounds=(0,1), method='bounded',
options={'disp':1, 'xtol': 1e-6})
min_kwargs.update(**kwargs)
res = minimize_scalar(log_likelihood_binom, args=(nd,na), **min_kwargs)
return res.x
示例7: fit_E_poisson_nt
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def fit_E_poisson_nt(nd, na, bg_a, **kwargs):
"""Fit the E using MLE with na extracted from a Poisson.
"""
min_kwargs = dict(bounds=(-0.1,1.1), method='bounded',
options={'disp':1, 'xtol': 1e-6})
min_kwargs.update(**kwargs)
res = minimize_scalar(log_likelihood_poisson_nt, args=(nd, na, bg_a),
**min_kwargs)
E = res.x
return E
示例8: fit_E_poisson_na
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def fit_E_poisson_na(nd, na, bg_a, **kwargs):
"""Fit the E using MLE with na extracted from a Poisson.
"""
min_kwargs = dict(bounds=(-0.1,1.1), method='bounded',
options={'disp':1, 'xtol': 1e-6})
min_kwargs.update(**kwargs)
res = minimize_scalar(log_likelihood_poisson_na, args=(nd, na, bg_a),
**min_kwargs)
E = res.x
return E
示例9: fit_E_poisson_nd
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def fit_E_poisson_nd(nd, na, bg_d, **kwargs):
"""Fit the E using MLE with nd extracted from a Poisson.
"""
min_kwargs = dict(bounds=(-0.1,1.1), method='bounded',
options={'disp':1, 'xtol': 1e-6})
min_kwargs.update(**kwargs)
res = minimize_scalar(log_likelihood_poisson_nd, args=(nd, na, bg_d),
**min_kwargs)
E = res.x
return E
示例10: updateShareLimit
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def updateShareLimit(self):
'''
Creates the attribute ShareLimit, representing the limiting lower bound of
risky portfolio share as mNrm goes to infinity.
Parameters
----------
None
Returns
-------
None
'''
if 'RiskyDstn' in self.time_vary:
self.ShareLimit = []
for t in range(self.T_cycle):
RiskyDstn = self.RiskyDstn[t]
temp_f = lambda s : -((1.-self.CRRA)**-1)*np.dot((self.Rfree + s*(RiskyDstn.X-self.Rfree))**(1.-self.CRRA), RiskyDstn.pmf)
SharePF = minimize_scalar(temp_f, bounds=(0.0, 1.0), method='bounded').x
self.ShareLimit.append(SharePF)
self.addToTimeVary('ShareLimit')
else:
RiskyDstn = self.RiskyDstn
temp_f = lambda s : -((1.-self.CRRA)**-1)*np.dot((self.Rfree + s*(RiskyDstn.X-self.Rfree))**(1.-self.CRRA), RiskyDstn.pmf)
SharePF = minimize_scalar(temp_f, bounds=(0.0, 1.0), method='bounded').x
self.ShareLimit = SharePF
self.addToTimeInv('ShareLimit')
示例11: test_minimize_scalar_custom
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def test_minimize_scalar_custom(self):
# This function comes from the documentation example.
def custmin(fun, bracket, args=(), maxfev=None, stepsize=0.1,
maxiter=100, callback=None, **options):
bestx = (bracket[1] + bracket[0]) / 2.0
besty = fun(bestx)
funcalls = 1
niter = 0
improved = True
stop = False
while improved and not stop and niter < maxiter:
improved = False
niter += 1
for testx in [bestx - stepsize, bestx + stepsize]:
testy = fun(testx, *args)
funcalls += 1
if testy < besty:
besty = testy
bestx = testx
improved = True
if callback is not None:
callback(bestx)
if maxfev is not None and funcalls >= maxfev:
stop = True
break
return optimize.OptimizeResult(fun=besty, x=bestx, nit=niter,
nfev=funcalls, success=(niter > 1))
res = optimize.minimize_scalar(self.fun, bracket=(0, 4), method=custmin,
options=dict(stepsize=0.05))
assert_allclose(res.x, self.solution, atol=1e-6)
示例12: test_minimize_scalar_coerce_args_param
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def test_minimize_scalar_coerce_args_param(self):
# Regression test for gh-3503
optimize.minimize_scalar(self.fun, args=1.5)
示例13: u1_peak
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def u1_peak(self, k):
T = k * self.Tr
self.z.cost(T)
self.z.T = T
self.z.p = self.z.p.reshape((-1, self.z.order + 1))
bnds = self.get_bounds(self.u1, k)
u1_res = minimize_scalar(lambda t: -self.u1(t), bounds=bnds, method='bounded')
self.peaks[0] = np.abs(self.u1(u1_res.x))
return self.peaks[0]
示例14: theta_peak
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def theta_peak(self, k):
T = k * self.Tr
self.x.cost(T)
self.x.T = T
self.x.p = self.x.p.reshape((-1, self.x.order + 1))
bnds = self.get_bounds(lambda t: np.abs(self.theta(t)), k)
theta_res = minimize_scalar(lambda t: -np.abs(self.theta(t)), bounds=bnds, method='bounded')
self.peaks[3] = np.abs(self.theta(theta_res.x))
return self.peaks[3]
示例15: phi_peak
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import minimize_scalar [as 别名]
def phi_peak(self, k):
T = k * self.Tr
self.y.cost(T)
self.y.T = T
self.y.p = self.y.p.reshape((-1, self.y.order + 1))
bnds = self.get_bounds(lambda t: np.abs(self.phi(t)), k)
phi_res = minimize_scalar(lambda t: -np.abs(self.phi(t)), bounds=bnds, method='bounded')
self.peaks[4] = np.abs(self.phi(phi_res.x))
return self.peaks[4]
# Returns a set of bounds for the minimizer to use. Necessary for accurate
# minimization of non-convex functions such as u1, u2, u3, and u4. This is
# a BRUTE FORCE method. We take rezo samples per piecewise polynomial
# segment, find the time which results in the maximum, and return the two
# time samples adjacent to that time.