python - 如何使用最小二乘算法通过Python中的线性方程来匹配两个数据集

标签 python algorithm numpy least-squares data-fitting

我有两个一维向量。其中一个包含通过测量系统测量的数据。另一个向量包含一种校准数据,其“形状”和时间完全相同(它基本上是单个脉冲,并且在两个向量中这些脉冲在时域中同步)。

我想通过简单的变换original_data = (calibration_data - offset) * Gain来将校准数据曲线与原始测量数据进行匹配

我需要使用“最佳方法”来查找偏移和增益参数,以便两条迹线看起来尽可能最相似。为此,我认为必须最小化两个数据集的最小二乘标量 sum_i( (F(gain,offset)(calibration_i)-measured_i) ** 2 )。最小化可以通过调整变换函数的增益和偏移来完成。

我已经实现了这种暴力算法:

    offset = 0
    gain = 1.0
    firstIteration = True
    lastlstsq = 0
    iterations = 0

    for ioffset in np.arange(-32768, 32768, 50):
        for igain in np.arange(1,5,0.1):
            # prepare the trace by transformation:
            int1 = map(lambda c: (c - ioffset) * igain, self.fetcher.yvalues['int1'])

            # this is pretty heavy computation here
            lstsq = sum(map(lambda c: c**2, map(sub, self.fetcher.yvalues['int0'],int1)))
            if firstIteration == True:
                # just store
                lastlstsq = lstsq
                offset = ioffset
                gain = igain
                firstIteration = False
            else:
                # what lstsq:
                if lstsq < lastlstsq:
                    # got better match:
                    lastlstsq = lstsq
                    offset = ioffset
                    gain = igain
                    print "Iteration ", iterations, " squares=", lstsq, " offset=", offset, " gain=", gain
            iterations = iterations + 1

它找到了最佳匹配,但速度太慢而且不太精确,因为我想找到 igain 的步长为 0.01,ioffset 的步长为 0.5。对于这个分辨率来说这个算法完全没用。

有什么方法可以用Pythonic方式解决这种优化问题吗? (或者是否有更好的方法来找到增益和偏移值以实现最佳匹配?)

不幸的是,我仅限于 numpy(没有 scipy),但任何类型的提示都值得赞赏。

最佳答案

在 user3235916 的帮助下,我成功写下了以下代码:

import numpy as np

measuredData = np.array(yvalues['int1'])
calibrationData = np.array(yvalues['int0'])

A = np.vstack( [measuredData, np.ones(len(measuredData))]).T
gain,offset = np.linalg.lstsq(A, calibrationData)[0]

然后我可以使用以下转换将测量数据重新计算为校准数据:

map(lambda c: c*gain+offset, measuredData)

完美契合(至少在视觉上)。

关于python - 如何使用最小二乘算法通过Python中的线性方程来匹配两个数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28484484/

相关文章:

python - 设置属性不起作用 - 愚蠢的语法错误?

python - 合并 Pandas 中的 2 个数据帧 : join on some columns, 总结其他

python - 使用 Django 的 reportlab header 参数

algorithm - O(n) 中的 MS-Access 数据库搜索算法?

arrays - 算法:给定一个数字数组 A,创建一个数组 B,其中 B[i] = sum(A[j]: A[j] <= A[i])

algorithm - 在二维数组中查找最长的路线

python - 使用 Python 的高效滚动修剪均值

python - Numpy reshape "reversal"

Python MemoryError 何时不是真的内存不足?

python - 如何使用 python smtplib 保存附加在另一个电子邮件中的电子邮件?