【问题标题】:cost function of Linear regression one variable on matplotlibmatplotlib上线性回归一个变量的成本函数
【发布时间】:2020-08-09 23:07:16
【问题描述】:

我正在尝试使用 matplotlib 打印抛物面,这是简单线性回归的成本函数。问题是该函数看起来不像抛物面...... linear regression here fake paraboloid here 完美的直线是权重 2,偏差 0

def main():
    #create database
    n_samples = 40
    x = np.linspace(0, 20, n_samples)
    y = 2*x + 4*np.random.randn(n_samples)

    #show
    plt.scatter(x, y)
    print_cost_func(x, y)

def cost_func(x: np.ndarray, y: np.ndarray, weight: int, bias: int) -> 
float:
    return np.sum((y - (weight*x + bias))**2) / (2*len(x))


def print_cost_func(x: np.ndarray, y: np.ndarray):
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    weight = np.arange(-50, 50, 0.25)
    bias = np.arange(-50, 50, 0.25)
    weight, bias = np.meshgrid(weight, bias)

    Z = np.zeros((400, 400))
    #i think the problem is here
    for i in range(400):
        for j in range(400):
            Z[i][j] = cost_func(x, y, weight[i][j], bias[i][j])


    # Plot the surface.
    surf = ax.plot_surface(weight, bias, Z, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.title('Cost function')
    plt.xlabel('Weight')
    plt.ylabel('Bias')
    plt.show()

【问题讨论】:

    标签: python matplotlib machine-learning linear-regression


    【解决方案1】:

    在您的代码顶部添加以下内容 -

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import cm
    

    【讨论】:

    • 我已经导入了所有这些包,它运行了,但是如果你看到图像“这里是假抛物面”,它不是抛物面,似乎 ndarray Z 不正确
    • 在我运行脚本时添加了结果。
    【解决方案2】:

    好消息,你有一个抛物面。只是沿偏置轴的梯度非常浅。我知道,因为我只是从统计方法中做一些非常相似的事情,使用 SSE 而不是损失,我得到了相同的情节。尝试将您的体重范围减小到 (-20, 20),您应该会看到更多的抛物线。

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 2019-05-19
      • 2014-12-07
      • 2016-01-13
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-25
      相关资源
      最近更新 更多