【发布时间】:2021-01-21 05:16:26
【问题描述】:
我正在尝试编写以下公式:
为此,我使用以下函数:
def predict(x, w):
"""
Function to predict y(x, w) based on the values of x and w.
Args:
x: a vector including all the values of the input variable x for a given set of point.
w: polynomial coefficient vector.
Returns: an array with the predicted values for y(x, w) function.
"""
x = np.array(x)
w = np.array(w)
# list of powers for x. {0, 1, 2 ... M}
powers = list(range(0, len(w)))
# apply the polynomial fitting function to each value of vectors x & w
sumatoria_list = sum(np.array([w[i] * (x ** i) for i in powers]))
# return final sum
return sumatoria_list
在下图中,您可以看到输入和输出的示例:
地点:
w0 = [-0.17594739490150393]
w1 = [0.7237871780107422, -1.7994691458244925]
x = array([0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ])
到目前为止,我的函数的输出是正确的,但是,我正在尝试使用 lambda:
def predict1(x, w):
"""
Function to predict y(x, w) based on the values of x and w.
Args:
x: a vector including all the values of the input variable x for a given set of point.
w: polynomial coefficient vector.
Returns: an array with the predicted values for y(x, w).
"""
x = np.array(x)
w = np.array(w)
# list of powers for x. {0, 1, 2 ... M}
powers = list(range(0, len(w)))
# apply the polynomial fitting function to each value of vectors x & w
sumatoria_list = list(map(lambda x, w, i: w * (x ** i), x, w, powers))
# return final sum
return sumatoria_list
尽管如此,它似乎无法正常工作。在下图中,您可以找到在函数中使用lambda 和map 的输出示例。
我认为我不太了解如何将 lambda 应用于此特定问题,因此非常感谢您的帮助!
【问题讨论】:
-
在您的正确代码中,您是否获得了
sum(np.array([w[i] * (x ** i) for i in powers]))的矢量输出?这似乎不对!
标签: python lambda map-function