梯度下降不起作用,它返回theta值的增量并达到无穷大

问题描述 投票:0回答:1

这是我在python中的代码。我尝试使用不同的alpha值和不同的实现,但是我没有获得好的theta值,并且以0.000000001学习率转到infinity,您也可以通过此代码给我任何建议...

    def gradient_descent(x,y):
        theta0=theta1=0
        iteration=10000000
        m=len(x)
        alpha=0.000000001
        for i in range(iteration):
            y_pre=theta1*x+theta0            #equation for y_prediction
            theta1d=-(2/m)*sum(x*(y-y_pre))  #finding derivative
            theta0d=-(2/m)*sum(y-y_pre)
            theta1=theta1+alpha*theta1d
            theta0=theta0+alpha*theta0d
            #cost_func=(sum((y-y_pre)**2)/2m
            print("theta1",theta1,"theta0",theta0)
machine-learning regression linear-regression data-science gradient-descent
1个回答
0
投票
def gradient_descent(x,y):
    theta0=theta1=0
    iteration=10000000
    m=len(x)
    alpha=0.000000001
    for i in range(iteration):
        y_pre=theta1*x+theta0            #equation for y_prediction
        theta1d=-(1/m)*sum(x*(y_pre - y))  #finding derivative (modified)
        theta0d=-(1/m)*sum(y_pre - y) #modified
        theta1=theta1+alpha*theta1d
        theta0=theta0+alpha*theta0d
        #cost_func=(sum((y_pre - y)**2)/2m   #modified
        print("theta1",theta1,"theta0",theta0)

用于计算θ值的公式为theta = theta - alpha * partial derivative of the cost function。通常,成本函数定义为cost_func=(sum((y_pre - y)**2)/2m(注意,差异是y_pred-y而不是y-y_pred)。成本函数的偏导数包含y_pre - y而不是y - y_pred。这是您应该如何计算成本函数和theta值的方法。 (尝试使用不同的Alpha值,我没有修改Alpha或迭代次数)

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.