function [f,g] = error_log(q,x,t,lambda);

% ERROR_LOG  Deviance for logistic regression.
%
% Input:
%
% q:      1 x (ninp+1) vector with weights and threshold
% x:      ninp x ndat input matrix
% t:      1 x ndat output vector
% lambda: regularization parameter [0]
%
% Output:
%
% f: deviance
% g: gradient

if nargin < 4,
  lambda = 0;
end

[ninp,npat] = size(x);
w = q(1:ninp);
if length(q) > ninp,
  b = q(ninp+1);
else
  b = 0;
end

p = 1./(1+exp(-(w*x+b)));

f = (-t*log(p+1e-10)'-(1-t)*log(1-p+1e-10)')/npat + lambda*([w,b]*[w,b]')/2;

if length(q) > ninp,
  g = [(p-t)*x',sum(p-t)]/npat;
else
  g = (p-t)*x'/npat;
end

if lambda,
  g = g + lambda*[w,b];
end
