gpt4 book ai didi

python - 如何更改问题求解格式以使用 lambda 和/或映射 (Python)

转载 作者:行者123 更新时间:2023-12-05 06:53:16 24 4
gpt4 key购买 nike

我正在尝试编写以下公式:

enter image description here

为此,我使用了以下函数:

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

在下图中,您可以看到输入和输出的示例:

enter image description here

地点:

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

然而,它似乎无法正常工作。在下图中,您可以找到在函数中使用 lambdamap 的输出示例。

enter image description here

我认为我不太了解如何将 lambda 应用于这个特定问题,因此非常感谢您的帮助!!

最佳答案

我认为它现在应该可以工作了,

请求的解决方案

代码语法

w = [0.7237871780107422, -1.7994691458244925]
x = [0., 0.11111111, 0.22222222, 0.33333333, 0.44444444, 0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ]

powers = list(range(0, len(w)))
print("power list: ", powers)
print("w: ", w)
lista = list(map(lambda rng, x: w[rng] * (x ** rng) ,powers, x))

print(lista)

输出

power list:  [0, 1]
w: [0.7237871780107422, -1.7994691458244925]

[0.7237871780107422, -0.19994101420331123]

[Program finished]

说明

不给你所需输出的原因是你不能操作 pow() 或与其他人一起操作完整列表,你必须迭代两个列表才能给你所需的输出。

例如:

Giving listA = [1, 2, 3], and listB = [1, 2, 2]. If you want to operate both lists, you've to iterate them, first.

代码语法

listC = list(map(lambda x, y: x ** y, listA, listB))

输出

[1, 4, 9]

[Program finished]

或者,您可以只使用 map() 进行数学运算

代码语法

listC2 = list(map(pow, listA, listB))

输出

[1, 4, 9]

[Program finished]

关于python - 如何更改问题求解格式以使用 lambda 和/或映射 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65821547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com