"Z" 变量在用于表示 sigmoid 函数的矩阵时未定义

"Z" Variable is undefined when used to represent a matrix for sigmoid function

我是一名高中生,我刚刚开始学习机器学习以进一步提高我的编码知识。我尝试了 Octave 这个程序,并一直在研究神经网络,或者至少尝试过。然而,在我的第一个程序中,我已经发现自己在 Sigmoid 梯度函数方面陷入僵局。当我试图让函数对矩阵中的每个值起作用时,我不知道该怎么做。我尝试将 z 作为函数的参数,但它说 "z" 本身是未定义的。我对 C 或 C++ 没有任何了解,而且我在这方面仍然是一个业余爱好者,如果我需要一些时间来理解,我很抱歉。感谢任何提供帮助的人!

我是 运行 Octave 4.4.1,我还没有尝试任何其他解决方案,因为我真的没有。

% Main Code
    g = sigGrad([-2 -1 0 1 2]);
% G is supposed to be my sigmoid Gradient for each value of Theta, which is the matrix within it's parameters.
% Sigmoid Gradient function
    function g = sigGrad(z)
    g = zeros(size(z));
% This is where the code tells me that z is undefined
    g = sigmoid(z).*(1.-sigmoid(z));
% I began by initializing a matrix of zeroes with the size of z
% It should later do the Gradient Equation, but it marks z as undefined before that
% Sigmoid function
    g = sigmoid(z)
    g = 1.0 ./ (1.0 + exp(-z));

据我所知,我发现您犯了一些简单的语法错误,我建议您先了解八度的要点,而不是一头扎进代码中。话虽如此,您必须使用正确的语法声明函数并按如下所示使用它们:

function g = sigmoid(z)
%   SIGMOID Compute sigmoid function
%   J = SIGMOID(z) computes the sigmoid of z.

g = 1.0 ./ (1.0 + exp(-z));
end

而另一段代码应该是

function g = sigGrad(z)
%   sigGrad returns the gradient of the sigmoid function evaluated at z
%   g = sigGrad(z) computes the gradient of the sigmoid function evaluated at z. 
%   This should work regardless if z is a matrix or a vector.
%   In particular, if z is a vector or matrix, you should return the gradient for each element.

g = zeros(size(z));

g = sigmoid(z).*(1 - sigmoid(z));

end

最后调用上面实现的函数使用:

g = sigGrad([1 -0.5 0 0.5 1]);