【问题标题】:Fitting a power law with known exponent and extracting the coefficient in Python用已知指数拟合幂律并在 Python 中提取系数
【发布时间】:2019-03-01 13:45:44
【问题描述】:

我有一个数据集,我知道它适合以下形式的曲线:

y = a x² 

我想提取a的值。

在 Python 中解决这个问题的最佳方法是什么(使用 scipy 等)?

【问题讨论】:

  • 在 SO 上有很多帖子展示了如何做到这一点。只需在谷歌上搜索python curve_fitpython lmfit,您就会发现很多示例。如果您在实施过程中遇到问题,请发布您的代码和数据并描述您面临的实际问题。

标签: python numpy scipy curve-fitting power-law


【解决方案1】:

这是一个使用 scipy 的 curve_fit() 的图形拟合示例:

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

xData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7])
yData = numpy.array([1.1, 20.2, 30.3, 60.4, 50.0, 60.6, 70.7])


def func(x, a):
    return (a * numpy.square(x))


# same as the scipy default
initialParameters = numpy.array([1.0])

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)

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('Parameters:', fittedParameters)
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 2021-06-04
    • 2019-06-14
    • 1970-01-01
    • 2020-05-07
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多