How to do a polynomial fit with fixed points

前端 未结 3 1953
忘掉有多难
忘掉有多难 2020-12-02 15:48

I have been doing some fitting in python using numpy (which uses least squares).

I was wondering if there was a way of getting it to fit data while forcing it throug

3条回答
  •  时光取名叫无心
    2020-12-02 16:48

    If you use curve_fit(), you can use sigma argument to give every point a weight. The following example gives the first , middle, last point very small sigma, so the fitting result will be very close to these three points:

    N = 20
    x = np.linspace(0, 2, N)
    np.random.seed(1)
    noise = np.random.randn(N)*0.2
    sigma =np.ones(N)
    sigma[[0, N//2, -1]] = 0.01
    pr = (-2, 3, 0, 1)
    y = 1+3.0*x**2-2*x**3+0.3*x**4 + noise
    
    def f(x, *p):
        return np.poly1d(p)(x)
    
    p1, _ = optimize.curve_fit(f, x, y, (0, 0, 0, 0, 0), sigma=sigma)
    p2, _ = optimize.curve_fit(f, x, y, (0, 0, 0, 0, 0))
    
    x2 = np.linspace(0, 2, 100)
    y2 = np.poly1d(p)(x2)
    plot(x, y, "o")
    plot(x2, f(x2, *p1), "r", label=u"fix three points")
    plot(x2, f(x2, *p2), "b", label=u"no fix")
    legend(loc="best")
    

    enter image description here

提交回复
热议问题