【问题标题】:Plotting log likelihood as a function of theta1 and theta2绘制对数似然函数作为 theta1 和 theta2 的函数
【发布时间】:2020-11-29 11:11:20
【问题描述】:

我被要求将逻辑回归模型的对数似然绘制为 theta1 和 theta2 的函数,以评估其是否为凸函数(模型只有两个参数,theta 是每个参数的权重)。我的理解是我需要一个笛卡尔图,每个轴都表示 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 的函数?

【问题讨论】:

    标签: python logistic-regression log-likelihood


    【解决方案1】:

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

    # 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()
    

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 1970-01-01
      • 2018-08-18
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      相关资源
      最近更新 更多