当前位置: 首页>>代码示例>>Python>>正文


Python optimize.fmin方法代码示例

本文整理汇总了Python中scipy.optimize.fmin方法的典型用法代码示例。如果您正苦于以下问题:Python optimize.fmin方法的具体用法?Python optimize.fmin怎么用?Python optimize.fmin使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.optimize的用法示例。


在下文中一共展示了optimize.fmin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: gammamomentcond2

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def gammamomentcond2(distfn, params, mom2, quantile=None):
    '''estimate distribution parameters based method of moments (mean,
    variance) for distributions with 1 shape parameter and fixed loc=0.

    Returns
    -------
    difference : array
        difference between theoretical and empirical moments

    Notes
    -----
    first test version, quantile argument not used

    The only difference to previous function is return type.

    '''
    alpha, scale = params
    mom2s = distfn.stats(alpha, 0.,scale)
    return np.array(mom2)-mom2s



######### fsolve doesn't move in small samples, fmin not very accurate 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:25,代码来源:estimators.py

示例2: _compute_reg_bw

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def _compute_reg_bw(self, bw):
        if not isinstance(bw, string_types):
            self._bw_method = "user-specified"
            return np.asarray(bw)
        else:
            # The user specified a bandwidth selection method e.g. 'cv_ls'
            self._bw_method = bw
            res = self.bw_func[bw]
            X = np.std(self.exog, axis=0)
            h0 = 1.06 * X * \
                 self.nobs ** (- 1. / (4 + np.size(self.exog, axis=1)))

            func = self.est[self.reg_type]
            bw_estimated = optimize.fmin(res, x0=h0, args=(func, ),
                                         maxiter=1e3, maxfun=1e3, disp=0)
            return bw_estimated 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:18,代码来源:kernel_regression.py

示例3: _cv_ls

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def _cv_ls(self):
        r"""
        Returns the cross-validation least squares bandwidth parameter(s).

        Notes
        -----
        For more details see pp. 16, 27 in Ref. [1] (see module docstring).

        Returns the value of the bandwidth that maximizes the integrated mean
        square error between the estimated and actual distribution.  The
        integrated mean square error (IMSE) is given by:

        .. math:: \int\left[\hat{f}(x)-f(x)\right]^{2}dx

        This is the general formula for the IMSE.  The IMSE differs for
        conditional (``KDEMultivariateConditional``) and unconditional
        (``KDEMultivariate``) kernel density estimation.
        """
        h0 = self._normal_reference()
        bw = optimize.fmin(self.imse, x0=h0, maxiter=1e3, maxfun=1e3, disp=0,
                           xtol=1e-3)
        bw = self._set_bw_bounds(bw)  # bound bw if necessary
        return bw 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:25,代码来源:_kernel_base.py

示例4: get_min

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def get_min(self, x0=None, **kwds):
        """Return [x,y] where z(x,y) = min(z) by minimizing z(x,y) w/
        scipy.optimize.fmin().

        Parameters
        ----------
        x0 : sequence, length (2,), optional
            Initial guess. If None then use the data grid point with the
            smallest `z` value.

        Returns
        -------
        [xmin, ymin]: 1d array (2,)
        """
        _kwds = dict(disp=0, xtol=1e-12, ftol=1e-8, maxfun=1e4, maxiter=1e4)
        _kwds.update(kwds)
        if x0 is None:
            idx0 = self.values.argmin()
            x0 = [self.xx[idx0], self.yy[idx0]]
        xopt = optimize.fmin(self, x0, **_kwds)
        return xopt 
开发者ID:elcorto,项目名称:pwtools,代码行数:23,代码来源:num.py

示例5: test_neldermead_initial_simplex_bad

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def test_neldermead_initial_simplex_bad(self):
        # Check it fails with a bad simplices
        bad_simplices = []

        simplex = np.zeros((3, 2))
        simplex[...] = self.startparams[:2]
        for j in range(2):
            simplex[j+1,j] += 0.1
        bad_simplices.append(simplex)

        simplex = np.zeros((3, 3))
        bad_simplices.append(simplex)

        for simplex in bad_simplices:
            if self.use_wrapper:
                opts = {'maxiter': self.maxiter, 'disp': False,
                        'return_all': False, 'initial_simplex': simplex}
                assert_raises(ValueError,
                              optimize.minimize, self.func, self.startparams, args=(),
                              method='Nelder-mead', options=opts)
            else:
                assert_raises(ValueError, optimize.fmin, self.func, self.startparams,
                              args=(), maxiter=self.maxiter,
                              full_output=True, disp=False, retall=False,
                              initial_simplex=simplex) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:27,代码来源:test_optimize.py

