首页 文章

线性回归差梯度下降性能

提问于
浏览
5

我在C中实现了一个简单的线性回归(单个变量)示例,以帮助我理解这些概念 . 我很确定关键算法是正确的,但我的表现非常糟糕 .

这是实际执行梯度下降的方法:

void LinearRegression::BatchGradientDescent(std::vector<std::pair<int,int>> & data,float& theta1,float& theta2)
{

    float weight = (1.0f/static_cast<float>(data.size()));
    float theta1Res = 0.0f;
    float theta2Res = 0.0f;

    for(auto p: data)
    {

        float cost = Hypothesis(p.first,theta1,theta2) - p.second;
        theta1Res += cost;
        theta2Res += cost*p.first;
    }   

    theta1 = theta1 - (m_LearningRate*weight* theta1Res);
    theta2 = theta2 - (m_LearningRate*weight* theta2Res);
}

其他关键功能如下:

float LinearRegression::Hypothesis(float x,float theta1,float theta2) const
{
    return theta1 + x*theta2;
}


float LinearRegression::CostFunction(std::vector<std::pair<int,int>> & data,
                                     float theta1,
                                     float theta2) const
{ 
    float error = 0.0f;
    for(auto p: data)
    {

        float prediction = (Hypothesis(p.first,theta1,theta2) - p.second) ;
        error += prediction*prediction;
    }

    error *= 1.0f/(data.size()*2.0f);
    return error;
}

void LinearRegression::Regress(std::vector<std::pair<int,int>> & data)
{
    for(unsigned int itr = 0; itr < MAX_ITERATIONS; ++itr)
    {
       BatchGradientDescent(data,m_Theta1,m_Theta2);
       //Some visualisation code
    }
}

现在的问题是,如果学习率大于0.000001,则梯度下降后的成本函数的值高于之前的值 . 也就是说,算法反向运行 . 线很快地通过原点形成一条直线,但是然后需要 millions 次迭代来实际到达一条相当合适的线 .

学习率为0.01,经过六次迭代后输出为:(差异为costAfter-costBefore)

Cost before 102901.945312, cost after 517539430400.000000, difference 517539332096.000000
Cost before 517539430400.000000, cost after 3131945127824588800.000000, difference 3131944578068774912.000000
Cost before 3131945127824588800.000000, cost after 18953312418560698826620928.000000, difference 18953308959796185006080000.000000
Cost before 18953312418560698826620928.000000, cost after 114697949347691988409089177681920.000000, difference 114697930004878874575022382383104.000000
Cost before 114697949347691988409089177681920.000000, cost after inf, difference inf
Cost before inf, cost after inf, difference nan

在这个例子中,thetas设置为零,学习率为0.000001,并且有8,000,000次迭代!可视化代码仅在每100,000次迭代后更新图形 .

enter image description here

创建数据点的函数:

static void SetupRegressionData(std::vector<std::pair<int,int>> & data)
{
    srand (time(NULL));

    for(int x = 50; x < 750; x += 3)
    {
        data.push_back(std::pair<int,int>(x+(rand() % 100), 400 + (rand() % 100) ));
    }
}

简而言之,如果我的学习速率太高,则梯度下降算法有效地向后运行并趋于无穷大,并且如果它降低到实际收敛到最小值的点,则实际这样做所需的迭代次数是不可接受的高 .

我是否错过了核心算法中的任何错误/错误?

1 回答

  • 5

    看起来一切都表现得如预期,但您在选择合理的学习率方面遇到了问题 . 这不是一个完全无关紧要的问题,并且有许多方法,从预定义的时间表,逐步降低学习率(参见例如this paper)到自适应方法,如AdaGrad或AdaDelta .

    对于具有固定学习速率的vanilla实现,您应该在将数据归入梯度下降算法之前将数据归一化为零均值和单位标准差,从而使您的生活更轻松 . 这样您就可以更轻松地推断学习率 . 然后,您可以相应地重新调整预测 .

相关问题