首页 > 解决方案 > 绘制对数似然函数作为 theta1 和 theta2 的函数

问题描述

我被要求将逻辑回归模型的对数似然绘制为 theta1 和 theta2 的函数,以评估其是否为凸函数(模型只有两个参数,thetas 是每个参数的权重)。我的理解是我需要一个笛卡尔图,每个轴都表示 thetas 的值。负对数似然给出为(在代码中):

sigma = sigmoid(np.dot(x, weight))
loss = -1/size * np.sum(y * np.log(sigma)) + (1 - y) * np.log(1-sigma)

如何在 Python 中将此函数绘制为 theta1 和 theta2 的函数?

标签: pythonlogistic-regressionlog-likelihood

解决方案


正如您所说,您可以通过将对数似然绘制为模型参数的函数来可视化损失情况。可视化的常用方法是创建等高线图。为了得到一个好的解决方案,你需要确保你有大量的样本,并且你的权重是负对数似然的最佳选择。请参阅下面的一些伪代码。

# Use numpy and matplotlib.
import numpy as np
import matplotlib.pyplot as plt

# The size of the neighborhood around the point to visualize.
nbh = 0.25

# Create a mesh grid of the parameters within the specified neighborhood.
w1_space = np.linspace(weight[0]-nbh, weight[0]+nbh, 100)
w2_space = np.linspace(weight[1]-nbh, weight[1]+nbh, 100)
w1, w2 = np.meshgrid(w1_space, w2_space)

# Assuming loss is a function of the weights, 
# compute the negative log-likehood for points within the given subspace.
nlls = np.array(list(map(loss, zip(w1.flatten(), w2.flatten())))).reshape(w1.shape)

# Plot the result using matplotlib.
plt.figure()
plt.contourf(w1, w2, nlls)
plt.show()

推荐阅读