【问题标题】:How do I use scipy optimize curve fit with panda df如何使用 scipy 优化曲线拟合与熊猫 df
【发布时间】:2019-08-08 06:26:58
【问题描述】:

这是我在这里的第一篇文章,我花了几个小时寻找这个答案,但我似乎无法弄清楚。我使用 pandas 将 .csv 传递给 np 矩阵。从那里我尝试应用简单的曲线拟合,但我得到的输出始终是错误的。该代码将绘制错误的拟合,并且不会绘制数据。

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

df = pd.read_csv("Results.csv")
xdata = df['Frame'].as_matrix()
ydata = df['Area'].as_matrix()

def func(x, a, b, c):
    return (a*np.sin(b*x))+(c * np.exp(x))
popt, pcov = curve_fit(func, xdata, ydata)

plt.plot(xdata, func(xdata, *popt), 'r-',
        label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
popt, pcov = curve_fit(func, xdata, ydata)

plt.plot(xdata, func(xdata, *popt), 'g--',
          label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

这是数据的样子:

提前感谢您的帮助。

【问题讨论】:

  • 能否发个数据文件的链接?
  • 拟合的棘手部分是找到好的起始值。如果没有给出起始值,curve_fit 将假定它们都是一,a=b=c=1。我想在你的情况下,那些离实际最佳拟合太远了,以至于拟合处于局部最优状态。而是从具有更多有用值的 p0 向量开始,即更接近您的预期。
  • @ImportanceOfBeingErnest 是绝对正确的。我想提供一个使用 scipy 的差分进化遗传算法模块生成初始参数估计的示例,这就是我请求数据文件链接的原因。
  • @JamesPhillips 也许最好将 OP 指向显示这一点的先前答案(可能也作为重复关闭),因为如果好的答案遍布不同的问题,它并没有多大帮助。
  • @JamesPhillips 非常感谢您的帮助!

标签: pandas numpy matplotlib scipy curve-fitting


【解决方案1】:

您的模型包含“exp(x)”并且数据文件包含 x 值为 1000,无论起始值如何,这都会导致数学溢出错误 - 优化器找不到解决该问题的方法,您必须更改适合该数据集的方程。我可以建议其他方程,但这个数据集不能适合发布的方程。

编辑:根据您对除以 100 的评论,这里是使用 scipy 的差分进化遗传算法模块来查找初始参数估计的代码,该模块使用拉丁超立方算法来确保彻底搜索参数空间- 该算法需要搜索范围,并且参数范围比精确的初始参数值更容易找到。在这里,我尝试了几个范围,从我所看到的情况来看,这可能是最适合您的范围。

import pandas as pd
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings


df = pd.read_csv("Results.csv")
xData = df['Frame'].as_matrix() / 100.0
yData = df['Area'].as_matrix()

def func(x, a, b, c):
    return (a*numpy.sin(b*x))+(c * numpy.exp(x))


# 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, 100.0]) # search bounds for a
    parameterBounds.append([0.0, 1.0]) # search bounds for b
    parameterBounds.append([0.0, 1.0]) # search bounds for c

    # "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('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 = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)

【讨论】:

  • 如果我将 x 值除以 100 会解决问题吗?
猜你喜欢
  • 1970-01-01
  • 2021-02-16
  • 2021-11-01
  • 2020-05-05
  • 2018-08-16
  • 2018-06-02
  • 1970-01-01
  • 2017-04-21
  • 2020-07-12
相关资源
最近更新 更多