【问题标题】:How to improve numpy curve fitting如何改进 numpy 曲线拟合
【发布时间】:2016-08-18 02:11:24
【问题描述】:

我从太阳能电池板充电器获得了一些时间与电流的数据,我试图将其拟合成曲线。数据集(由 matplotlib.dates.date2num 转换的时间)位于http://pastebin.com/4FAMbbCJ。我将时间放入一个名为 Time 的列表中,将当前放入 Current。

import numpy
import matplotlib.pyplot as plt

fit = numpy.polyfit(Time, Current, 10)
fit_fxn = numpy.poly1d(fit)

plt.figure(1)
plt.subplot(211)
plt.plot_date(Time, Current, '-r', xdate=True, ydate=False)
plt.title("Current flow over time")
plt.ylabel("milliAmps")
plt.xlabel("Time")

plt.subplot(212)
plt.plot_date(Time, fit_fxn(Time), '-r', xdate=True, ydate=False)
plt.title("Current fxn with time")

plt.show()

散点图很好,但无论我用 polyfit 尝试多少系数,我仍然得到一条大致直线。编辑:在我看来,电流在中午左右达到峰值,正如太阳能所预期的那样,但曲线最早会产生最大电流,然后从那里开始直线下降。我会添加一张图片,但没有足够的声望点。我认为这个错误在我的实现中比在 polyfit 中更可能发生,我只是想看看我在哪里搞砸了。

有人对如何找到更好的曲线有任何想法吗?

【问题讨论】:

  • 您是在暗示 polyfit 例程不起作用吗?从数学上讲,您必须定义“更好的曲线”的含义。为什么选择多项式而不是指数或简单的直线?为什么最小二乘拟合而不是某些数据平滑算法?无论您使用什么函数(多项式或其他函数),任何统计方法都会在最小二乘意义上为您提供最适合数据的方法。
  • 您的实现看起来不错,问题是您的数据看起来不像多项式。你健身的目标是什么?当然,您不是在寻找一些预期的系数(因为太阳通量与时间的关系并不是真正的多项式),也许您只是想要一个很好的绘图曲线?也许您正在寻找峰值电流的时间或值?
  • 肯定比直线要好。

标签: python numpy curve-fitting


【解决方案1】:

更多的是自变量的问题。您使用的是 10 次多项式,但这意味着您将有 4.5e+58 之类的东西 -> 您的系数必须非常小,并且您将失去精度。

尝试以这种方式移动时间变量的最小值。

import numpy
import matplotlib.pyplot as plt
t = Time-Time.min()

fit = numpy.polyfit(t, Current, 10)
fit_fxn = numpy.poly1d(fit)

plt.figure(1)
plt.subplot(211)
plt.plot_date(Time, Current, '-r', xdate=True, ydate=False)
plt.title("Current flow over time")
plt.ylabel("milliAmps")
plt.xlabel("Time")

plt.subplot(212)
plt.plot_date(Time, fit_fxn(t), '-r', xdate=True, ydate=False)
plt.title("Current fxn with time")

plt.show()

【讨论】:

  • t = Time-Time.min() 给出了“AttributeError: 'list' object has no attribute 'min'”的错误,并且 t = Time-min(Time) 给出了“TypeError: unsupported operand - 的类型:'list' 和 'float'"。但是,通过minimum = min(Time); for time in Time: t.append(time - minimum) 运行列表是可行的。然后它给出了一个很好的拟合曲线!感谢您的建议。
  • 由于您使用 numpy 的 polyfit,我只是假设 Time 是一个 numpy 数组。如果您将列表转换为数组,它应该不会再给您带来任何问题。
  • 那么我应该已经警告过你了 - 更高次的多项式是个坏主意see Runge's phenomenon
【解决方案2】:

我遇到了同样的问题。我意识到如果数字太大,拟合将无法正常工作。 尝试重新调整您的单位。这对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 2012-04-25
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2020-09-25
    • 2017-04-07
    • 2019-10-19
    相关资源
    最近更新 更多