理解这个lambda函数是如何工作的

Ada*_*tra 1 python lambda

我以为我理解lambda函数是如何工作的,尽管我自己并没有使用它们.但是本教程下面的lambda 完全让我感到困惑:

import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_model
import matplotlib
Run Code Online (Sandbox Code Playgroud)

那很简单.更多:

# 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)
Run Code Online (Sandbox Code Playgroud)

现在这行我不明白:

plot_decision_boundary(lambda x: clf.predict(x))
Run Code Online (Sandbox Code Playgroud)

我已多次读过lambdas如何工作,但我只是不知道x这里如何通过正确的值.如何x映射到相关值?

tde*_*ney 7

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

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

def call_clf_predict(x):
    return clf.predict(x)
plot_decision_boundary(call_clf_predict)
Run Code Online (Sandbox Code Playgroud)

在这里,它更清楚发生了什么.plot_decision_boundary得到一个可调用的并使用单个参数调用它np.c_[xx.ravel(), yy.ravel()].

但是首先不应该使用lambda.你可以做到

plot_decision_boundary(clf.predict)
Run Code Online (Sandbox Code Playgroud)

在python教程的传统中,lambda再次被滥用.

  • 你是对的,它不使用它就可以工作。非常非常有趣。 (2认同)