當前位置: 首頁>>代碼示例>>Python>>正文


Python optimize.newton方法代碼示例

本文整理匯總了Python中scipy.optimize.newton方法的典型用法代碼示例。如果您正苦於以下問題:Python optimize.newton方法的具體用法?Python optimize.newton怎麽用?Python optimize.newton使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在scipy.optimize的用法示例。


在下文中一共展示了optimize.newton方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_derivatives

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def test_derivatives(loss, x0, y_true):
    # Check that gradients are zero when the loss is minimized on 1D array
    # using the Newton-Raphson and the first and second order derivatives
    # computed by the Loss instance.

    loss = _LOSSES[loss]()
    y_true = np.array([y_true], dtype=np.float32)
    x0 = np.array([x0], dtype=np.float32).reshape(1, 1)
    get_gradients, get_hessians = get_derivatives_helper(loss)

    def func(x):
        return loss(y_true, x)

    def fprime(x):
        return get_gradients(y_true, x)

    def fprime2(x):
        return get_hessians(y_true, x)

    optimum = newton(func, x0=x0, fprime=fprime, fprime2=fprime2)
    assert np.allclose(loss.inverse_link_function(optimum), y_true)
    assert np.allclose(loss(y_true, optimum), 0)
    assert np.allclose(get_gradients(y_true, optimum), 0) 
開發者ID:ogrisel,項目名稱:pygbm,代碼行數:25,代碼來源:test_loss.py

示例2: test_derivatives

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def test_derivatives(loss, x0, y_true):
    # Check that gradients are zero when the loss is minimized on 1D array
    # using Halley's method with the first and second order derivatives
    # computed by the Loss instance.

    loss = _LOSSES[loss]()
    y_true = np.array([y_true], dtype=Y_DTYPE)
    x0 = np.array([x0], dtype=Y_DTYPE).reshape(1, 1)
    get_gradients, get_hessians = get_derivatives_helper(loss)

    def func(x):
        return loss(y_true, x)

    def fprime(x):
        return get_gradients(y_true, x)

    def fprime2(x):
        return get_hessians(y_true, x)

    optimum = newton(func, x0=x0, fprime=fprime, fprime2=fprime2)
    assert np.allclose(loss.inverse_link_function(optimum), y_true)
    assert np.allclose(loss(y_true, optimum), 0)
    assert np.allclose(get_gradients(y_true, optimum), 0) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:25,代碼來源:test_loss.py

示例3: solve_T

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def solve_T(self, P, V, quick=True):
        r'''Generic method to calculate `T` from a specified `P` and `V`.
        Provides SciPy's `newton` solver, and iterates to solve the general
        equation for `P`, recalculating `a_alpha` as a function of temperature
        using `a_alpha_and_derivatives` each iteration.

        Parameters
        ----------
        P : float
            Pressure, [Pa]
        V : float
            Molar volume, [m^3/mol]
        quick : bool, optional
            Unimplemented, although it may be possible to derive explicit 
            expressions as done for many pure-component EOS

        Returns
        -------
        T : float
            Temperature, [K]
        '''
        self.Tc = sum(self.Tcs)/self.N
        # -4 goes back from object, GCEOS
        return super(type(self).__mro__[-3], self).solve_T(P=P, V=V, quick=quick) 
開發者ID:CalebBell,項目名稱:thermo,代碼行數:26,代碼來源:eos_mix.py

示例4: xirr

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def xirr(cashflows, guess=0.1):
    """
    calculate the Internal Rate of Return of a series of cashflows at irregular intervals.

    :param cashflows: a list, in which each element is a tuple of the form (date, amount),
        where date is a datetime object and amount is an integer or floating number.
        Cash outflows (investments) are represented with negative amounts,
        and cash inflows (returns) are positive amounts.
    :param guess: floating number, a guess at the xirr rate solution to be used
        as a starting point for the numerical solution
    :returns: the IRR as a single floating number
    """
    return optimize.newton(lambda r: xnpv(r, cashflows), guess) 
開發者ID:refraction-ray,項目名稱:xalpha,代碼行數:15,代碼來源:cons.py

示例5: _bessel_zeros

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def _bessel_zeros(N):
    """
    Find zeros of ordinary Bessel polynomial of order `N`, by root-finding of
    modified Bessel function of the second kind
    """
    if N == 0:
        return asarray([])

    # Generate starting points
    x0 = _campos_zeros(N)

    # Zeros are the same for exp(1/x)*K_{N+0.5}(1/x) and Nth-order ordinary
    # Bessel polynomial y_N(x)
    def f(x):
        return special.kve(N+0.5, 1/x)

    # First derivative of above
    def fp(x):
        return (special.kve(N-0.5, 1/x)/(2*x**2) -
                special.kve(N+0.5, 1/x)/(x**2) +
                special.kve(N+1.5, 1/x)/(2*x**2))

    # Starting points converge to true zeros
    x = _aberth(f, fp, x0)

    # Improve precision using Newton's method on each
    for i in range(len(x)):
        x[i] = optimize.newton(f, x[i], fp, tol=1e-15)

    # Average complex conjugates to make them exactly symmetrical
    x = np.mean((x, x[::-1].conj()), 0)

    # Zeros should sum to -1
    if abs(np.sum(x) + 1) > 1e-15:
        raise RuntimeError('Generated zeros are inaccurate')

    return x 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:39,代碼來源:filter_design.py

