我想把下面的函数矢量化
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.]
^{} 方法返回多项式系数,最高幂优先。在
^{} 方法要求系数首先具有最低幂次。当将一个方法的输出输入到另一个方法时,请考虑这一点。在
而且,
polyval
的x参数不合逻辑:np.zeros(len(pnp_array))
。为什么要多次要求polyval
在同一点0求值多项式?尤其是因为你的非矢量化函数计算了win_size
处的多项式。要与非矢量化方法一致,请替换行与
^{pr2}$那么测试用例的两个输出是相同的。在
为什么我不知道多项式的代表性呢?但这是你自己决定的。)
第一步是比较两种方法的中间值
例如,我可以跟踪
polyfit
步骤然后我应该将其与多维polyfit情况下的
fit
变量进行比较。在更改上一个函数以返回
^{pr2}$fit
和res
:合身似乎很相配。所以大概问题出在
poly1d
步骤上。在相关问题 更多 >
编程相关推荐