矢量化numpy polyfit运动风

2024-09-28 21:07:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把下面的函数矢量化

def nppolyfit(pnp_array, **kwargs):
  """ Moving polyfit 
  """
  win_size = kwargs['length']
  degree = kwargs['degree']

  xdata = range(win_size)
  res = np.zeros(pnp_array.shape)

  for i in range(win_size, len(pnp_array) + 1):
      res[i-1]  = np.poly1d(np.polyfit(xdata , pnp_array[i - win_size : i], deg = degree))(win_size)

  return res

目前所做的工作:

^{pr2}$

但看起来我好像遗漏了什么或者做错了什么。你能纠正我吗?也许还有其他更有效的解决办法?谢谢。在

测试用例:

import numpy as np
npd = np.arange(30)
win_size1 = 11
degree = 1
c1  =     nppolyfit(npd, length=win_size1, degree=degree)
c1v  =   nppolyfitv(npd, length=win_size1, degree=degree)
print(c1)
print(c1v)

结果是:

[  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.  11.  12.  13.  14.  15.
  16.  17.  18.  19.  20.  21.  22.  23.  24.  25.  26.  27.  28.  29.  30.]
[   0.    0.    0.    0.    0.    0.    0.    0.    0.    0.    1.   30.
   59.   88.  117.  146.  175.  204.  233.  262.  291.  320.  349.  378.
  407.  436.  465.  494.  523.  552.]

Tags: sizenprangeresarraylengthwinkwargs
2条回答

^{}方法返回多项式系数,最高幂优先。在

^{}方法要求系数首先具有最低幂次。当将一个方法的输出输入到另一个方法时,请考虑这一点。在

而且,polyval的x参数不合逻辑:np.zeros(len(pnp_array))。为什么要多次要求polyval在同一点0求值多项式?尤其是因为你的非矢量化函数计算了win_size处的多项式。要与非矢量化方法一致,请替换行

res[win_size-1:] = np.polynomial.polynomial.polyval(np.zeros(len(pnp_array)), fit).T[len(pnp_array) - 1,:]

^{pr2}$

那么测试用例的两个输出是相同的。在

为什么我不知道多项式的代表性呢?但这是你自己决定的。)

第一步是比较两种方法的中间值

例如,我可以跟踪polyfit步骤

In [304]: def nppolyfit(pnp_array, **kwargs):
     ...:   """ Moving polyfit 
     ...:   """
     ...:   win_size = kwargs['length']
     ...:   degree = kwargs['degree']
     ...: 
     ...:   xdata = np.arange(win_size)
     ...:   res = np.zeros(pnp_array.shape)
     ...:   fits = []
     ...:   for i in range(win_size, len(pnp_array) + 1):
     ...:       fit = np.polyfit(xdata , pnp_array[i - win_size : i], deg = degr
     ...: ee)
     ...:       res[i-1] = np.poly1d(fit)(win_size)
     ...:       fits.append(fit)
     ...:   return res, fits
     ...: 
     ...: 
In [305]: 
In [305]: nppolyfit(npd,length=win_size1, degree=degree)
Out[305]: 
(array([  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,  11.,
         12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,
         23.,  24.,  25.,  26.,  27.,  28.,  29.,  30.]),
 [array([  1.00000000e+00,   1.60677522e-15]),
  array([ 1.,  1.]),
  array([ 1.,  2.]),
  array([ 1.,  3.]),
  array([ 1.,  4.]),
  array([ 1.,  5.]),
  array([ 1.,  6.]),
  array([ 1.,  7.]),
  array([ 1.,  8.]),
  array([ 1.,  9.]),
  array([ 1., 10.]),
  array([  1.,  11.]),
  array([  1.,  12.]),
  array([  1.,  13.]),
  array([  1.,  14.]),
  array([  1.,  15.]),
  array([  1.,  16.]),
  array([  1.,  17.]),
  array([  1.,  18.]),
  array([  1.,  19.])])

然后我应该将其与多维polyfit情况下的fit变量进行比较。在

更改上一个函数以返回fitres

^{pr2}$

合身似乎很相配。所以大概问题出在poly1d步骤上。在

相关问题 更多 >