曲线拟合在matplotlib中的对数 - 对数图中并获得线的方程

时间:2018-02-21 02:16:33

标签: python matplotlib scipy linear-regression curve-fitting

我正在尝试为我的数据绘制最佳拟合曲线。这是非常糟糕的数据样本,但为了简单起见,我想说,我希望在对数对数范围内绘制一条直线作为最佳拟合。

我认为我已经通过回归做到了这一点,它给我一个合理的拟合线。但我想在scipy中用曲线拟合函数仔细检查它。我还想提取拟合线的方程式。

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import scipy.optimize as optimization




x = np.array([ 1.72724547e-08,   1.81960233e-08,   1.68093027e-08,   2.22839973e-08,
   2.23090589e-08,   4.28020801e-08,   2.30004711e-08,   2.48543008e-08,
1.08633065e-07,   3.24417303e-08,   3.22946248e-08,   3.82328031e-08,
   3.97713860e-08,   3.44080732e-08,   3.81526816e-08,   3.30756706e-08
])

y = np.array([ 4.18793565e+12,   4.40554864e+12,   4.48745390e+12,   4.50816705e+12,
   4.57088190e+12,   4.60256574e+12,   4.66659380e+12,   4.79733449e+12,  7.31139083e+12,   7.53355564e+12,   8.03526122e+12,   8.14704284e+12,
   8.47227414e+12,   8.62978548e+12,   8.81048873e+12,   9.46237161e+12
 ])


# Regression Function
def regress(x, y):
    """Return a tuple of predicted y values and parameters for linear regression."""
    p = sp.stats.linregress(x, y)
    b1, b0, r, p_val, stderr = p
    y_pred = sp.polyval([b1, b0], x)
    return y_pred, p

# plotting z
allx, ally = x, y                              # data, non-transformed
y_pred, _ = regress(np.log(allx), np.log(ally))      # change here           # transformed input             

plt.loglog(allx, ally, marker='$\\star$',color ='g', markersize=5,linestyle='None')
plt.loglog(allx, np.exp(y_pred), "c--", label="regression")  # transformed output



# Let's fit an exponential function.  
# This looks like a line on a lof-log plot.
def myExpFunc(x, a, b):
    return a * np.power(x, b)

popt, pcov = curve_fit(myExpFunc, x, y, maxfev=1000)
plt.plot(x, myExpFunc(x, *popt), 'r:', 
         label="({0:.3f}*x**{1:.3f})".format(*popt))
print "Exponential Fit: y = (a*(x**b))"
print "\ta = popt[0] = {0}\n\tb = popt[1] = {1}".format(*popt)

plt.show() 

我再次为一个糟糕的数据集道歉。非常感谢你的帮助。

我的情节如下: enter image description here     在这里输入代码

0 个答案:

没有答案