使用梯度下降的线性回归;成本函数值有问题

Linear regression using gradient descent; having trouble with cost function value

我正在使用梯度下降对线性回归进行编码。通过使用 for 循环而不是张量。

我认为我的代码在逻辑上是正确的,当我绘制图形时,theta 值和线性模型似乎都很好。但是成本函数的价值很高。你能帮帮我吗?

代价函数的值为1,160,934,异常

def gradient_descent(alpha,x,y,ep=0.0001, max_repeat=10000000):
    m = x.shape[0]
    converged = False
    repeat = 0
    theta0 = 1.0
    theta3 = -1.0
#     J=sum([(theta0 +theta3*x[i]- y[i])**2 for i in range(m)]) / 2*m #######
    J=1
    
    while not converged : 
        grad0= sum([(theta0 +theta3*x[i]-y[i]) for i in range (m)]) / m
        grad1= sum([(theta0 + theta3*x[i]-y[i])*x[i] for i in range (m)])/ m
        
        temp0 = theta0 - alpha*grad0
        temp1 = theta3 - alpha*grad1
        
        theta0 = temp0
        theta3 = temp1
    
        msqe = (sum([(theta0 + theta3*x[i] - y[i]) **2 for i in range(m)]))* (1 / 2*m)
        print(theta0,theta3,msqe)
        if abs(J-msqe) <= ep:
            print ('Converged, iterations: {0}', repeat, '!!!')
            converged = True
        
        J = msqe
        repeat += 1
        
        if repeat == max_repeat:
                converged = True
                print("max 까지 갔다")
   
    return theta0, theta3, J
[theta0,theta3,J]=gradient_descent(0.001,X3,Y,ep=0.0000001,max_repeat=1000000)

print("************\n theta0 : {0}\ntheta3 : {1}\nJ : {2}\n"
          .format(theta0,theta3,J))

This is the data set.

我认为数据集本身非常广泛,这就是最佳拟合线显示大量成本函数的原因。如果您缩放数据 - 您会发现它显着下降。

在处理具有巨大方差的大型数据集时,成本高是很正常的。此外,您的数据正在处理大量数据,因此成本非常高,规范化数据将为您提供正确的估计,因为规范化数据不需要缩放。试试这个验证从随机wrights开始,每次观察成本如果成本在很大范围内波动那么可能有一些错误,否则它很好。