示例6: _norm_factor

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def _norm_factor(p, k):
    """
    Numerically find frequency shift to apply to delay-normalized filter such
    that -3 dB point is at 1 rad/sec.

    `p` is an array_like of polynomial poles
    `k` is a float gain

    First 10 values are listed in "Bessel Scale Factors" table,
    "Bessel Filters Polynomials, Poles and Circuit Elements 2003, C. Bond."
    """
    p = asarray(p, dtype=complex)

    def G(w):
        """
        Gain of filter
        """
        return abs(k / prod(1j*w - p))

    def cutoff(w):
        """
        When gain = -3 dB, return 0
        """
        return G(w) - 1/np.sqrt(2)

    return optimize.newton(cutoff, 1.5) 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:28,代碼來源:filter_design.py

示例7: _digammainv

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def _digammainv(y):
    # Inverse of the digamma function (real positive arguments only).
    # This function is used in the `fit` method of `gamma_gen`.
    # The function uses either optimize.fsolve or optimize.newton
    # to solve `sc.digamma(x) - y = 0`.  There is probably room for
    # improvement, but currently it works over a wide range of y:
    #    >>> y = 64*np.random.randn(1000000)
    #    >>> y.min(), y.max()
    #    (-311.43592651416662, 351.77388222276869)
    #    x = [_digammainv(t) for t in y]
    #    np.abs(sc.digamma(x) - y).max()
    #    1.1368683772161603e-13
    #
    _em = 0.5772156649015328606065120
    func = lambda x: sc.digamma(x) - y
    if y > -0.125:
        x0 = np.exp(y) + 0.5
        if y < 10:
            # Some experimentation shows that newton reliably converges
            # must faster than fsolve in this y range.  For larger y,
            # newton sometimes fails to converge.
            value = optimize.newton(func, x0, tol=1e-10)
            return value
    elif y > -3:
        x0 = np.exp(y/2.332) + 0.08661
    else:
        x0 = 1.0 / (-y - _em)

    value, info, ier, mesg = optimize.fsolve(func, x0, xtol=1e-11,
                                             full_output=True)
    if ier != 1:
        raise RuntimeError("_digammainv: fsolve failed, y = %r" % y)

    return value[0]


## Gamma (Use MATLAB and MATHEMATICA (b=theta=scale, a=alpha=shape) definition)

## gamma(a, loc, scale)  with a an integer is the Erlang distribution
## gamma(1, loc, scale)  is the Exponential distribution
## gamma(df/2, 0, 2) is the chi2 distribution with df degrees of freedom. 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:43,代碼來源:_continuous_distns.py

示例8: _findroot

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def _findroot(self, func, x0=None, xab=None, **kwds):
        """Find root of `func` by Newton's method if `x0` is given or Brent's
        method if `xab` is given. If neither is given, then
        ``xab=[self.x[0],self.x[-1]]`` and Brent's method is used.

        Parameters
        ----------
        func : callable, must accept a scalar and retun a scalar
        x0 : float
            start guess for Newton's secant method
        xab : sequence of length 2
            start bracket for Brent's method, root must lie in between
        **kwds :
            passed to scipy root finder (newton() or brentq())

        Returns
        -------
        xx : scalar
            the root of func(x)
        """
        if x0 is not None:
            xx = optimize.newton(func, x0, **kwds)
        else:
            if xab is None:
                xab = [self.x[0], self.x[-1]]
            xx = optimize.brentq(func, xab[0], xab[1], **kwds)
        return xx 
開發者ID:elcorto,項目名稱:pwtools,代碼行數:29,代碼來源:num.py

示例9: addSSmNrm

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def addSSmNrm(self,solution):
        '''
        Finds steady state (normalized) market resources and adds it to the
        solution.  This is the level of market resources such that the expectation
        of market resources in the next period is unchanged.  This value doesn't
        necessarily exist.

        Parameters
        ----------
        solution : ConsumerSolution
            Solution to this period's problem, which must have attribute cFunc.
        Returns
        -------
        solution : ConsumerSolution
            Same solution that was passed, but now with the attribute mNrmSS.
        '''
        # Make a linear function of all combinations of c and m that yield mNext = mNow
        mZeroChangeFunc = lambda m : (1.0-self.PermGroFac/self.Rfree)*m + (self.PermGroFac/self.Rfree)*self.ExIncNext

        # Find the steady state level of market resources
        searchSSfunc = lambda m : solution.cFunc(m) - mZeroChangeFunc(m) # A zero of this is SS market resources
        m_init_guess = self.mNrmMinNow + self.ExIncNext # Minimum market resources plus next income is okay starting guess
        try:
            mNrmSS = newton(searchSSfunc,m_init_guess)
        except:
            mNrmSS = None

        # Add mNrmSS to the solution and return it
        solution.mNrmSS = mNrmSS
        return solution 