示例6: test_minimize_l_bfgs_b_maxfun_interruption

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def test_minimize_l_bfgs_b_maxfun_interruption(self):
        # gh-6162
        f = optimize.rosen
        g = optimize.rosen_der
        values = []
        x0 = np.ones(7) * 1000

        def objfun(x):
            value = f(x)
            values.append(value)
            return value

        # Look for an interesting test case.
        # Request a maxfun that stops at a particularly bad function
        # evaluation somewhere between 100 and 300 evaluations.
        low, medium, high = 30, 100, 300
        optimize.fmin_l_bfgs_b(objfun, x0, fprime=g, maxfun=high)
        v, k = max((y, i) for i, y in enumerate(values[medium:]))
        maxfun = medium + k
        # If the minimization strategy is reasonable,
        # the minimize() result should not be worse than the best
        # of the first 30 function evaluations.
        target = min(values[:low])
        xmin, fmin, d = optimize.fmin_l_bfgs_b(f, x0, fprime=g, maxfun=maxfun)
        assert_array_less(fmin, target) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:27,代码来源:test_optimize.py

示例7: validate_models

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def validate_models(self, n_users, n_debug=None):
        df_train, df_val = self.load_train_val(n_users, n_debug=n_debug)

        preds_mat = np.vstack([model.fit_and_predict(df_train, df_val, validate=True) for model in self.models]).T

        def opt_coefs(coefs):
            preds = preds_mat.dot(coefs)
            df_val["preds"] = preds
            mrr = mrr_fast(df_val, "preds")
            print(mrr, coefs)
            return -mrr

        best_coefs = fmin(opt_coefs, [model.weight for model in self.models])
        best_coefs = fmin_powell(opt_coefs, best_coefs)

        preds = preds_mat.dot(best_coefs)
        df_val["click_proba"] = preds
        print("MRR {:4f}".format(mrr_fast(df_val, "click_proba")))
        print("Best coefs: ", best_coefs) 
开发者ID:logicai-io,项目名称:recsys2019,代码行数:21,代码来源:model_utils.py

示例8: compute_reference_frame

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def compute_reference_frame(self,epipole,F):
		'''
		Method to compute the reference frame of the reconstruction (i.e. plane at infinity in an affine or metric space).
		Args: 
			epipole: the epipole
			F: the fundamental matrix
		Returns:
			p: the reference plane
			h: the homography [e]xF

		'''
		H=self._eg_utils.compute_homography(epipole,F)	#compute the homography [e]xF 
		# get the reference plane 
		p = np.sum(np.divide(np.eye(3)-H, np.transpose(np.asarray([epipole, epipole, epipole]))),axis=0)/3
		# adjust reference plane to make the first two projection matrices as equal as possible
		p=fmin(self.init_plane,np.append(p,1),xtol=1e-25,ftol=1e-25,args=(H.real,epipole.real));
		p=p[0:3]
		return p, H 
开发者ID:nbarba,项目名称:py3DRec,代码行数:20,代码来源:uncalibrated_rec.py

示例9: Get_RpRs

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def Get_RpRs(d, **kwargs):
    '''
    Returns the value of the planet radius over the stellar radius
    for a given depth :py:obj:`d`, given
    the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`.

    '''
    if ps is None:
            raise Exception("Unable to import `pysyzygy`.")

    def Depth(RpRs, **kwargs):
        return 1 - ps.Transit(RpRs=RpRs, **kwargs)([kwargs.get('t0', 0.)])

    def DiffSq(r):
        return 1.e10 * (d - Depth(r, **kwargs)) ** 2

    return fmin(DiffSq, [np.sqrt(d)], disp=False) 
开发者ID:rodluger,项目名称:everest,代码行数:19,代码来源:transit.py

示例10: Get_rhos

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def Get_rhos(dur, **kwargs):
    '''
    Returns the value of the stellar density for a given transit
    duration :py:obj:`dur`, given
    the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`.

    '''
    if ps is None:
            raise Exception("Unable to import `pysyzygy`.")

    assert dur >= 0.01 and dur <= 0.5, "Invalid value for the duration."

    def Dur(rhos, **kwargs):
        t0 = kwargs.get('t0', 0.)
        time = np.linspace(t0 - 0.5, t0 + 0.5, 1000)
        try:
            t = time[np.where(ps.Transit(rhos=rhos, **kwargs)(time) < 1)]
        except:
            return 0.
        return t[-1] - t[0]

    def DiffSq(rhos):
        return (dur - Dur(rhos, **kwargs)) ** 2

    return fmin(DiffSq, [0.2], disp=False) 
