带有自适应参数的numpy.polyfit [英] numpy.polyfit with adapted parameters

查看:94
本文介绍了带有自适应参数的numpy.polyfit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于此:多项式方程参数 在这里,我得到3个平方函数y = a*x² + b*x + c的参数,现在我只想获取平方函数的 first 参数,该参数描述了我的函数y = a*x².换句话说:我想设置b=c=0并获取a的适应参数.如果我理解正确,polyfit将无法做到这一点.

Regarding to this: polynomial equation parameters where I get 3 parameters for a squared function y = a*x² + b*x + c now I want only to get the first parameter for a squared function which describes my function y = a*x². With other words: I want to set b=c=0 and get the adapted parameter for a. In case I understand it right, polyfit isn't able to do this.

推荐答案

这可以通过x和y,首先要构建一个所谓的设计矩阵 M像这样:

This can be done by numpy.linalg.lstsq. To explain how to use it, it is maybe easiest to show how you would do a standard 2nd order polyfit 'by hand'. Assuming you have your measurement vectors x and y, you first construct a so-called design matrix M like so:

M = np.column_stack((x**2, x, np.ones_like(x)))

之后,您可以像这样使用lstsq获得通常的系数,作为方程M * k = y的最小二乘解:

after which you can obtain the usual coefficients as the least-square solution to the equation M * k = y using lstsq like this:

k, _, _, _ = np.linalg.lstsq(M, y)

其中,k是具有常规系数的列向量[a, b, c].请注意,lstsq返回一些其他参数,您可以忽略这些参数.这是一个非常强大的技巧,它使您可以将y拟合到放入设计矩阵中的列的任何线性组合.可以使用例如对于类型为z = a * x + b * y的2D拟合(例如,参见此示例,我在Matlab中使用了相同的技巧),或者像您的问题一样缺少系数的polyfits.

where k is the column vector [a, b, c] with the usual coefficients. Note that lstsq returns some other parameters, which you can ignore. This is a very powerful trick, which allows you to fit y to any linear combination of the columns you put into your design matrix. It can be used e.g. for 2D fits of the type z = a * x + b * y (see e.g. this example, where I used the same trick in Matlab), or polyfits with missing coefficients like in your problem.

在您的情况下,设计矩阵只是包含x**2的单个列.快速示例:

In your case, the design matrix is simply a single column containing x**2. Quick example:

import numpy as np
import matplotlib.pylab as plt

# generate some noisy data
x = np.arange(1000)
y = 0.0001234 * x**2 + 3*np.random.randn(len(x))

# do fit
M = np.column_stack((x**2,)) # construct design matrix
k, _, _, _ = np.linalg.lstsq(M, y) # least-square fit of M * k = y

# quick plot
plt.plot(x, y, '.', x, k*x**2, 'r', linewidth=3)
plt.legend(('measurement', 'fit'), loc=2)
plt.title('best fit: y = {:.8f} * x**2'.format(k[0]))
plt.show()

结果:

这篇关于带有自适应参数的numpy.polyfit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