【问题标题】:lambda: what's the output that a lambda function multiply numpy array?lambda:lambda 函数乘以 numpy 数组的输出是什么?
【发布时间】:2017-10-24 08:20:02
【问题描述】:

我正在用 python 学习机器学习。我从那本书中阅读了以下代码。

x, y = np.array(x), np.array(y)
x = (x - x.mean()) / x.std()

x0 = np.linspace(-2, 4, 100)

def get_model(deg):
    return lambda input_x=x0: np.polyval(np.polyfit(x, y, deg), input_x)

def get_cost(deg, input_x, input_y):
    return 0.5 * ((get_model(deg)(input_x) - input_y) ** 2).sum()

我不知道为什么在get_cost 函数中,作者使用get_model(deg) 乘以input_x 即为x。据我了解,get_model(deg) 函数已经返回基于x0 预测的y

当我试图了解发生了什么时,我输入了get_model(4),然后它返回了<function __main__.get_model.<locals>.<lambda>>。令我惊讶的是,它没有返回基于x0 预测的y 而是一个函数?!我完全搞砸了。

当我尝试输入get_model(4)(x) 时,它只是返回基于x 预测的y,我不明白。请有人可以帮我弄清楚。

【问题讨论】:

  • 那不是乘法。 get_model 是一个返回另一个函数的函数。
  • @user2357112 说得通。

标签: python python-3.x numpy lambda


【解决方案1】:

如您所见,get_model(x) 方法不是返回预测,而是用于预测的模型。 如果您执行get_model(1),该方法将返回一个线性模型,它允许您将值拟合到一个线性函数中:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.gcf()
fig.set_size_inches(10, 5)

x = np.linspace(-2, 4, 200)
y = x**2 
y += np.random.rand(len(x)) * 10
x0= x

def get_model(deg):
    return lambda input_x=x0: np.polyval(np.polyfit(x, y, deg), input_x)

linear_model = get_model(1)

plt.scatter(x, y)
plt.scatter(x, linear_model(), c='red')

plt.show()

如果你想尝试其他模型,你可以通过改变模型的度数来做到这一点:

plt.scatter(x, y)
plt.scatter(x, get_model(2)(), c='red')
plt.scatter(x, get_model(19)(), c='yellow')

plt.show()

我希望这可以帮助您更好地理解代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2020-01-13
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多