gpt4 book ai didi

machine-learning - 梯度下降似乎失败了

转载 作者:行者123 更新时间:2023-11-30 08:20:59 24 4
gpt4 key购买 nike

我实现了梯度下降算法来最小化成本函数,以获得确定图像是否具有良好质量的假设。我在 Octave 中这样做了。这个想法在某种程度上基于 machine learning class 中的算法。作者:吴恩达

因此,我有 880 个值“y”,其中包含从 0.5 到 ~12 的值。我在“X”中有 880 个从 50 到 300 的值,可以预测图像的质量。

遗憾的是,该算法似乎失败了,经过几次迭代后,theta 的值非常小,以至于 theta0 和 theta1 变成“NaN”。我的线性回归曲线有奇怪的值......

这里是梯度下降算法的代码:(theta = Zeros(2, 1);,alpha= 0.01,迭代=1500)

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


tmp_j1=0;
for i=1:m,
tmp_j1 = tmp_j1+ ((theta (1,1) + theta (2,1)*X(i,2)) - y(i));
end

tmp_j2=0;
for i=1:m,
tmp_j2 = tmp_j2+ (((theta (1,1) + theta (2,1)*X(i,2)) - y(i)) *X(i,2));
end

tmp1= theta(1,1) - (alpha * ((1/m) * tmp_j1))
tmp2= theta(2,1) - (alpha * ((1/m) * tmp_j2))

theta(1,1)=tmp1
theta(2,1)=tmp2

% ============================================================

% Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta);
end
end

这是成本函数的计算:

function J = computeCost(X, y, theta)   %

m = length(y); % number of training examples
J = 0;
tmp=0;
for i=1:m,
tmp = tmp+ (theta (1,1) + theta (2,1)*X(i,2) - y(i))^2; %differenzberechnung
end
J= (1/(2*m)) * tmp
end

最佳答案

如果您想知道如何将看似复杂的 for 循环向量化并压缩为单个单行表达式,那么请继续阅读。矢量化形式为:

theta = theta - (alpha/m) * (X' * (X * theta - y))

下面详细解释了我们如何使用梯度下降算法得到这个向量化表达式:

这是微调 θ 值的梯度下降算法: enter image description here

假设给出以下 X、y 和 θ 值:

  • m = 训练样本数量
  • n = 特征数量 + 1

enter image description here

这里

  • m = 5(训练示例)
  • n = 4(特征+1)
  • X = m x n 矩阵
  • y = m x 1 向量矩阵
  • θ = n x 1 向量矩阵
  • xi 是第 ith 个训练示例
  • xj 是给定训练示例中的第 jth 个特征

此外,

  • h(x) = ([X] * [θ])(训练集的预测值的 m x 1 矩阵)
  • h(x)-y = ([X] * [θ] - [y])(我们的预测误差的 m x 1 矩阵)

机器学习的整个目标是最小化预测中的错误。根据上述推论,我们的错误矩阵是 m x 1 向量矩阵,如下所示:

enter image description here

要计算 θj 的新值,我们必须获得所有误差(m 行)乘以训练的第 jth 个特征值的总和即,取出E中的所有值,分别与相应训练示例的第j个特征相乘,然后将它们全部相加。这将帮助我们获得 θj 的新值(希望更好)。对所有 j 个或多个特征重复此过程。用矩阵形式可以写成:

enter image description here

这可以简化为: enter image description here

  • [E]' x [X] 将为我们提供一个行向量矩阵,因为 E' 是 1 x m 矩阵,X 是 m x n 矩阵。但我们感兴趣的是获得一个列矩阵,因此我们转置结果矩阵。

更简洁地说,可以写为: enter image description here

由于(A * B)' = (B' * A')A'' = A,我们也可以将上面写为

enter image description here

这是我们开始时的原始表达式:

theta = theta - (alpha/m) * (X' * (X * theta - y))

关于machine-learning - 梯度下降似乎失败了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10479353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com