首页 > 解决方案 > matplotlib上线性回归一个变量的成本函数

问题描述

我正在尝试使用 matplotlib 打印抛物面,这是简单线性回归的成本函数。问题是函数看起来不是抛物面...... 这里的线性回归 假抛物面这里 完美的直线是权重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()

标签: pythonmatplotlibmachine-learninglinear-regression

解决方案


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

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

在此处输入图像描述


推荐阅读