gpt4 book ai didi

python - numpy.polyfit vs numpy.polynomial.polynomial.polyfit

转载 作者:行者123 更新时间:2023-12-03 18:29:23 27 4
gpt4 key购买 nike

为什么要 numpy.polyfit numpy.polynomial.polynomial.polyfit
在下面的测试中产生不同的图?

import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 50)
y = 5 * x + 10 + (np.random.random(len(x)) - 0.5) * 5

plt.scatter(x, y,marker='.', label='Data for regression')
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)),
label='numpy.polyfit')
plt.plot(np.unique(x), np.poly1d(polyfit(x, y, 1))(np.unique(x)),
label='polynomial.polyfit')
plt.legend()
plt.show()

enter image description here

最佳答案

乍一看,文档似乎表明它们应该给出相同的结果 -

numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)

Least squares polynomial fit.

Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimises the squared error in the order deg, deg-1, … 0.





numpy.polynomial.polynomial.polyfit(x, y, deg, rcond=None, full=False, w=None)

Least-squares fit of a polynomial to data.

Return the coefficients of a polynomial of degree deg that is the least squares fit to the data values y given at points x. If y is 1-D the returned coefficients will also be 1-D. If y is 2-D multiple fits are done, one for each column of y, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form

p(x) = c0 + c1 * x + ... + cn * xn



但区别在于从两种方法返回的系数的顺序,至少对于所讨论的用例是这样。
  • numpy.polyfit根据生成方程,按度数降序返回系数

    p(x) = cn * xn + c(n-1) * x(n-1) + ... + c1 * x + c0
  • numpy.polynomial.polynomial.polyfit根据生成方程,按度数升序返回系数

    p(x) = c0 + c1 * x + ... + c(n-1) * x(n-1) + cn * xn

  • 尽管在数学上相同,但这两个方程在 ndarray 中并不相同。表示。在文档中使用不同的符号可能会混淆这一点。为了演示,请考虑以下内容

    import numpy as np

    x = np.linspace(0, 10, 50)
    y = x**2 + 5 * x + 10

    print(np.polyfit(x, y, 2))
    print(np.polynomial.polynomial.polyfit(x, y, 2))

    [ 1.  5. 10.]
    [10. 5. 1.]

    两种方法得到的结果相同,但顺序相反,前者是 np.poly1d() 预计,

    print(np.poly1d(np.polyfit(x, y, 2)))
    print(np.poly1d(np.polynomial.polynomial.polyfit(x, y, 2)))

       2
    1 x + 5 x + 10
    2
    10 x + 5 x + 1

    后者是 np.polynomial.polynomial.Polynomial() 构造函数期望。,

    print(np.polynomial.polynomial.Polynomial(np.polynomial.polynomial.polyfit(x, y, 2)))
    print(np.polynomial.polynomial.Polynomial(np.polyfit(x, y, 2)))

    poly([10.  5.  1.])  # 10 + 5 * x + 1 * x**2
    poly([ 1. 5. 10.]) # 1 + 5 * x + 10 * x**2

    Flipping来自 np.polynomial.polynomial.polyfit 的结果在将其传递给 poly1d() 之前或使用 np.polynomial.polynomial.Polynomial将产生预期的结果:

    Matching output

    关于python - numpy.polyfit vs numpy.polynomial.polynomial.polyfit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004096/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com