開發者ID:econ-ark,項目名稱:HARK,代碼行數:32,代碼來源:ConsIndShockModel.py

示例10: calc_radiator

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def calc_radiator(Qh, tair, Qh0, tair0, tsh0, trh0):
    """
    Calculates the supply and return temperature as well as the flow rate of water in radiators similar to the model
    implemented by Holst (1996) using a Newton-Raphson solver.

    :param Qh: Space heating demand in the building
    :param tair: environment temperature in the building
    :param Qh0: nominal radiator power
    :param tair0:
    :param tsh0:
    :param trh0:
    :return:

    [Holst} S. Holst (1996) "TRNSYS-Models for Radiator Heating Systems"
    """
    # TODO: add documentation and sources

    nh = 0.3  # radiator constant
    if Qh > 0 or Qh < 0:  # use radiator function also for sensible cooling panels (ceiling cooling, chilled beam,...)
        tair = tair + 273
        tair0 = tair0 + 273
        tsh0 = tsh0 + 273
        trh0 = trh0 + 273
        mCw0 = Qh0 / (tsh0 - trh0)
        # minimum
        LMRT0 = lmrt(tair0, trh0, tsh0)
        delta_t = Qh / mCw0
        result = newton(fh, trh0, args=(delta_t, Qh0, Qh, tair, LMRT0, nh), maxiter=100, tol=0.01) - 273
        trh = result.real
        tsh = trh + Qh / mCw0
        mCw = Qh / (tsh - trh)
    else:
        mCw = 0
        tsh = np.nan
        trh = np.nan
    # return floats with numpy function. Needed when np.vectorize is use to call this function
    return np.float(tsh), np.float(trh), np.float(mCw) # C, C, W/C 
開發者ID:architecture-building-systems,項目名稱:CityEnergyAnalyst,代碼行數:39,代碼來源:radiators.py

示例11: bond_ytm

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def bond_ytm(price, par, T, coup, freq=2, guess=0.05):
    freq = float(freq)
    periods = T*freq
    coupon = coup/100.*par/freq
    dt = [(i+1)/freq for i in range(int(periods))]
    ytm_func = lambda(y): \
        sum([coupon/(1+y/freq)**(freq*t) for t in dt]) + \
        par/(1+y/freq)**(freq*t) - price
        
    return optimize.newton(ytm_func, guess) 
開發者ID:jamesmawm,項目名稱:Mastering-Python-for-Finance-source-codes,代碼行數:12,代碼來源:bond_ytm.py

示例12: neg_bin_fit

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def neg_bin_fit(vec, init=0.0001):
    ''' Function to fit negative binomial to data
    @param vec: The data vector used to fit the negative binomial distribution
    @param init: Set init to a number close to 0, and you will always converge
    '''
    if not vec:
        raise ValueError("Data must be specified")

    est_r = newton(r_derv, init, args=(vec,))
    est_p = p_equa(est_r, vec)
    return est_r, est_p
    

# r = 40
# p = 0.5
# size = 100000
#
# import matplotlib.pyplot as plt
# random_nb_data = np.random.negative_binomial(r, p, size)
# print(random_nb_data)
# a=[]
# for i in random_nb_data:
#     a.append(i)
# _ = plt.hist(a, bins='auto')
# plt.title("Histogram with 'auto' bins")
# plt.show()
# print(neg_bin_fit(a)) 
開發者ID:GATB,項目名稱:DiscoSnp,代碼行數:29,代碼來源:negative_binomial.py

示例13: calculate_TH

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def calculate_TH(self, T, H):
        def to_solve(P):
            self.calculate(T, P)
            return self.H - H
        return newton(to_solve, self.P) 
開發者ID:CalebBell,項目名稱:thermo,代碼行數:7,代碼來源:mixture.py

示例14: calculate_PH

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def calculate_PH(self, P, H):
        def to_solve(T):
            self.calculate(T, P)
            return self.H - H
        return newton(to_solve, self.T) 
開發者ID:CalebBell,項目名稱:thermo,代碼行數:7,代碼來源:mixture.py

示例15: calculate_TS

# 需要導入模塊: from scipy import optimize [as 別名]
# 或者: from scipy.optimize import newton [as 別名]
def calculate_TS(self, T, S):
        def to_solve(P):
            self.calculate(T, P)
            return self.S - S
        return newton(to_solve, self.P) 
開發者ID:CalebBell,項目名稱:thermo,代碼行數:7,代碼來源:mixture.py


注:本文中的scipy.optimize.newton方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。