Skip to main content
 首页 » 编程设计

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

2025年05月04日10飞鱼

我以为我了解 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再次被滥用。