python - 了解此 lambda 函数的工作原理

标签 python lambda

我以为我了解 lambda 函数的工作原理,尽管我自己并不使用它们。但是下面的 lambda 来自 this tutorial完全难住了我:

import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_model
import matplotlib

这很容易。更多:

# Generate a dataset and plot it
np.random.seed(0)
X, y = sklearn.datasets.make_moons(200, noise=0.20)
plt.scatter(X[:,0], X[:,1], s=40, c=y, cmap=plt.cm.Spectral)
clf = sklearn.linear_model.LogisticRegressionCV()
clf.fit(X, y)

# Helper function to plot a decision boundary.
# If you don't fully understand this function don't worry, it just generates the contour plot below.

def plot_decision_boundary(pred_func):

    # Set min and max values and give it some padding
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    h = 0.01

    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    # Predict the function value for the whole gid
    Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)

现在我不明白的行:

plot_decision_boundary(lambda x: clf.predict(x))

我读过很多次 lambda 的工作原理,但我只是不明白这里的 x 是如何传递之前的正确值的。 x 是如何映射到相关值的?

最佳答案

lambdas 只是匿名函数。 lambda 主体只能是一个表达式(作为您可以放入函数中的内容的子集),因为它们必须与其他代码内联。

plot_decision_boundary(lambda x: clf.predict(x)) 可以重写为

def call_clf_predict(x):
    return clf.predict(x)
plot_decision_boundary(call_clf_predict)

到这里,更清楚是怎么回事了。 plot_decision_boundary 获取可调用对象并使用单个参数调用它 np.c_[xx.ravel(), yy.ravel()]

但是 lambda 一开始就不应该在这里使用。你可以这样做

plot_decision_boundary(clf.predict)

在python教程的盛大传统中,lambda再次被滥用。

关于python - 了解此 lambda 函数的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34829807/

相关文章:

python - 无法连接到 FTP 服务器

asp.net-mvc - 带有 lambda 表达式的 ASP.net MVC 操作 URL

javascript - 如何从jsondata中获取key的值

c++ - 如果它包含多个语句,是否有理由不允许 lambdas 推断返回类型?

python - 根据条件拆分 Python 列表

python - 为什么添加和分配 (+=) 与 numpy.ndarrays 行为异常?

python - 使用带有高级运算符的 python 的功能管道

haskell - 函数组合 (.) 如何从内部工作?

python - App Engine 应用程序中的 CORS(python)

python - 如何格式化 Python 线图 Bokeh/matplotlib 日期时间和图形问题的日期时间