简单线性回归中成本函数的应用

2024-04-24 16:59:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我是机器学习的新手,我研究过成本函数背后的数学。我想知道在哪里实现线性回归的成本函数,即J(B1,B2)=1/2n∑(y-y∗pred)^2?你知道吗

在下面的代码中没有使用成本函数,因为我们在预测值之后计算成本函数。当我检查代码时,我没有看到任何错误。最小化步骤。 代码可用here

import numpy as np
import matplotlib.pyplot as plt



def estimate_coef(X, y):

    n = np.size(X)

    m_X, m_y = np.mean(X), np.mean(y)

    SS_Xy = np.sum(y*X) - n*m_y*m_X
    SS_XX = np.sum(X*X) - n*m_X*m_X

    b_1 = SS_Xy / SS_XX

    b_0 = m_y - b_1*m_X

    return (b_0, b_1)

def plot_regression_line(X, y, b):
    n = np.size(X)
    plt.scatter(X, y, color = "m", 
               marker = "o", s = 30) 
    y_pred = b[0] + b[1]*X
    print(f'prediction=>{y_pred}')
    plt.plot(X, y_pred, color = "g")
    plt.xlabel('x') 
    plt.ylabel('y')
    plt.show() 

def main(): 
    # observations 
    X = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 
    y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12]) 

    # estimating coefficients 
    b = estimate_coef(X, y) 
    print(f'b_0=>{b[0]}, b_1=>{b[1]}') 



    # plotting regression line 
    plot_regression_line(X, y, b) 

if __name__ == "__main__": 
    main()

Tags: 函数代码importplotmaindefasnp
1条回答
网友
1楼 · 发布于 2024-04-24 16:59:11

需要解决的最小化问题是b0和b1,即我们需要找到两者的最佳值。当你解决最小化问题时,你会得到b_1 = SS_Xy / SS_XXb_0 = m_y - b_1*m_X。他们没有在代码中解决最小化问题,而是直接使用结果来获得最优值。文章中提到了这一点:

Our task is to find the value of b_0 and b_1 for which J(b_0,b_1) is minimum!

Without going into the mathematical details, we present the result here:

相关问题 更多 >