【问题标题】:problems with python curve fit : horizontal linepython曲线拟合的问题:水平线
【发布时间】:2021-05-24 18:23:35
【问题描述】:

我无法用方程式来拟合我的观点。 它绘制一条水平线。 我的印象是它来自初始参数,但我不知道该放什么。 我从另一个论坛获取了这段代码。 一开始一切正常,但是当我输入新数据时,出现了问题。

有人可以帮帮我吗?

***import numpy as np, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings
xData = np.array([.26, .35, .36, .37, .42, .46, .48, .54, .59, .72, .74, .83, .88, 1.04, 1.10, 1.12, 1.48])
yData = np.array([27.40, 29.96, 27.50, 28.20, 32.47, 31.52, 31.00, 34.93, 32.80, 35.84, 39.50, 40.00, 41.35, 41.50, 42.79, 41.71, 46.23])
 
def func(x, a, b, Offset): # Sigmoid A With Offset from zunzun.com
    return  1.0 / (1.0 + np.exp(-a * (x-b))) + Offset
# 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 np.sum((yData - val) ** 2.0)
# generate initial parameter values
geneticParameters = [0,0,0] 
# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)
print('Parameters', fittedParameters)
modelPredictions = func(xData, *fittedParameters) 
absError = modelPredictions - yData
SE = np.square(absError) # squared errors
MSE = np.mean(SE) # mean squared errors
RMSE = np.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (np.var(absError) / np.var(yData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)
##########################################################
# 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 = np.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)
    # now the model as a line plot 
    axes.plot(xModel, yModel)
    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label
    plt.show()
   # plt.close('all') # clean up after using pyplot
graphWidth = 400
graphHeight = 300
ModelAndScatterPlot(graphWidth, graphHeight)***

【问题讨论】:

  • 你的适合度很可能不会收敛。尝试找到更好的启动参数
  • 您的主要问题是拟合函数的幅度仅为 1,而数据跨度约为 20。您缺少幅度参数。

标签: python line curve data-fitting


【解决方案1】:

失败的最可能原因是您选择了三参数 (a,b,offset) sigmoid 模型而不是四参数模型。从 27.4 到 46.23 的数据范围永远不能拟合到范围从 0 到 1 的函数,即使有偏移也是如此。

另一个可能的困难原因是在开始非线性回归的迭代过程时对参数值的初始猜测。

为了避免这些困难,我们将使用如下所示的非迭代方法。

请注意,符号和符号与您的代码中的不同。

您可以在您的非线性回归软件中使用上述参数的数值作为初始值。

注意:非迭代方法的一般原理在论文中进行了解释:https://fr.scribd.com/doc/14674814/Regressions-et-equations-integrales

上述演算是对四参数逻辑回归的应用的简化版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 2013-11-08
    • 2020-12-06
    • 2021-03-21
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    相关资源
    最近更新 更多