machine-learning - Octave 中的线性回归实现
问题描述
我最近尝试在 octave 中实现线性回归,但无法通过在线判断。这是代码
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
for i = 1:m
temp1 = theta(1)-(alpha/m)*(X(i,:)*theta-y(i,:));
temp2 = theta(2)-(alpha/m)*(X(i,:)*theta-y(i,:))*X(i,2);
theta = [temp1;temp2];
endfor
J_history(iter) = computeCost(X, y, theta);
end
end
我知道矢量化实现,但只是想尝试迭代方法。任何帮助,将不胜感激。
解决方案
您不需要内部for
循环。相反,您可以使用该sum
功能。
在代码中:
for iter = 1:num_iters
j= 1:m;
temp1 = sum((theta(1) + theta(2) .* X(j,2)) - y(j));
temp2 = sum(((theta(1) + theta(2) .* X(j,2)) - y(j)) .* X(j,2));
theta(1) = theta(1) - (alpha/m) * (temp1 );
theta(2) = theta(2) - (alpha/m) * (temp2 );
J_history(iter) = computeCost(X, y, theta);
end
实施矢量化解决方案也是一个很好的练习,然后比较它们以了解矢量化在实践中的效率如何。
推荐阅读
- python - PyTorch:尝试更新隐藏状态时出现 LSTM 错误
- python - PyDub OSError: [WinError 6] 句柄无效
- reactjs - Webpack + Linaria - 当前未启用对实验性语法“jsx”的支持
- reactjs - react-router 无法在 LAMP 中进行生产构建
- angular - ng build --prod API 后 Angular 7 8 9 不起作用
- javascript - 如何通过javascript中的“for of”循环将器官插入空数组
- gradle - Gradle artifactory插件不上传zip文件
- javascript - getByteTimeDomainData(网络音频 API)
- git - Eclipse 配置 GIT 稀疏检出
- css - 提高产品页面上 woocommerce 缩略图的质量