繁体   English   中英

如何使用 plot 在 x 轴上循环变量 i 和在 y 轴上循环中的局部变量使用 matplotlib

[英]How to plot loop variable i on x-axis and local variable in the loop on y-axis using matplotlib

我正在使用 numpy 在线性回归上练习梯度下降。 这是我的梯度下降过程:

def batch_gradient_descent(data_points, initial_b, initial_W, lr, iterations):
    b = initial_b
    W = initial_W
    for i in range(iterations): # Calcultes Gradient Descent for n-iterations.
        b, W = gradient_step(b, W, data_points, lr)
        current_cost = cost(b, W, data_points)
        # plt.figure(figsize=(8, 4))
        # plt.plot(i, current_cost, linewidth=1)
        # plt.xlabel("iteration")
        # plt.ylabel("log(L)")
        # plt.title("log(L) After "+str(i)+"th iteration")

    plt.show()
    return [b, W]

我需要使用 matplotlib 到 plot 总共只有两个数字:

  1. x 轴是 i,y 轴是根据每个 i 的 log(cost) 值。

  2. x轴是i,y轴是W中每个元素的值的曲线,是一个5*1的向量。 因此,该图中将有 5 行。

顺便说一下,总迭代次数是 200,这意味着 x 轴上的取值范围应该是 0 - 200。

我的原始解决方案在代码中进行了注释,但它实际绘制的是许多数字,看起来像: 在此处输入图像描述 在此处输入图像描述

这样做的正确方法是什么?

您可以 append 将它们添加到您的xy轴的列表中

x = []
y = []

def batch_gradient_descent(data_points, initial_b, initial_W, lr, iterations):
    b = initial_b
    W = initial_W
    for i in range(iterations): # Calcultes Gradient Descent for n-iterations.
        b, W = gradient_step(b, W, data_points, lr)
        current_cost = cost(b, W, data_points)
        x.append(i)
        y.append(current_cost)
    return [b, W]

然后 plot 就像:

plt.figure(figsize=(8, 4))
plt.plot(x, y, linewidth=1)
plt.xlabel("iteration")
plt.ylabel("log(L)")
plt.title("log(L) After " + str(x[-1]) + "th iteration")
plt.show()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM