matlab - 梯度下降 - 逻辑回归 - 奇怪的 thetas
问题描述
针对训练数据运行我的梯度下降函数会产生 [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");
解决方案
- 您已在函数
h = x * theta
内部使用GradientDescent(..)
来计算不正确的假设函数。应该是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)。
推荐阅读
- android - Android上的配置文件
- php - PHP E_NOTICE 最佳实践 - 检查未定义的 var 的值是否不好?
- firebase - 如何只允许向实时数据库添加新条目?
- reactjs - 在 react-admin 中从 redux-form 访问 change() 的简单方法?
- python - 正则表达式 - 不包括单词但带有通配符
- amazon-web-services - 如何使用 Terraform 在 AWS API Gateway 部署阶段分配标签
- swift - Swift 类型推断和基本加法
- video - 是否可以在不使用 ffmpeg 更改其起始代码的情况下将 HEVC 附件 B 原始视频文件混合到容器(mp4、mkv..etc)中
- amazon-s3 - 导入笔记本时出现 Databricks 错误:请求存储桶位置时必须指定存储桶名称参数
- ios - UIView 动画 shadowPath 不跟随