开发者ID:rodluger,项目名称:everest,代码行数:27,代码来源:transit.py

示例11: fit_minic

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def fit_minic(self):
        #this doesn't make sense, since number of parameters stays unchanged
        #need leave-one-out, gcv; or some penalization for weak priors
        #added extra penalization for lambd
        def get_bic(lambd):
            #return self.fit(lambd).bic #+lambd #+ 1./lambd  #added 1/lambd for checking
            #return self.fit(lambd).gcv()
            #return self.fit(lambd).cv()
            return self.fit(lambd).aicc()

        from scipy import optimize
        lambd = optimize.fmin(get_bic, 1.)
        return lambd

#TODO:
#I need the hatmatrix in the model if I want to do iterative fitting, e.g. GCV
#move to model or use it from a results instance inside the model,
#    each call to fit returns results instance 
开发者ID:nccgroup,项目名称:Splunking-Crime,代码行数:20,代码来源:penalized.py

示例12: isf

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def isf(STAT, alpha, df, resels, n, Q=None, version='spm12'):
	'''
	Inverse survival function
	'''
	if isinstance(alpha, (int,float)):
		alpha       = [alpha]
	zstar = []
	for aaa in alpha:
		z0    = _approx_threshold(STAT, aaa, df, resels, n)
		fn    = lambda x : (rft(1, 0, STAT, x[0], df, resels, n, Q, False, version)[0] - aaa)**2
		zzz   = optimize.fmin(fn, z0, xtol=1e-9, disp=0)[0]
		zstar.append(zzz)
	return np.asarray(zstar)




################################
# Convienence classes
################################ 
开发者ID:0todd0000,项目名称:spm1d,代码行数:22,代码来源:prob.py

示例13: expected_loss_for_range

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def expected_loss_for_range(estimate_range, true_s, function='absolute', u=1,o=1,u_f=1,o_f=1, r=1):
    """Function to attain expected loss and Bayes action based on an absolute-error or
           squared error-loss function for a defined range of estimates.

                Args:
                    estimate_range (np.array): Range of value estimates.
                    true_s (np.array): Array of possible true value occurrences (from a probability distribution)
                    u (int or float, optional): Underestimation re-weighting factor.
                    o (int or float, optional): Overestimation re-weighting factor.
                    u_f (int or float, optional): Fatal underestimation re-weighting factor.
                    o_f (int or float, optional): Fatal overestimation re-weighting factor.
                    r (int, float or np.array, optional): Risk-affinity re-weighting factor.
                Returns:
                    [0]: Expected loss for the range of estimates.
                    [1]: Bayes action (estimate with minimal expected loss)
                    [2]: Expected loss of Bayes action.
        """
    expected_loss_s = lambda estimate_s, r: expected_loss_for_estimate(estimate_s, true_s, function, u, o, u_f, o_f, r)
    loss_e = [expected_loss_s(e, r) for e in estimate_range]
    bayes_action = sop.fmin(expected_loss_s, -40, args=(r,), disp=False)
    bayes_action_loss_e = expected_loss_s(bayes_action, r)
    return loss_e, bayes_action, bayes_action_loss_e 
开发者ID:cgre-aachen,项目名称:gempy,代码行数:24,代码来源:decision_making.py

示例14: rlocfind

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def rlocfind(self, poleloc):
        self.poleloc = poleloc
        kinit,pinit = _k_poles(self,poleloc)
        k = fmin(self.opt,[kinit])[0]
        poles = self._RLFindRoots([k])
        poles = self._RLSortRoots(poles)
        return k, poles 
开发者ID:python-control,项目名称:python-control,代码行数:9,代码来源:controls.py

示例15: _find_microstrip_wire_width

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import fmin [as 别名]
def _find_microstrip_wire_width(Z_target, dielectric_thickness, eps_r, Lk_per_sq):

    def error_fun(wire_width):
        Z_guessed = _microstrip_Z_with_Lk(wire_width, dielectric_thickness, eps_r, Lk_per_sq)
        return (Z_guessed-Z_target)**2 # The error

    x0 = dielectric_thickness
    try:
        from scipy.optimize import fmin
    except:
        raise ImportError(""" [PHIDL] To run the microsctrip functions you need scipy,
          please install it with `pip install scipy` """)
    w = fmin(error_fun, x0, args=(), disp=False)
    return w[0] 
开发者ID:amccaugh,项目名称:phidl,代码行数:16,代码来源:geometry.py


注:本文中的scipy.optimize.fmin方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。