python - 如何在Python中进行指数非线性回归

标签 python regression non-linear-regression

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

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()

我很确定我把它弄得过于复杂和困惑了。

最佳答案

这里是使用您的数据和方程的示例代码,其中使用 scipy 的 Differential_evolution 遗传算法来确定非线性拟合器的初始参数估计。差分进化的 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)

关于python - 如何在Python中进行指数非线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52943720/

相关文章:

r - 如何在 R 中执行前向选择、后向选择和逐步回归?

python - 如何使用三次或更高次的多项式曲面回归来拟合一组 3D 数据点?

machine-learning - 这两个成本函数在倍频程中相等吗?

python - 将 PNG 图像裁剪为其最小尺寸

python - 如何将现有的 django 应用程序/项目部署/迁移到 Heroku 上的生产服务器?

python - 在 Pyodbc 中使用哪个版本的 MySQL 驱动程序

python - 我如何将 ljust() 转换应用于字符串列表的每个元素?

r - glmnet 错误 (nulldev == 0) 停止 ("y is constant; gaussian glmnet fails at standardization step")

r - mgcv:如何指定平滑和因子之间的交互?

python - Scipy curve_fit 给出了错误的答案