Scipy.optimization线性函数逼近

时间:2014-07-19 16:13:28

标签: python numpy scipy approximation

我已经查看了scipy.optimize中的函数逼近方法,并且在读出函数的描述之后(可能是错误的)它们仅仅是近似非线性函数。

例如,如果我在zip()x的{​​{1}}函数之后对输出进行了示例

y

正如您所看到的,非线性函数近似得更好,但我需要线性用于我的目的。

我承认错过了函数文档中遗漏的可能性,所以如果可以用“阅读文档”方式回答问题,我表示歉意。

2 个答案:

答案 0 :(得分:5)

除了@ user2589273建议的np.polyfitscipy.stats.linregress之外,进行线性回归的低级方法是使用np.linalg.lstsq求解系数矩阵。虽然这种方法比使用其中一个预先打包的函数进行线性回归要多一些,但了解它如何在基本级别工作非常有用,特别是当您开始处理多变量数据时。 / p>

例如:

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()

enter image description here

答案 1 :(得分:3)

你尝试过最小方块的东西吗? http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html 另外如果我没记错的话,numpy的polyfit可以选择确定你需要的适合度,在你的情况下它会是一个。

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' ) 

希望有所帮助