小编nos*_*san的帖子

线性回归的梯度下降不起作用

我正在尝试为线性回归实现一个简单的梯度下降算法.我正在使用Armadillo C++线性代数库,而且我也是Armadillo的新手.这就是我想要做的:

void linRegression(mat &features, mat &targets, double alpha,double error){
    mat theta = ones(features.n_cols+1);
    mat temp = zeros(features.n_cols+1);
    mat features_new = join_horiz(ones(features.n_rows),features);
    mat predictions;
    double con = alpha*(1.0/features.n_rows);
    int j = 0;
    while(j<1000){
        mat step_error = (features_new*theta - targets);
        for(unsigned int i=0;i<theta.n_rows;i++){
            temp(i) = con*sum(step_error%features_new.col(i));
        }
        theta = theta-temp;
        mat pred = predict(theta,features_new);
        cout<<theta<<endl;
        j++;
    }
}
Run Code Online (Sandbox Code Playgroud)

但theta的值不断增加并最终达到无穷大.我不确定我做错了什么.

c++ machine-learning data-analysis linear-regression armadillo

0
推荐指数
1
解决办法
408
查看次数