调用polyfit

时间:2019-11-22 08:07:19

标签: numpy

这里是numpy / python的新功能,试图找出一些不太像c的,更像numpy的编码样式。

背景

我已经完成了一些代码,这些代码需要一组固定的x值和多组相应的y值集,并试图找出y值的哪一组是“最线性的”。

通过在循环中遍历每组y值,通过将这些y与x的直线拟合来计算并存储残差,然后在循环完成查找最小残差值的索引后进行操作。

...抱歉,下面的代码可能更有意义。

import numpy as np
import numpy.polynomial.polynomial as poly

# set of x values
xs = [1,22,33,54]

# multiple sets of y values for each of the x values in 'xs'
ys = np.array([[1, 22, 3, 4],
               [2, 3, 1, 5],
               [3, 2, 1, 1],
               [34,23, 5, 4],
               [23,24,29,33],
               [5,19, 12, 3]])

# array to store the residual from a linear fit of each of the y's against x
residuals = np.empty(ys.shape[0])

# loop through the xs's and calculate the residual of a linear fit for each
for i in range(ys.shape[0]):
    _, stats = poly.polyfit(xs, ys[i], 1, full=True)
    residuals[i] = stats[0][0]

# the 'most linear' of the ys's is at np.argmin:
print('most linear at', np.argmin(residuals))

问题

我想知道是否有可能将其“ numpy'ize”成单个表达式,例如

残差= get_residuals(xs,ys)

...我尝试过:

我尝试了以下方法,但是没有运气(它总是将完整的数组传递进来,而不是逐行传递):

# ------ ok try to do it without a loop --------

def wrap(x, y):
    _, stats = poly.polyfit(x, y, 1, full=True)
    return stats[0][0]


res = wrap(xs, ys)   # <- fails as passes ys as full 2D array

res = wrap(np.broadcast_to(xs, ys.shape), ys)  # <- fails as passes both as 2D arrays

任何人都可以提供有关如何将其数字化的提示吗?

1 个答案:

答案 0 :(得分:0)

来自numpy.polynomial.polynomial.polyfit docs(不要与不可互换的numpy.polyfit混淆) :

  

x:类似于数组,形状为(M,)

     

y:类似array_,形状为(M,)或(M,K)

您的ys需要换位以使ys.shape[0]等于xs.shape

def wrap(x, y):
    _, stats = poly.polyfit(x, y.T, 1, full=True)
    return stats[0]


res = wrap(xs, ys)

res
Out[]: array([284.57337884,   5.54709898,   0.41399317,  91.44641638,
     6.34982935, 153.03515358])
相关问题