【问题标题】:Calculate the sigmoid function计算 sigmoid 函数
【发布时间】:2016-12-05 10:12:24
【问题描述】:
我正在从 coursera 学习机器学习。我正在尝试计算 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
【问题讨论】:
标签:
matlab
machine-learning
sigmoid
【解决方案1】:
好吧,你可以这样:
g = ones(size(z)) ./ (ones(size(z)) + exp(-1 * z));
把1变成一个z/g维度的数组,然后计算sigmoid。
【解决方案2】:
以下是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
【解决方案3】:
Sigmoid函数g(z)=1/(1+e^(-z))
在八度音程中看起来像
g = 1./(1 + exp(-z));
【解决方案4】:
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
【解决方案5】:
在后一种情况下,您正在尝试乘以(依法)多维矩阵,其中1个是字面上是一个逐个矩阵。因此,它将导致“矩阵尺寸必须同意具有多个列的矩阵的错误”。
【解决方案6】:
您可能想要尝试的是利用元素操作(更多信息来自 Octave 官方文档here)。
注意元素操作:
当你有两个大小相同的矩阵时,你可以对它们进行逐个元素的操作
所以定义的 g 和 z 大小相同,下面的代码应该返回 Sigmoid 函数。
g = (g.+1)./(1 + e.^-z);
所以本质上,它做了两件简单的事情。首先,它将零矩阵或标量变成一个“1”。然后它将每个元素除以每个对应元素的 (1 + ez)。
【解决方案7】:
正确答案
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() 的第一个函数中错过了点运算符 (.)。
【解决方案8】:
您需要使用 for 循环将 sigmoid 函数应用于向量或矩阵的每个元素。
【解决方案9】:
.^ 适用于矩阵中的每个元素。 / 才不是。 ./ 可能(尽管您可能需要制作一些 1 的矩阵)