[英]linalg.lstsq with fixed slope?
Suppose that we have two arrays of data: x = [1,2,3] y = [2,4,6] Obviously a linear fit would return a slope of 2 and an intercept of 0 and, of course, both routines in Numpy linalg.lstsq()
and polyfit()
are successful. 假设我们有两个数据数组:x = [1,2,3] y = [2,4,6]显然线性拟合会返回2的斜率和0的截距,当然,这两个例程都是Numpy linalg.lstsq()
和polyfit()
是成功的。 But they think of slope and intercept as parameters to search. 但他们认为斜率和截距是搜索的参数。
Is it possible to keep the slope fixed and define only the intercept ? 是否可以保持斜率固定并仅定义截距?
If the fit equation is y = a*x + b
, you can find the intercept b
that best fits you data, given a fixed slope a = A
, as: 如果拟合方程为y = a*x + b
,则可以找到最适合数据的截距b
,给定固定斜率a = A
,如下:
b = np.mean(y - A*x)
If instead you had a fixed intercept b = B
and wanted to find the slope best fitting your data, the math works out to: 相反,如果您有一个固定的截距b = B
并希望找到最适合您数据的斜率,则数学计算结果为:
a = np.dot(X, Y-B) / np.dot(X, X)
You could use scipy.optimize.fsolve
: 你可以使用scipy.optimize.fsolve
:
X = np.array([1, 2, 3])
Y = np.array([2, 4, 6])
s = 2
def f(i):
"""Fixed slope 1-deg polynomial residuals"""
return ((Y - (s*X + i))**2).sum()
It performs about the same as polyfit
: 它的表现与polyfit
大致相同:
In [37]: np.polyfit(X, Y, 1)
Out[37]: array([ 2.00000000e+00, 2.30755522e-15])
In [38]: fsolve(f, x0=1)
Out[38]: array([ 1.63883763e-16])
And changing the slope: 并改变坡度:
In [39]: s = 4
In [40]: fsolve(f, x0=1)
Out[40]: array([-3.99075568])
We get a new optimum 我们得到了一个新的优化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.