Binding a Curve with Python 3.3 Integer Inputs

I am using the scipy curvefit module to match a function and would like to know if there is a way to tell it that the only possible elements are integers, not real numbers? Any ideas on another way to do this?

+4
source share
2 answers

In its general form, the task is with whole NP-hard programming (see here ). To solve this problem, an effective heuristic or approximate algorithm exists, but no one guarantees an exact optimal solution.

In scipy you can implement a grid search by integer coefficients and use, say, curve_fitover real parameters for given integer coefficients. Regarding grid search. scipy has brute.

For example, if y = a * x + b * x^2 + some-noise, where ashould be an integer, this might work:

  • Generate some test data using a = 5and b = -1.5:

    coef, n = [5, - 1.5], 50
    xs = np.linspace(0, 10, n)[:,np.newaxis]
    xs = np.hstack([xs, xs**2])
    noise = 2 * np.random.randn(n)
    ys = np.dot(xs, coef) + noise
    
  • The function that sets the integer coefficients corresponds to the real coefficient using the method curve_fit:

    def optfloat(intcoef, xs, ys):
        from scipy.optimize import curve_fit
        def poly(xs, floatcoef):
            return np.dot(xs, [intcoef, floatcoef])
        popt, pcov = curve_fit(poly, xs, ys)
        errsqr = np.linalg.norm(poly(xs, popt) - ys)
        return dict(errsqr=errsqr, floatcoef=popt)
    
  • The function that sets the integer coefficients uses the above function to optimize the float coefficient and returns an error:

    def errfun(intcoef, *args):
        xs, ys = args
        return optfloat(intcoef, xs, ys)['errsqr']
    
  • errfun scipy.optimize.brute, optfloat :

    from scipy.optimize import brute
    grid = [slice(1, 10, 1)]  # grid search over 1, 2, ..., 9
    # it is important to specify finish=None in below
    intcoef = brute(errfun, grid, args=(xs, ys,), finish=None)
    floatcoef = optfloat(intcoef, xs, ys)['floatcoef'][0]
    

, [5.0, -1.50577] , .

+2

No: scipy.optimize.curve_fit() lesssq(), , (AFAIK) scipy.optimize .

epsfcn ( numpy.finfo('double'). eps ~ 2.e-16), , , ,

    int_var = int(float_var)

float_var 1.0 1.00000001, , .

"tmp_float_var", ,

    int_var = int(tmp_float_var / numpy.finfo('double').eps)

. , , .

0

Source: https://habr.com/ru/post/1534927/


All Articles