计算sigmoid函数

时间:2016-07-31 01:53:41

标签: matlab machine-learning sigmoid

我正在从课程中学习机器学习。我正在尝试计算sigmoid函数,我有以下代码:

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

% You need to return the following variables correctly 

g = zeros(size(z));

% ====================== YOUR CODE HERE ======================

% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
%               vector or scalar).



g = (1 + exp(-1 * z)) .^ -1;
 g = 1/(1+ (1/exp(z)))


% my question is why the first g calculation works for matrix(say 100*2) however the second only works for (100*1) as both are trying to do the same this.


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

end

9 个答案:

答案 0 :(得分:3)

正确答案

rt=-z;  %changing sign of z
rt=rt';  %transposing matrix

g=1./(1+e.^(rt));   %you need to use dot(.) while dividing and also while finding power to apply those operation for every element in the matrix.

回答你的问题

1.g = (1 + exp(-1 * z)) .^ -1;
2.g = 1/(1+ (1/exp(z)))           

你在第二个函数中错过了点运算符(。),而第一个函数用于exp()。

答案 1 :(得分:3)

您可能想要尝试的是利用元素操作(来自Octave官方文档here的更多信息)。

请注意,使用元素操作:

  

当你有两个相同大小的矩阵时,你可以对它们执行逐元素操作

因此定义的g和z具有相同的大小,下面的代码应该返回Sigmoid函数。

g = (g.+1)./(1 + e.^-z);

从本质上讲,它做了两件简单的事情。首先,它将零点矩阵或标量变为一个带有" 1"。然后它为每个对应元素划分每个元素(1 + e z )。

答案 2 :(得分:3)

S型函数g(z)= 1 /(1 + e ^(-z))

八度看起来像

g = 1 //(1 + exp(-z));

答案 3 :(得分:0)

。^适用于矩阵中的每个元素。 / 才不是。 ./可能(虽然您可能需要制作一些1的1的矩阵)

答案 4 :(得分:0)

你需要使用for循环将sigmoid函数应用于向量或矩阵的每个元素。

答案 5 :(得分:0)

在后一种情况下,您尝试将多维矩阵与1相乘(除以逆),该矩阵实际上是一个一对一的矩阵。因此,对于具有多列的矩阵,将导致“矩阵尺寸必须一致”错误。

答案 6 :(得分:0)

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

% You need to return the following variables correctly 
g = zeros(length(z),1);

for  i = 1:100,
  g(i) = 1/(1 + exp(-z(i)));

end

答案 7 :(得分:0)

以下是Octave中的实现:

请在文件名sigmoid.m中添加以下代码

function g = sigmoid(z)
g = 1 ./ (1+((e).^(-z)));
end

以下是上述实现中的Vector个示例:

>> A = [1;2;3]
A =

   1
   2
   3

>> sigmoid(A)
ans =

   0.73106
   0.88080
   0.95257

以下是上述实现中的Scalar个示例:

>> sigmoid(0)
ans =  0.50000

答案 8 :(得分:0)

好吧,你可以这样做:

g = ones(size(z)) ./ (ones(size(z)) + exp(-1 * z));

将1变成z/g维数的数组,然后计算sigmoid。

相关问题