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


Python optimize.leastsq方法代码示例

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


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

示例1: fit_random

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def fit_random(self, ntries=10, rvs_generator=None, nparams=None):
        '''fit with random starting values

        this could be replaced with a global fitter

        '''

        if nparams is None:
                nparams = self.nparams
        if rvs_generator is None:
            rvs = np.random.uniform(low=-10, high=10, size=(ntries, nparams))
        else:
            rvs = rvs_generator(size=(ntries, nparams))

        results = np.array([np.r_[self.fit_minimal(rv),  rv] for rv in rvs])
        #selct best results and check how many solutions are within 1e-6 of best
        #not sure what leastsq returns
        return results 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:20,代码来源:nonlinls.py

示例2: test_regression_2639

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def test_regression_2639(self):
        # This test fails if epsfcn in leastsq is too large.
        x = [574.14200000000005, 574.154, 574.16499999999996,
             574.17700000000002, 574.18799999999999, 574.19899999999996,
             574.21100000000001, 574.22199999999998, 574.23400000000004,
             574.245]
        y = [859.0, 997.0, 1699.0, 2604.0, 2013.0, 1964.0, 2435.0,
             1550.0, 949.0, 841.0]
        guess = [574.1861428571428, 574.2155714285715, 1302.0, 1302.0,
                 0.0035019999999983615, 859.0]
        good = [ 5.74177150e+02, 5.74209188e+02, 1.74187044e+03, 1.58646166e+03,
                 1.0068462e-02, 8.57450661e+02]

        def f_double_gauss(x, x0, x1, A0, A1, sigma, c):
            return (A0*np.exp(-(x-x0)**2/(2.*sigma**2))
                    + A1*np.exp(-(x-x1)**2/(2.*sigma**2)) + c)
        popt, pcov = curve_fit(f_double_gauss, x, y, guess, maxfev=10000)
        assert_allclose(popt, good, rtol=1e-5) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:20,代码来源:test_minpack.py

示例3: error

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def error(params, xs, ys):
        """A callback function for use with :func:`scipy.optimize.leastsq` to compute
        the residuals given a set of parameters, x, and y

        Parameters
        ----------
        params : list
            The model's parameters, a list of floats
        xs : :class:`np.ndarray`
            The time array to predict with respect to.
        ys : :class:`np.ndarray`
            The intensity array to predict against

        Returns
        -------
        :class:`np.ndarray`:
            The residuals of ``ys - self.shape(params, x)`` with optional penalty terms
        """
        raise NotImplementedError() 
开发者ID:mobiusklein,项目名称:ms_deisotope,代码行数:21,代码来源:shape_fitter.py

示例4: guess

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def guess(xs, ys):
        """Get crude estimates of roughly where to start fitting parameters

        The results are by no means accurate, but will serve as a reasonable starting point
        for :func:`scipy.optimize.leastsq`.

        Parameters
        ----------
        xs : :class:`np.ndarray`
            The time array to predict with respect to.
        ys : :class:`np.ndarray`
            The intensity array to predict against

        Returns
        -------
        list
        """
        raise NotImplementedError() 
开发者ID:mobiusklein,项目名称:ms_deisotope,代码行数:20,代码来源:shape_fitter.py

示例5: fit

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def fit(self):
        """Fit E(V) model, fill ``self.params``."""
        # Quadratic fit to get an initial guess for the parameters.
        # Thanks: https://github.com/materialsproject/pymatgen
        # -> pymatgen/io/abinitio/eos.py
        a, b, c = np.polyfit(self.volume, self.energy, 2)
        v0 = -b/(2*a)
        e0 = a*v0**2 + b*v0 + c
        b0 = 2*a*v0
        b1 = 4  # b1 is usually a small number like 4
        if not self.volume.min() < v0 and v0 < self.volume.max():
            raise Exception('The minimum volume of a fitted parabola is not in the input volumes')

        # need to use lst2dct and dct2lst here to keep the order of parameters
        pp0_dct = dict(e0=e0, b0=b0, b1=b1, v0=v0)
        target = lambda pp, v: self.energy - self.func(v, self.func.lst2dct(pp))
        pp_opt, ierr = leastsq(target,
                               self.func.dct2lst(pp0_dct),
                               args=(self.volume,))
        self.params = self.func.lst2dct(pp_opt) 
