im_*_*ous 1 python numpy scipy approximation
我已经研究过函数逼近方法scipy.optimize,在读取函数的描述之后(可能是错误的)它们只是近似非线性函数.
例如,如果我在zip()for x和函数之后对输出进行采样y
[(1,1),(4,2),(6,4),(8,6),(10,11)]
Run Code Online (Sandbox Code Playgroud)
如您所见,非线性函数近似得更好,但我需要线性用于我的目的.
我承认错过了函数文档中遗漏的可能性,所以如果问题可以用"阅读文档"方式回答,我表示歉意.
除了np.polyfit和scipy.stats.linregress由@ user2589273所建议的,一个低级别的方式做线性回归是解决用于使用系数矩阵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)
Run Code Online (Sandbox Code Playgroud)
绘制拟合:
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()
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
3941 次 |
| 最近记录: |