【问题标题】:how to do exponential nonlinear regression in python如何在python中进行指数非线性回归
【发布时间】:2019-03-27 09:03:00
【问题描述】:

我正在尝试使用方程进行非线性回归

y=ae^(-bT)

其中 T 是数据的温度:

([26.67, 93.33, 148.89, 222.01, 315.56])

和y是数据的粘度:

([1.35, .085, .012, .0049, .00075])

我们的目标是确定ab 的值,同时不对等式进行线性化以绘制图形。到目前为止,我尝试过的一种方法是:

import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit 
def func(x, a, b):
    return a*(np.exp(-b * x)) 
#data
temp = np.array([26.67, 93.33, 148.89, 222.01, 315.56])
Viscosity = np.array([1.35, .085, .012, .0049, .00075])
initialGuess=[200,1]
guessedFactors=[func(x,*initialGuess ) for x in temp]
#curve fit
popt,pcov = curve_fit(func, temp, Viscosity,initialGuess)
print (popt)
print (pcov)
tempCont=np.linspace(min(temp),max(temp),50)
fittedData=[func(x, *popt) for x in tempCont]
fig1 = plt.figure(1)
ax=fig1.add_subplot(1,1,1)
###the three sets of data to plot
ax.plot(temp,Viscosity,linestyle='',marker='o', color='r',label="data")
ax.plot(temp,guessedFactors,linestyle='',marker='^', color='b',label="initial guess")
###beautification
ax.legend(loc=0, title="graphs", fontsize=12)
ax.set_ylabel("Viscosity")
ax.set_xlabel("temp")
ax.grid()
ax.set_title("$\mathrm{curve}_\mathrm{fit}$")
###putting the covariance matrix nicely
tab= [['{:.2g}'.format(j) for j in i] for i in pcov]
the_table = plt.table(cellText=tab,
                  colWidths = [0.2]*3,
                  loc='upper right', bbox=[0.483, 0.35, 0.5, 0.25] )
plt.text(250,65,'covariance:',size=12)
###putting the plot
plt.show()

我很确定我把它弄得过于复杂而且搞砸了。

【问题讨论】:

    标签: python regression non-linear-regression


    【解决方案1】:

    这是使用您的数据和方程的示例代码,其中 scipy 的差分进化遗传算法用于确定非线性拟合器的初始参数估计值。差分进化的 scipy 实现使用拉丁超立方算法来确保对参数空间的彻底搜索,这里我给出了我认为拟合参数应该存在的范围。

    import numpy, scipy, matplotlib
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    from scipy.optimize import differential_evolution
    import warnings
    
    xData = numpy.array([26.67, 93.33, 148.89, 222.01, 315.56])
    yData = numpy.array([1.35, .085, .012, .0049, .00075])
    
    
    def func(T, a, b):
        return a * numpy.exp(-b*T)
    
    
    # function for genetic algorithm to minimize (sum of squared error)
    def sumOfSquaredError(parameterTuple):
        warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
        val = func(xData, *parameterTuple)
        return numpy.sum((yData - val) ** 2.0)
    
    
    def generate_Initial_Parameters():
        parameterBounds = []
        parameterBounds.append([0.0, 10.0]) # search bounds for a
        parameterBounds.append([-1.0, 1.0]) # search bounds for b
    
        # "seed" the numpy random number generator for repeatable results
        result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
        return result.x
    
    # by default, differential_evolution completes by calling curve_fit() using parameter bounds
    geneticParameters = generate_Initial_Parameters()
    
    # now call curve_fit without passing bounds from the genetic algorithm,
    # just in case the best fit parameters are aoutside those bounds
    fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)
    print('Fitted parameters:', fittedParameters)
    print()
    
    modelPredictions = func(xData, *fittedParameters) 
    
    absError = modelPredictions - yData
    
    SE = numpy.square(absError) # squared errors
    MSE = numpy.mean(SE) # mean squared errors
    RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
    Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
    
    print()
    print('RMSE:', RMSE)
    print('R-squared:', Rsquared)
    
    print()
    
    
    ##########################################################
    # graphics output section
    def ModelAndScatterPlot(graphWidth, graphHeight):
        f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
        axes = f.add_subplot(111)
    
        # first the raw data as a scatter plot
        axes.plot(xData, yData,  'D')
    
        # create data for the fitted equation plot
        xModel = numpy.linspace(min(xData), max(xData))
        yModel = func(xModel, *fittedParameters)
    
        # now the model as a line plot
        axes.plot(xModel, yModel)
    
        axes.set_xlabel('temp') # X axis data label
        axes.set_ylabel('viscosity') # Y axis data label
    
        plt.show()
        plt.close('all') # clean up after using pyplot
    
    graphWidth = 800
    graphHeight = 600
    ModelAndScatterPlot(graphWidth, graphHeight)
    

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 2023-03-08
      • 2017-02-15
      • 2020-06-03
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2021-03-11
      • 2023-03-05
      相关资源
      最近更新 更多