1

我正在尝试实现前馈反向传播自动编码器(使用渐变下降进行训练)并希望验证是否正确计算渐变。这个tutorial建议一次计算一个参数的导数:grad_i(theta) = (J(theta_i+epsilon) - J(theta_i-epsilon))/(2*epsilon)。我已经在Matlab中编写了一段样例代码来做这件事,但没有多少运气 - 由导数计算出的梯度与通过数值发现的梯度之间的差异趋于较大(>> 4个有效数字)。检查渐变下降时的渐变

如果有人可以提供任何建议,我将非常感谢帮助(无论是在我的梯度计算或我如何执行检查)。因为我已经大大简化了代码以使其更具可读性,所以我没有包含偏见,也不再捆绑权重矩阵。

首先,我初始化变量:

numHidden = 200; 
numVisible = 784; 
low = -4*sqrt(6./(numHidden + numVisible)); 
high = 4*sqrt(6./(numHidden + numVisible)); 
encoder = low + (high-low)*rand(numVisible, numHidden); 
decoder = low + (high-low)*rand(numHidden, numVisible); 

接着,给定的一些输入图像x,不用前馈传播:

a = sigmoid(x*encoder); 
z = sigmoid(a*decoder); % (reconstruction of x) 

我使用的损失函数是标准Σ (0.5 *(z-x)^ 2)):

% first calculate the error by finding the derivative of sum(0.5*(z-x).^2), 
% which is (f(h)-x)*f'(h), where z = f(h), h = a*decoder, and 
% f = sigmoid(x). However, since the derivative of the sigmoid is 
% sigmoid*(1 - sigmoid), we get: 
error_0 = (z - x).*z.*(1-z); 

% The gradient \Delta w_{ji} = error_j*a_i 
gDecoder = error_0'*a; 

% not important, but included for completeness 
% do back-propagation one layer down 
error_1 = (error_0*encoder).*a.*(1-a); 
gEncoder = error_1'*x; 

and fin盟友,检查梯度是正确的(在这种情况下,只是做它的解码器):

epsilon = 10e-5; 
check = gDecoder(:); % the values we obtained above 
for i = 1:size(decoder(:), 1) 
    % calculate J+ 
    theta = decoder(:); % unroll 
    theta(i) = theta(i) + epsilon; 
    decoderp = reshape(theta, size(decoder)); % re-roll 
    a = sigmoid(x*encoder); 
    z = sigmoid(a*decoderp); 
    Jp = sum(0.5*(z - x).^2); 

    % calculate J- 
    theta = decoder(:); 
    theta(i) = theta(i) - epsilon; 
    decoderp = reshape(theta, size(decoder)); 
    a = sigmoid(x*encoder); 
    z = sigmoid(a*decoderp); 
    Jm = sum(0.5*(z - x).^2); 

    grad_i = (Jp - Jm)/(2*epsilon); 
    diff = abs(grad_i - check(i)); 
    fprintf('%d: %f <=> %f: %f\n', i, grad_i, check(i), diff); 
end 

在MNIST数据集(对于第一个条目)运行此给出的结果,如:

2: 0.093885 <=> 0.028398: 0.065487 
3: 0.066285 <=> 0.031096: 0.035189 
5: 0.053074 <=> 0.019839: 0.033235 
6: 0.108249 <=> 0.042407: 0.065843 
7: 0.091576 <=> 0.009014: 0.082562 

回答

0

在a和z上都不要sigmoid。只需在z上使用它。

a = x*encoder; 
z = sigmoid(a*decoderp);