numpy np.polyfit()(最小二乘多项式拟合曲线)(有待进一步研究)
生活随笔
收集整理的這篇文章主要介紹了
numpy np.polyfit()(最小二乘多项式拟合曲线)(有待进一步研究)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
from numpy\lib\polynomial.py
@array_function_dispatch(_polyfit_dispatcher) def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):"""Least squares polynomial fit.最小二乘多項(xiàng)式擬合。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`.將度數(shù)``deg''的多項(xiàng)式``p(x)= p [0] * x ** deg + ... + p°''擬合到點(diǎn)`(x,y)`。 返回系數(shù)p的向量,該向量按deg,deg-1,... 0的順序最小化平方誤差。The `Polynomial.fit <numpy.polynomial.polynomial.Polynomial.fit>` class method is recommended for new code as it is more stable numerically. See the documentation of the method for more information.對于新代碼,建議使用Polynomial.fit <numpy.polynomial.polynomial.Polynomial.fit>類方法,因?yàn)樗跀?shù)值上更穩(wěn)定。 有關(guān)更多信息,請參見該方法的文檔。Parameters----------x : array_like, shape (M,)x-coordinates of the M sample points ``(x[i], y[i])``.M個采樣點(diǎn)的``(x [i],y [i])''的x坐標(biāo)。y : array_like, shape (M,) or (M, K)y-coordinates of the sample points. Several data sets of sample points sharing the same x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset per column.采樣點(diǎn)的y坐標(biāo)。 可以通過傳入每列包含一個數(shù)據(jù)集的2D數(shù)組,一次擬合幾個共享相同x坐標(biāo)的采樣點(diǎn)數(shù)據(jù)集。deg : intDegree of the fitting polynomial擬合多項(xiàng)式的度(階數(shù)?)rcond : float, optionalRelative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases.擬合的相對條件編號。 相對于最大奇異值,小于此奇異值的將被忽略。 默認(rèn)值為len(x)* eps,其中eps是float類型的相對精度,在大多數(shù)情況下約為2e-16。full : bool, optionalSwitch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned.切換確定返回值的性質(zhì)。 如果為False(默認(rèn)值),則僅返回系數(shù);當(dāng)設(shè)置為True還返回來自奇異值分解的True診斷信息時。w : array_like, shape (M,), optionalWeights to apply to the y-coordinates of the sample points. For gaussian uncertainties, use 1/sigma (not 1/sigma**2).應(yīng)用于采樣點(diǎn)的y坐標(biāo)的權(quán)重。 對于高斯不確定性,請使用1 / sigma(而不是1 / sigma ** 2)。cov : bool or str, optionalIf given and not `False`, return not just the estimate but also its covariance matrix. By default, the covariance are scaled by chi2/sqrt(N-dof), i.e., the weights are presumed to be unreliable except in a relative sense and everything is scaled such that the reduced chi2 is unity. This scaling is omitted if ``cov='unscaled'``, as is relevant for the case that the weights are 1/sigma**2, with sigma known to be a reliable estimate of the uncertainty.如果給出且不是“ False”,則不僅返回估計(jì)值,還返回其協(xié)方差矩陣。 默認(rèn)情況下,協(xié)方差由chi2 / sqrt(N-dof)縮放,即除相對意義上的權(quán)重被假定為不可靠的,并且一切都縮放以使減少的chi2統(tǒng)一。 如果``cov ='unscaled''',則忽略此縮放比例,這與權(quán)重為1 / sigma ** 2的情況有關(guān),已知sigma是不確定性的可靠估計(jì)。Returns-------p : ndarray, shape (deg + 1,) or (deg + 1, K)Polynomial coefficients, highest power first. If `y` was 2-D, thecoefficients for `k`-th data set are in ``p[:,k]``.residuals, rank, singular_values, rcondPresent only if `full` = True. Residuals is sum of squared residualsof the least-squares fit, the effective rank of the scaled Vandermondecoefficient matrix, its singular values, and the specified value of`rcond`. For more details, see `linalg.lstsq`.V : ndarray, shape (M,M) or (M,M,K)Present only if `full` = False and `cov`=True. The covariancematrix of the polynomial coefficient estimates. The diagonal ofthis matrix are the variance estimates for each coefficient. If yis a 2-D array, then the covariance matrix for the `k`-th data setare in ``V[:,:,k]``Warns-----RankWarningThe rank of the coefficient matrix in the least-squares fit isdeficient. The warning is only raised if `full` = False.最小二乘擬合中的系數(shù)矩陣的秩不足。 僅當(dāng)“ full” = False時才發(fā)出警告。The warnings can be turned off by>>> import warnings>>> warnings.simplefilter('ignore', np.RankWarning)See Also--------polyval : Compute polynomial values.計(jì)算多項(xiàng)式值。linalg.lstsq : Computes a least-squares fit.計(jì)算最小二乘擬合。scipy.interpolate.UnivariateSpline : Computes spline fits.計(jì)算樣條擬合。Notes-----The solution minimizes the squared error.. math ::E = \\sum_{j=0}^k |p(x_j) - y_j|^2in the equations::x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]...x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]The coefficient matrix of the coefficients `p` is a Vandermonde matrix.系數(shù)“ p”的系數(shù)矩陣是范德蒙德矩陣。`polyfit` issues a `RankWarning` when the least-squares fit is badly conditioned. This implies that the best fit is not well-defined due to numerical error. The results may be improved by lowering the polynomial degree or by replacing `x` by `x` - `x`.mean(). The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious: including contributions from the small singular values can add numerical noise to the result.當(dāng)最小二乘擬合條件不好時,`polyfit`會發(fā)出“ RankWarning”。 這意味著由于數(shù)值誤差,最佳擬合的定義不明確。 通過降低多項(xiàng)式次數(shù)或?qū)?#96;x`替換為`x`-`x`.mean()可以改善結(jié)果。 rcond參數(shù)也可以設(shè)置為小于其默認(rèn)值的值,但是結(jié)果擬合可能是虛假的:包括小的奇異值的貢獻(xiàn)會在結(jié)果中增加數(shù)值噪聲。Note that fitting polynomial coefficients is inherently badly conditioned when the degree of the polynomial is large or the interval of sample points is badly centered. The quality of the fit should always be checked in these cases. When polynomial fits are not satisfactory, splines may be a good alternative.注意,當(dāng)多項(xiàng)式的階數(shù)較大或采樣點(diǎn)的間隔嚴(yán)重居中時,擬合多項(xiàng)式系數(shù)固有地條件不好。 在這種情況下,應(yīng)始終檢查配合質(zhì)量。 當(dāng)多項(xiàng)式擬合不令人滿意時,樣條線可能是不錯的選擇。References----------.. [1] Wikipedia, "Curve fitting",https://en.wikipedia.org/wiki/Curve_fitting.. [2] Wikipedia, "Polynomial interpolation",https://en.wikipedia.org/wiki/Polynomial_interpolationExamples-------->>> import warnings>>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])>>> z = np.polyfit(x, y, 3)>>> zarray([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) # may varyIt is convenient to use `poly1d` objects for dealing with polynomials:>>> p = np.poly1d(z)>>> p(0.5)0.6143849206349179 # may vary>>> p(3.5)-0.34732142857143039 # may vary>>> p(10)22.579365079365115 # may varyHigh-order polynomials may oscillate wildly:>>> with warnings.catch_warnings():... warnings.simplefilter('ignore', np.RankWarning)... p30 = np.poly1d(np.polyfit(x, y, 30))...>>> p30(4)-0.80000000000000204 # may vary>>> p30(5)-0.99999999999999445 # may vary>>> p30(4.5)-0.10547061179440398 # may varyIllustration:>>> import matplotlib.pyplot as plt>>> xp = np.linspace(-2, 6, 100)>>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')>>> plt.ylim(-2,2)(-2, 2)>>> plt.show()"""示例
# -*- coding: utf-8 -*- """ @File : plot.py @Time : 2020/2/24 8:55 @Author : Dontla @Email : sxana@qq.com @Software: PyCharm """import matplotlib.pyplot as pltimport numpy as np# 如發(fā)現(xiàn)格式不對可用記事本或notepad批量替換 keyword = {'11:30.0': (50000, 13.96), '12:16.0': (54500, 13.20), '13:15.0': (47500, 12.48),'14:22.0': (55450, 12.44), '14:35.0': (55430, 13.72), '17:03.0': (13990, 11.00),'17:38.0': (9058, 11.60), '17:57.0': (5044, 12.46), '18:20.0': (1300, 13.80),'18:25.0': (900, 13.90), '18:28.0': (700, 13.96), '18:40.0': (200, 13.34),'18:42.0': (150, 13.10), '18:44.0': (100, 11.80), '18:44.2': (90, 11.34),'18.44.4': (80, 11.38), '18:44.8': (70, 9.50), '18:45.0': (60, 9.20),'18:46.0': (50, 11.9), '18:46.3': (40, 10.8), '18:46.6': (30, 9.20),'18:49.0': (20, 9.70), '18:49.6': (15, 6.90), '18:50.3': (13, 4.70),'18:50.9': (12, 3.80), '18:51.5': (11, 2.60), '18:52.2': (10, 1.70),'18:52.9': (9, 1.00), '18:53.6': (8, 0.2), '18:54.3': (7, 0.06),'18:55.0': (6, 0.02)}data = []for key in keyword:data.append(keyword[key])x = np.array(data)[:, 0] y = np.array(data)[:, 1]# 用3次多項(xiàng)式擬合 可以改為5 次多項(xiàng)式。。。。 返回三次多項(xiàng)式系數(shù) z1 = np.polyfit(x, y, 10) p1 = np.poly1d(z1)# 在屏幕上打印擬合多項(xiàng)式 print(p1) # 3 2 # 2.534e-13 x - 2.506e-08 x + 0.000714 x + 7.821yvals = p1(x) # 也可以使用yvals=np.polyval(z1,x)plot1 = plt.plot(x, y, '*', label='original values') plot2 = plt.plot(x, yvals, 'r', label='polyfit values')plt.xlabel('xaxis')plt.ylabel('yaxis')plt.legend(loc=4) # 指定legend的位置,讀者可以自己help它的用法plt.title('polyfitting')plt.show()plt.savefig('p1.png')結(jié)果:
D:\Yolov3_Tensorflow\python\python.exe C:/Users/HuaWei/Desktop/繪制不同光照條件下識別率曲線圖/plot.py10 9 8 7 6 -3.045e-40 x + 7.957e-35 x - 8.616e-30 x + 4.993e-25 x - 1.672e-20 x5 4 3 2+ 3.273e-16 x - 3.641e-12 x + 2.149e-08 x - 5.822e-05 x + 0.05093 x + 4.692Process finished with exit code 0
這圖象咋這么奇怪呢?
我擦,原來是x的間隔設(shè)置太大了
改一改:
現(xiàn)在好了
總結(jié)
以上是生活随笔為你收集整理的numpy np.polyfit()(最小二乘多项式拟合曲线)(有待进一步研究)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 为什么元组中只包含一个元素
- 下一篇: python matplotlib.py