开发者ID:elcorto,项目名称:pwtools,代码行数:22,代码来源:eos.py

示例6: gaussian_fit_curve

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def gaussian_fit_curve(x, y, mu0=0, sigma0=1, a0=None, return_all=False,
        **kwargs):
    """Gaussian fit of curve (x,y).
    If a0 is None then only (mu,sigma) are fitted (to a gaussian density).
    `kwargs` are passed to the leastsq() function.

    If return_all=False then return only the fitted (mu,sigma) values
    If return_all=True (or full_output=True is passed to leastsq)
    then the full output of leastsq is returned.
    """
    if a0 is None:
        gauss_pdf = lambda x, m, s: np.exp(-((x-m)**2)/(2*s**2))/\
                                    (np.sqrt(2*np.pi)*s)
        err_fun = lambda p, x, y: gauss_pdf(x, *p) - y
        res = leastsq(err_fun, x0=[mu0, sigma0], args=(x, y), **kwargs)
    else:
        gauss_fun = lambda x, m, s, a: a*np.sign(s)*np.exp(-((x-m)**2)/(2*s**2))
        err_fun = lambda p, x, y: gauss_fun(x, *p) - y
        res = leastsq(err_fun, x0=[mu0, sigma0, a0], args=(x, y), **kwargs)

    if 'full_output' in kwargs:
        return_all = kwargs['full_output']
    mu, sigma = res[0][0], res[0][1]
    if return_all: return res
    return mu, sigma 
开发者ID:tritemio,项目名称:FRETBursts,代码行数:27,代码来源:gaussian_fitting.py

示例7: gaussian_fit_pdf

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def gaussian_fit_pdf(s, mu0=0, sigma0=1, a0=1, return_all=False,
        leastsq_kwargs={}, **kwargs):
    """Gaussian fit of samples s using a fit to the empirical PDF.
    If a0 is None then only (mu,sigma) are fitted (to a gaussian density).
    `kwargs` are passed to get_epdf().
    If return_all=False then return only the fitted (mu,sigma) values
    If return_all=True (or full_output=True is passed to leastsq)
    then the full output of leastsq and the PDF curve is returned.
    """
    ## Empirical PDF
    epdf = get_epdf(s, **kwargs)

    res = gaussian_fit_curve(epdf[0], epdf[1], mu0, sigma0, a0, return_all,
            **leastsq_kwargs)
    if return_all: return res, epdf
    return res 
开发者ID:tritemio,项目名称:FRETBursts,代码行数:18,代码来源:gaussian_fitting.py

示例8: gaussian_fit_hist

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def gaussian_fit_hist(s, mu0=0, sigma0=1, a0=None, bins=np.r_[-0.5:1.5:0.001],
        return_all=False, leastsq_kwargs={}, weights=None, **kwargs):
    """Gaussian fit of samples s fitting the hist to a Gaussian function.
    If a0 is None then only (mu,sigma) are fitted (to a gaussian density).
    kwargs are passed to the histogram function.
    If return_all=False then return only the fitted (mu,sigma) values
    If return_all=True (or full_output=True is passed to leastsq)
    then the full output of leastsq and the histogram is returned.
    `weights` optional weights for the histogram.
    """
    histogram_kwargs = dict(bins=bins, density=True, weights=weights)
    histogram_kwargs.update(**kwargs)
    H = np.histogram(s, **histogram_kwargs)
    x, y = 0.5*(H[1][:-1] + H[1][1:]), H[0]
    #bar(H[1][:-1], H[0], H[1][1]-H[1][0], alpha=0.3)

    res = gaussian_fit_curve(x, y, mu0, sigma0, a0, return_all,
            **leastsq_kwargs)
    if return_all: return res, H, x, y
    return res 
