【问题标题】:How to implement automatic model determination and two state model fitting in python?如何在python中实现自动模型确定和二态模型拟合?
【发布时间】:2018-07-18 09:04:14
【问题描述】:

目前,我一直在 Prism 中手动对我的所有数据进行模型拟合。这是相当乏味和耗时的。我想知道是否有任何方法可以提高数据分析的效率。我对 Python 很熟悉,所以我想从 Python 入手,想出一个更好的工作流程。非常感谢您的帮助。

两个问题:

  1. 如何在python中进行二态模型拟合(图1)?在我的情况下,它将有一个初始的线性增加,然后是水平平台状态。我希望在python中的实现方式以及自动检测变化发生的转折点的方式(理想情况下我可以得到它发生的时间和斜率)

  2. 另一种情况是状态变为指数或多项式。 python有没有办法自动判断哪个模型最好。

Figure 1

【问题讨论】:

  • 注意自动选择模型。通常最复杂的模型/函数最适合数据。

标签: python scipy modeling model-fitting


【解决方案1】:

Scipy 提供了一种支持自定义函数的最小二乘曲线拟合方法。这是第一个模型的示例:

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

#custom fit function - first slope steeper than second slope
def two_lin(x, m1, n1, m2, n2):
    return np.min([m1 * x + n1, m2 * x + n2], axis = 0)

#x/y data points
x = np.asarray([0, 1, 2,  3,  4,  5,  6,  7,  8,  9,  10])
y = np.asarray([2, 4, 8, 12, 14, 18, 20, 21, 22, 23,  24])
#initial guess for a steep rising and plateau phase
start_values = [3, 0, 0, 3]
#curve fitting
fit_param, pcov = curve_fit(two_lin, x, y, p0 = start_values)

#output of slope/intercept for both parts
m1, n1, m2, n2 = fit_param
print(m1, n1, m2, n2)
#calculating sum of squared residuals as parameter for fit quality
r = y - two_lin(x, *fit_param)
print(np.sum(np.square(r)))

#point, where the parts intersect 
if m1 != m2:
    x_intersect = (n2 - n1) / (m1 - m2)
    print(x_intersect)
else:
    print("did not find two linear components")

#plot data and fit function
x_fit = np.linspace(-1, 11, 100)  
plt.plot(x, y, 'o', label='data')
plt.plot(x_fit, two_lin(x_fit, *fit_param), '--', label='fit')

plt.axis([-2, 12, 0, 30])
plt.legend()
plt.show()

更多关于scipy.optimize.curve_fit can be found in the reference guide. 的信息对于多项式,numpy 提供了numpy.polyfitnumpy.poly1d 的标准函数,但您仍然需要提供预期的次数。

残差平方和可以用来比较不同拟合函数的准确度。

【讨论】:

  • 嗨 Piinthesky,这是一个很棒的实现。有没有办法返回发生斜率变化的 x 坐标?
  • 添加代码以明确如何提取每个段的斜率/截距。请接受 kazemakase 的评论。
  • 如何在船上添加 Kazemakase 的评论?
  • 在判断拟合数据时不要忽视它,想想它。如果您用于判断的数字很好地代表了现实,请务必重新评估。查看原始数据 - 原因,我添加绘图的原因。
猜你喜欢
  • 1970-01-01
  • 2014-12-17
  • 2014-05-27
  • 2017-05-19
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多