梯度下降需要太多迭代才能收敛

2024-04-18 20:45:46 发布

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

梯度下降似乎并不收敛

我正在使用Python从头开始做梯度下降(没有sklearn),在Boston住房数据集(房间数量与平均成本)上实现线性回归。你知道吗

Scikit Learn的线性回归为我提供了以下斜率/截距,与数据完美吻合。 斜率=[9.10210898] 截距=-34.67062077643854

然而,梯度下降甚至不接近。你知道吗

import numpy as np
import matplotlib.pyplot as plt

l_rate = 0.0001 # Learning rate
steps = 100000    # number of iterations ( steps )

m = 0.0 # initial slope
b = 0.0 # initial intercept

n = len(x)

cost_array = np.empty([steps],dtype="float64")

# Start Gradient Descent
for step in range(steps) :
    y_pred = m * x + b

    # Derivative of the cost function w.r.t slope (m)
    m_der  = (-1/n) * sum( (y - y_pred) * x)

    # Derivative of the cost function w.r.t intercept (b)    
    b_der  = (-1/n) * sum( y - y_pred )

    # move m
    m = m -  l_rate * m_der
    b = b -  l_rate * b_der

    cost = (1/(2*n)) * np.sum(np.square(y - y_pred))
    cost_array[step] = cost

我希望在学习率有多种变化的情况下(比如在0.1&0.0000001之间),解决方案应该在5000次迭代中收敛。然而,斜率和截距的完美值(由SKLearn的线性回归计算)只有在100K次迭代之后才能实现。你知道吗

显然,我做错了什么。你能帮我找出哪里出了问题吗?你知道吗


Tags: of数据importrateasnp线性steps