开发者ID:tritemio,项目名称:FRETBursts,代码行数:22,代码来源:gaussian_fitting.py

示例9: gaussian_fit_cdf

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def gaussian_fit_cdf(s, mu0=0, sigma0=1, return_all=False, **leastsq_kwargs):
    """Gaussian fit of samples s fitting the empirical CDF.
    Additional kwargs are passed to the leastsq() function.
    If return_all=False then return only the fitted (mu,sigma) values
    If return_all=True (or full_output=True is passed to leastsq)
    then the full output of leastsq and the histogram is returned.
    """
    ## Empirical CDF
    ecdf = [np.sort(s), np.arange(0.5, s.size+0.5)*1./s.size]

    ## Analytical Gaussian CDF
    gauss_cdf = lambda x, mu, sigma: 0.5*(1+erf((x-mu)/(np.sqrt(2)*sigma)))

    ## Fitting the empirical CDF
    err_func = lambda p, x, y: y - gauss_cdf(x, p[0], p[1])
    res = leastsq(err_func, x0=[mu0, sigma0], args=(ecdf[0], ecdf[1]),
            **leastsq_kwargs)
    if return_all: return res, ecdf
    return res[0] 
开发者ID:tritemio,项目名称:FRETBursts,代码行数:21,代码来源:gaussian_fitting.py

示例10: two_gaussian_fit_curve

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def two_gaussian_fit_curve(x, y, p0, return_all=False, verbose=False, **kwargs):
    """Fit a 2-gaussian mixture to the (x,y) curve.
    `kwargs` are passed to the leastsq() function.

    If return_all=False then return only the fitted paramaters
    If return_all=True then the full output of leastsq is returned.
    """
    if kwargs['method'] == 'leastsq':
        kwargs.pop('method')
        kwargs.pop('bounds')
        def err_func(p, x, y):
            return (y - two_gauss_mix_pdf(x, p))
        res = leastsq(err_func, x0=p0, args=(x, y), **kwargs)
        p = res[0]
    else:
        def err_func(p, x, y):
            return ((y - two_gauss_mix_pdf(x, p))**2).sum()
        res = minimize(err_func, x0=p0, args=(x, y), **kwargs)
        p = res.x

    if verbose:
        print(res, '\n')
    if return_all: return res
    return reorder_parameters(p) 
开发者ID:tritemio,项目名称:FRETBursts,代码行数:26,代码来源:gaussian_fitting.py

示例11: gaussian2d_fit

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def gaussian2d_fit(sx, sy, guess=[0.5,1]):
    """2D-Gaussian fit of samples S using a fit to the empirical CDF."""
    assert sx.size == sy.size

    ## Empirical CDF
    ecdfx = [np.sort(sx), np.arange(0.5,sx.size+0.5)*1./sx.size]
    ecdfy = [np.sort(sy), np.arange(0.5,sy.size+0.5)*1./sy.size]

    ## Analytical gaussian CDF
    gauss_cdf = lambda x, mu, sigma: 0.5*(1+erf((x-mu)/(np.sqrt(2)*sigma)))

    ## Fitting the empirical CDF
    fitfunc = lambda p, x: gauss_cdf(x, p[0], p[1])
    errfunc = lambda p, x, y: fitfunc(p, x) - y
    px,v = leastsq(errfunc, x0=guess, args=(ecdfx[0],ecdfx[1]))
    py,v = leastsq(errfunc, x0=guess, args=(ecdfy[0],ecdfy[1]))
    print("2D Gaussian CDF fit", px, py)

    mux, sigmax = px[0], px[1]
    muy, sigmay = py[0], py[1]
    return mux, sigmax, muy, sigmay 
开发者ID:tritemio,项目名称:FRETBursts,代码行数:23,代码来源:gaussian_fitting.py

