Scipy优化线性函数近似

2 投票
2 回答
5697 浏览
提问于 2025-04-18 13:57

我查看了 scipy.optimize 中的函数近似方法,读完这些函数的描述后,我觉得(可能是错的)它们只适用于非线性函数的近似。

举个例子,如果我用 zip() 函数对 xy 的输出进行了采样,结果是这样的:

[(1,1),(4,2),(6,4),(8,6),(10,11)]

从上面可以看出,非线性函数的近似效果要好得多,但我需要的是线性函数来满足我的需求。

我承认可能在函数的文档中漏掉了一些信息,如果我的问题可以通过“看文档”来回答,那我在这里先道个歉。

2 个回答

3

你有没有试过做一个最小二乘法拟合?这个方法可以帮助你找到数据的最佳线性关系。你可以看看这个链接了解更多:http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html。另外,如果我没记错的话,numpy的polyfit函数也有一个选项,可以让你确定拟合所需的自由度,在你的情况下,自由度应该是1。

importing polyfit from numpy... etc.

coefficients = polyfit( xlist, ylist, 1 ) #where 1 is the degree of freedom
p = poly1d( coefficients ) 
x = linspace( 0, 5, 100 ) #generates 100 points between 0 and 5 to plot 'curve'
plot( x, p(x), label='Best Fit Line' ) 

希望这些对你有帮助。

5

除了@user2589273提到的np.polyfitscipy.stats.linregress,还有一种比较底层的方法可以进行线性回归,那就是使用np.linalg.lstsq来求解系数矩阵。虽然这种方法比使用现成的线性回归函数要麻烦一些,但了解它的基本原理非常有用,尤其是当你开始处理多变量数据时。

举个例子:

import numpy as np

# a simple linear relationship: y = mx + c with m=0.5 and c=2
x = np.arange(50)
y = x * 0.5 + 2
y += np.random.randn(50) * 5    # add some noise

# we can rewrite the line equation as y = Ap, where A=[[x, 1]] and p=[[m], [c]]
A = np.c_[x, np.ones(50)]

# solving for p gives us the slope and intercept
p, residuals, rank, svals = np.linalg.lstsq(A, y)

绘制拟合曲线:

from matplotlib import pyplot as plt

fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(x, y, 'ob', label='data')
ax.plot(x, A.dot(p), '-k', lw=2, label='linear fit')
ax.legend()

在这里输入图片描述

撰写回答