當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。