示例12: LinearB

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def LinearB(Xi, Yi):
    X = np.asfarray(Xi)
    Y = np.asfarray(Yi)

    # we want a function y = m * x + b
    def fp(v, x):
        return x * v[0] + v[1]

    # the error of the function e = x - y
    def e(v, x, y):
        return (fp(v, x) - y)

    # the initial value of m, we choose 1, because we thought YODA would
    # have chosen 1
    v0 = np.array([1.0, 1.0])

    vr, _success = leastsq(e, v0, args=(X, Y))

    # compute the R**2 (sqrt of the mean of the squares of the errors)
    err = np.sqrt(sum(np.square(e(vr, X, Y))) / (len(X) * len(X)))

#    print vr, success, err
    return vr, err 
开发者ID:EMVA1288,项目名称:emva1288,代码行数:25,代码来源:routines.py

示例13: test_regression_2639

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def test_regression_2639(self):
        # This test fails if epsfcn in leastsq is too large.
        x = [574.14200000000005, 574.154, 574.16499999999996,
             574.17700000000002, 574.18799999999999, 574.19899999999996,
             574.21100000000001, 574.22199999999998, 574.23400000000004,
             574.245]
        y = [859.0, 997.0, 1699.0, 2604.0, 2013.0, 1964.0, 2435.0,
             1550.0, 949.0, 841.0]
        guess = [574.1861428571428, 574.2155714285715, 1302.0, 1302.0,
                 0.0035019999999983615, 859.0]
        good = [5.74177150e+02, 5.74209188e+02, 1.74187044e+03, 1.58646166e+03,
                1.0068462e-02, 8.57450661e+02]

        def f_double_gauss(x, x0, x1, A0, A1, sigma, c):
            return (A0*np.exp(-(x-x0)**2/(2.*sigma**2))
                    + A1*np.exp(-(x-x1)**2/(2.*sigma**2)) + c)
        popt, pcov = curve_fit(f_double_gauss, x, y, guess, maxfev=10000)
        assert_allclose(popt, good, rtol=1e-5) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:20,代码来源:test_minpack.py

示例14: _fitGivenSmoothness

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def _fitGivenSmoothness(y, t, ode, theta, s):
    # p = ode.getNumParam()
    # d = ode.getNumState()

    splineList = interpolate(y, t, s=s)
    interval = np.linspace(t[1], t[-1], 1000)
    # xApprox, fxApprox, t = _getApprox(splineList, interval)

    # g2 = partial(residual_sample, ode, fxApprox, xApprox, interval)
    # g2J = partial(jac_sample, ode, fxApprox, xApprox, interval)
    g2 = partial(residual_interpolant, ode, splineList, interval)
    g2J = partial(jac_interpolant, ode, splineList, interval)

    res = leastsq(func=g2, x0=theta, Dfun=g2J, full_output=True)

    loss = 0
    for spline in splineList:
        loss += spline.get_residual()
    # approximate the integral using fixed points
    r = np.reshape(res[2]['fvec']**2, (len(interval), len(splineList)), 'F')

    return (r.sum())*(interval[1] - interval[0]) + loss 
开发者ID:publichealthengland,项目名称:pygom,代码行数:24,代码来源:get_init.py

示例15: _profileObtainAndVerify

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import leastsq [as 别名]
def _profileObtainAndVerify(f, df, x0, full_output=False):
    '''
    Find the solution of the profile likelihood and check
    that the algorithm has converged.
    '''
    x, cov, infodict, mesg, ier = leastsq(func=f, x0=x0, Dfun=df,
                                          maxfev=10000, full_output=True)

    if ier not in (1, 2, 3, 4):
        raise EstimateError("Failure in estimation of the profile likelihood: "
                            + mesg)

    if full_output:
        output = dict()
        output['cov'] = cov
        output['infodict'] = infodict
        output['mesg'] = mesg
        output['ier'] = ier
        return x, output
    else:
        return x 
开发者ID:publichealthengland,项目名称:pygom,代码行数:23,代码来源:confidence_interval.py


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