【问题标题】:Gradient Descent - Logistical Regression - Weird thetas梯度下降 - 逻辑回归 - 奇怪的 thetas
【发布时间】:2020-02-25 06:57:47
【问题描述】:

对训练数据运行我的梯度下降函数会产生 [0.3157; 0.0176; 0.0148]。第一个值明显高于其他值。在预测我的测试数据的概率时,最终为 0.42 +- 0.01。这使得概率总是更接近于 0。我相信错误依赖于梯度下降函数。

梯度下降函数

function [theta] = GradientDescent(x, y)
    m = size(x,1);  
    n = size(x,2);  

    theta = zeros(n,1);
    alpha = .005; 
    iterations = 10000; 
    J=[];

    for i = 1:iterations
        h = x * theta;
        theta = theta - (alpha/m)* x' * (h-y);
        J_old = J;
        J = -(1/m) * sum(y .* log(h) + (1 - y) .* log(1-h));
        if((i>2 && abs(J_old - J) < 10^-5))
             break;
        end
        if(any(isnan(theta())))
            disp("breaking the iterations since theta returns NaN values");
            break;
        end
    end
    disp("Performing Gradient descent -  with "+n+" features");
end

主代码-加载数据和运行概率

[X, Y] = LoadData("train_q1.csv");
scatter(X(:, 2), X(:, 3), 25, Y);
% 1 is buy - on the ends
% 0 is sell - in the middle
%============ 1b.
thetas = ones(3, 1);
[theta] = GradientDescent(X, Y);
disp(theta);
% get accuracy
[trainX, trainY] = LoadData("test_q1.csv");

correct = 0;
%probability
for i=1:length(trainY)
    disp(1 ./ (1 + exp(trainX(i, :) * theta)));
    probability = round(1 ./ (1 + exp(trainX(i, :) * theta)));
    if trainY(i) == probability
        correct = correct + 1;
    end
end
disp(correct);
% print accuracy
disp("The model is " + (correct/length(trainY) * 100) + "% correct");

【问题讨论】:

    标签: matlab machine-learning gradient-descent


    【解决方案1】:
    • 您在GradientDescent(..) 函数中使用了h = x * theta 来计算不正确的假设函数。它应该是h = 1./(1 + exp(-x*theta))(注意减号)。
    • 所以当你计算概率时,它应该是disp(1 ./ (1 + exp(-(trainX(i, :) * theta))))。请注意,您没有在 exp() 中包含减号 (-)。

    • 同样在[trainX, trainY] = LoadData("test_q1.csv") 中,名称不正确。它应该是 testX, testY 而不是 trainX, trainY,因为您正在加载一个测试数据集 (test_q1.csv)。

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2015-07-15
      • 2014-03-21
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2014-08-26
      相关资源
      最近更新 更多