plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
bsxfan/meta-embeddings-master
tracer.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_library/test/tracer.m
1,081
utf_8
5e8d7ea9aefc9d1c1cc8161546bd9483
function [w,deriv] = tracer(w,vstring,gstring,jstring) % This is an MV2DF. See MV2DF_API_DEFINITION.readme. % % Applies linear transform y = map(w). It needs the transpose of map, % transmap for computing the gradient. map and transmap are function % handles. if nargin==0 test_this(); return; end if nargin<2 vstring=[]; end if nargin<3 gstring=[]; end if nargin<4 jstring=[]; end if isempty(w) w = @(x)tracer(x,vstring,gstring,jstring); return; end if isa(w,'function_handle') outer = tracer([],vstring,gstring,jstring); w = compose_mv(outer,w,[]); return; end if ~isempty(vstring) fprintf('%s\n',vstring); end deriv = @(g2) deriv_this(g2,gstring,jstring); function [g,hess,linear] = deriv_this(g,gstring,jstring) if ~isempty(gstring) fprintf('%s\n',gstring); end linear = true; hess = @(d) hess_this(d,jstring); function [h,Jd] = hess_this(Jd,jstring) h = []; if nargout>1 if ~isempty(jstring) fprintf('%s\n',jstring); end end function test_this() f = tracer([],'V','G','J'); test_MV2DF(f,randn(5,1));
github
bsxfan/meta-embeddings-master
test_MV2DF_noHess.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_library/test/test_MV2DF_noHess.m
1,125
utf_8
2af48174c2441c011dffbf316b93612d
function test_MV2DF_noHess(f,x0) %id_in = identity_trans([]); %id_out = identity_trans([]); %f = f(id_in); %f = id_out(f); x0 = x0(:); Jc = cstepJacobian(f,x0); Jr = rstepJacobian(f,x0); [y0,deriv] = f(x0); m = length(y0); n = length(x0); J2 = zeros(size(Jr)); for i=1:m; y = zeros(m,1); y(i) = 1; J2(i,:) = deriv(y)'; end c_err = max(max(abs(Jc-J2))); r_err = max(max(abs(Jr-J2))); fprintf('test gradient : cstep err = %g, rstep err = %g\n',c_err,r_err); g2 = randn(m,1); rHess = @(dx) rstep_approxHess(dx,g2,f,x0); cHess = @(dx) cstep_approxHess(dx,g2,f,x0); Hr = zeros(n,n); Hc = zeros(n,n); for j=1:n; x = zeros(n,1); x(j) = 1; Hr(:,j) = rHess(x); Hc(:,j) = cHess(x); end rc_err = max(max(abs(Hr-Hc))); fprintf('test Hess prod: cstep-rstep = %g\n',rc_err); function x = rstep_approxHess(dx,dy,f,x0) alpha = sqrt(eps); x2 = x0 + alpha*dx; [dummy,deriv2] = f(x2); x1 = x0 - alpha*dx; [dummy,deriv1] = f(x1); g2 = deriv2(dy); g1 = deriv1(dy); x = (g2-g1)/(2*alpha); function p = cstep_approxHess(dx,dy,f,x0) x = x0 + 1e-20i*dx; [dummy,deriv] = f(x); g = deriv(dy); p = 1e20*imag(g);
github
bsxfan/meta-embeddings-master
inv_lu2.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/utils/inv_lu2.m
1,044
utf_8
8fa16d13c5b1ad8e681b3f2ba0f9b2c9
function [inv_map,bi_inv_map,logdet,invA] = inv_lu2(A) % INV_LU2 % Does a LU decomposition on A and returns logdet, inverse and % two function handles that respectively map X to A\X and A\X/A. % if nargin==0 test_this(); return; end [L,T,p] = lu(A,'vector'); P = sparse(p,1:length(p),1); % P*A = L*U % L is lower triangular, with unit diagonal and unit determinant % T is upper triangular, det(T) = prod(diag(T), may have negative values on diagonal % P is a permuation matrix: P' = inv(P) and det(P) is +1 or -1 % inv_map = @(X) T\(L\(P*X)); % inv(A)*X*inv(A) bi_inv_map = @(X) ((inv_map(X)/T)/L)*P; if nargout>2 logdet = sum(log(diag(T)))-log(det(P)); if nargout>3 invA = T\(L\P); end end function test_this() dim = 3; A = randn(dim)+sqrt(-1)*randn(dim); [inv_map,bi_inv_map,logdet,iA] = inv_lu2(A); [logdet,log(det(A))] X = randn(dim,3); Y1 = A\X, Y2 = inv_map(X) Z1 = (A\X)/A Z2 = bi_inv_map(X) iA, inv(A)
github
bsxfan/meta-embeddings-master
invchol2.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/utils/invchol2.m
968
utf_8
936256e3c3a28ed65ad0c15d9fbb04cd
function [inv_map,bi_inv_map,logdet,invA] = invchol2(A) % INVCHOL2 % Does a Cholesky decomposition on A and returns logdet, inverse and % two function handles that respectively map X to A\X and A\X/A. % if nargin==0 test_this(); return; end if isreal(A) R = chol(A); %R'*R = A inv_map = @(X) R\(R'\X); % inv(A)*X*inv(A) bi_inv_map = @(X) (inv_map(X)/R)/(R'); if nargout>2 logdet = 2*sum(log(diag(R))); if nargout>3 invA = inv_map(eye(size(A))); end end else inv_map = @(X) A\X; % inv(A)*X*inv(A) bi_inv_map = @(X) (A\X)/A; if nargout>2 logdet = log(det(A)); if nargout>3 invA = inv_map(eye(size(A))); end end end function test_this() dim = 3; r = randn(dim,2*dim); A = r*r'; [inv_map,bi_inv_map,logdet,iA] = invchol2(A); [logdet,log(det(A))] X = randn(dim,3); Y1 = A\X, Y2 = inv_map(X) Z1 = (A\X)/A Z2 = bi_inv_map(X) iA, inv(A)
github
bsxfan/meta-embeddings-master
invchol_or_lu.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/utils/invchol_or_lu.m
1,418
utf_8
468d08dd52dd54bb77a471a5e2d0a856
function [inv_map,bi_inv_map,logdet,invA] = invchol_or_lu(A) % INVCHOL_OR_LU % Does a Cholesky decomposition on A and returns logdet, inverse and % two function handles that respectively map X to A\X and A\X/A. % if nargin==0 test_this(); return; end if isreal(A) R = chol(A); %R'*R = A inv_map = @(X) R\(R'\X); % inv(A)*X*inv(A) bi_inv_map = @(X) (inv_map(X)/R)/(R'); if nargout>2 logdet = 2*sum(log(diag(R))); if nargout>3 invA = inv_map(eye(size(A))); end end else [L,T,p] = lu(A,'vector'); P = sparse(p,1:length(p),1); % P*A = L*U % L is lower triangular, with unit diagonal and unit determinant % T is upper triangular, det(T) = prod(diag(T), may have negative values on diagonal % P is a permuation matrix: P' = inv(P) and det(P) is +1 or -1 % inv_map = @(X) T\(L\(P*X)); % inv(A)*X*inv(A) bi_inv_map = @(X) ((inv_map(X)/T)/L)*P; if nargout>2 logdet = sum(log(diag(T)))-log(det(P)); if nargout>3 invA = T\(L\P); end end end function test_this() dim = 3; A = randn(dim)+sqrt(-1)*randn(dim); [inv_map,bi_inv_map,logdet,iA] = invchol_or_lu(A); [logdet,log(det(A))] X = randn(dim,3); Y1 = A\X, Y2 = inv_map(X) Z1 = (A\X)/A Z2 = bi_inv_map(X) iA, inv(A)
github
bsxfan/meta-embeddings-master
invchol_taylor.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/utils/invchol_taylor.m
1,241
utf_8
0f52f57c84dc1ae326e32c031541c496
function [inv_map,logdet] = invchol_taylor(A) % Does a Cholesky decomposition on A and returns: % inv_map: a function handle to solve for X in AX = B % logdet (of A) % % This code is designed to work correctly if A has a small complex % perturbation, such as used in complex step differentiation, even though % the complex A is not positive definite. if nargin==0 test_this(); return; end if isreal(A) R = chol(A); %R'*R = A inv_map = @(X) R\(R'\X); if nargout>1 logdet = 2*sum(log(diag(R))); end if nargout>2 invA = inv_map(eye(size(A))); end else R = chol(real(A)); rmap = @(X) R\(R'\X); P = rmap(imag(A)); inv_map = @(X) inv_map_complex(X,rmap,P); if nargout>1 logdet = 2*sum(log(diag(R))) + i*trace(P); end end end function Y = inv_map_complex(X,rmap,P) Z = rmap(X); Y = Z - i*P*Z; end function test_this() dim = 20; R = randn(dim,dim+1); C = R*R'; C = C + 1.0e-20i*randn(dim); [map,logdet] = invchol_taylor(C); x = randn(dim,1); maps = imag([map(x),C\x]), logdets = imag([logdet,log(det(C))]) maps = real([map(x),C\x]), logdets = real([logdet,log(det(C))]) end
github
bsxfan/meta-embeddings-master
train_system.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/discrim_training/train_system.m
4,969
utf_8
69b1726b853595599d4a79414b256c8b
function [w,mce,divergence,w_pen,c_pen,optimizerState,converged] = train_system(classf,system,penalizer,W0,lambda,confusion,maxiters,maxCG,prior,optimizerState) % % Supervised training of a regularized K-class linear logistic % regression. Allows regularization via weight penalties and via % label confusion probabilities. % % % Inputs: % classf: 1-by-N row of class labels, in the range 1..K % % system: MV2DF function handle that maps parameters to score matrix. % Note: The system input data is already wrapped in this handle. % % penalizer: MV2DF function handle that maps parameters to a positive regularization penalty. % % % W0: initial parameters. This is NOT optional. % % % confusion: a scalar or a matrix of label confusion probabilities % -- if this is a K-by-K matrix, then % entry_ij denotes P(label_j | class i) % % -- if scalar: confusion = q, then % P(label_i | class_i) = 1-q, and % P(label_j | class_i) = q/(K-1) % % maxiters: the maximum number of Newton Trust Region optimization % iterations to perform. Note, the user can make maxiters % small, examine the solution and then continue training: % -- see W0 and optimizerState. % % % prior: a prior probability distribution over the K classes to % modify the optimization operating point. % optional: % omit or use [] % default is prior = ones(1,K)/K % % optimizerState: In this implementation, it is the trust region radius. % optional: % omit or use [] % If not supplied when resuming iteration, % this may cost some extra iterations. % Resume further iteration thus: % [W1,...,optimizerState] = train_..._logregr(...); % ... examine solution W1 ... % [W2,...,optimizerState] = train_..._logregr(...,W1,...,optimizerState); % % % % % % Outputs: % W: the solution. % mce: normalized multiclass cross-entropy of the solution. % The range is 0 (good) to 1(useless). % % optimizerState: see above, can be used to resume iteration. % if nargin==0 test_this(); return; end classf = classf(:)'; K = max(classf); N = length(classf); if ~exist('maxCG','var') || isempty(maxCG) maxCG = 100; end if ~exist('optimizerState','var') optimizerState=[]; end if ~exist('prior','var') || isempty(prior) prior = ones(K,1)/K; else prior = prior(:); end weights = zeros(1,N); for k = 1:K fk = find(classf==k); count = length(fk); weights(fk) = prior(k)/(count*log(2)); end if ~exist('confusion','var') || isempty(confusion) confusion = 0; end if isscalar(confusion) q = confusion; confusion = (1-q)*eye(K) + (q/(K-1))*(ones(K)-eye(K)); end post = bsxfun(@times,confusion,prior(:)); post = bsxfun(@times,post,1./sum(post,1)); logpost = post; nz = logpost>0; logpost(nz) = log(post(nz)); confusion_entropy = -mean(sum(post.*logpost,1),2); prior_entropy = -log(prior)'*prior; c_pen = confusion_entropy/prior_entropy; fprintf('normalized confusion entropy = %g\n',c_pen); T = zeros(K,N); for i=1:N T(:,i) = post(:,classf(i)); end w=[]; obj1 = mce_obj(system,T,weights,log(prior)); obj2 = penalizer(w); obj = sum_of_functions(w,[1,lambda],obj1,obj2); w0 = W0(:); [w,y,optimizerState,converged] = trustregion_newton_cg(obj,w0,maxiters,maxCG,optimizerState,[],1); w_pen = lambda*obj2(w)/prior_entropy; mce = y/prior_entropy-w_pen; divergence = mce-c_pen; fprintf('mce = %g, divergence = %g, conf entr = %g, weight pen = %g\n',mce,divergence,c_pen,w_pen); function y = score_map(W,X) [dim,N] = size(X); W = reshape(W,[],dim+1); offs = W(:,end); W(:,end)=[]; y = bsxfun(@plus,W*X,offs); y = y(:); function W = score_transmap(y,X) [dim,N] = size(X); y = reshape(y,[],N).'; W = [X*y;sum(y)]; W = W.'; W = W(:); function test_this() K = 3; N = 100; dim = 2; % ----------------syntesize data ------------------- randn('state',0); means = randn(dim,K)*10; %signal X = randn(dim,K*N); % noise classf = zeros(1,K*N); ii = 1:N; for k=1:K X(:,ii) = bsxfun(@plus,means(:,k),X(:,ii)); classf(ii) = k; ii = ii+N; end N = K*N; % ---------------- define system ------------------- w=[]; map = @(W) score_map(W,X); transmap = @(Y) score_transmap(Y,X); system = linTrans(w,map,transmap); penalizer = sumsquares_penalty(w,1); % ------------- train it ------------------------------ confusion = 0.01; lambda = 0.01; W0 = zeros(K,dim+1); W = train_system(classf,system,penalizer,W0,lambda,confusion,20); % ------------ plot log posterior on training data -------------------- scores = score_system(W,system,K); scores = logsoftmax(scores); subplot(1,2,1);plot(scores'); scores = score_system(W,system,K,true); scores = [scores;zeros(1,N)]; scores = logsoftmax(scores); subplot(1,2,2);plot(scores');
github
bsxfan/meta-embeddings-master
sum_of_functions.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/sum_of_functions.m
1,094
utf_8
af1885792c3ce587c098ffc61a10cc06
function [y,deriv] = sum_of_functions(w,weights,f,g) % This is an MV2DF (see MV2DF_API_DEFINITION.readme) which % represents the new function, s(w), obtained by summing the % weighted outputs of the given functions: % s(w) = sum_i weights(i)*functions{i}(w) % % Usage examples: % % s = @(w) sum_of_functions(w,[1,-1],f,g) % % Here f,g are function handles to MV2DF's. if nargin==0 test_this(); return; end weights = weights(:); if isempty(w) s = stack(w,f,g,true); n = length(weights); map = @(s) reshape(s,[],n)*weights; transmap = @(y) reshape(y(:)*weights.',[],1); y = linTrans(s,map,transmap); return; end if isa(w,'function_handle') f = sum_of_functions([],weights,f,g); y = compose_mv(f,w,[]); return; end f = sum_of_functions([],weights,f,g); if nargout==1 y = f(w); else [y,deriv] = f(w); end function test_this() A = randn(4,4); B = randn(4,4); w = []; f = gemm(w,4,4,4); g = transpose_mv2df(f,4,4); %f = A*B; %g = B'*A'; s = sum_of_functions(w,[-1,1],f,g); %s = stack(w,f,g); test_MV2DF(s,[A(:);B(:)]);
github
bsxfan/meta-embeddings-master
scale_function.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/scale_function.m
856
utf_8
fae26a24cbea0fcc7ae35cf1642b18e4
function [y,deriv] = scale_function(w,scale,f) % This is an MV2DF (see MV2DF_API_DEFINITION.readme) which % represents the new function, % % g(w) = scale(w)*f(w), % % where scale is scalar-valued and f is matrix-valued. % % % Here scale and f are function handles to MV2DF's. if nargin==0 test_this(); return; end if isempty(w) s = stack(w,f,scale); y = mm_special(s,@(w)reshape(w(1:end-1),[],1),@(w)w(end)); return; end if isa(w,'function_handle') f = scale_function([],scale,f); y = compose_mv(f,w,[]); return; end f = scale_function([],scale,f); if nargout==1 y = f(w); else [y,deriv] = f(w); end function test_this() m = 5; n = 10; data = randn(m,n); scal = 3; w = [data(:);scal]; g = subvec([],m*n+1,1,m*n); scal = subvec([],m*n+1,m*n+1,1); f = scale_function([],scal,g); test_MV2DF(f,w);
github
bsxfan/meta-embeddings-master
outerprod_of_functions.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/outerprod_of_functions.m
1,085
utf_8
731782f761b675bb6d3567ddb560c950
function [y,deriv] = outerprod_of_functions(w,f,g,m,n) % This is an MV2DF (see MV2DF_API_DEFINITION.readme) which % represents the new function, % % g(w) = f(w)g(w)' % % where f(w) and g(w) are column vectors of sizes m and n respectively. % % Here f,g are function handles to MV2DF's. if nargin==0 test_this(); return; end if ~exist('n','var'), n=[]; end function A = extractA(w) if isempty(m), m = length(w)-n; end A = w(1:m); A = A(:); end function B = extractB(w) if isempty(m), m = length(w)-n; end B = w(1+m:end); B = B(:).'; end if isempty(w) s = stack(w,f,g); y = mm_special(s,@(w)extractA(w),@(w)extractB(w)); return; end if isa(w,'function_handle') f = outerprod_of_functions([],f,g,m,n); y = compose_mv(f,w,[]); return; end f = outerprod_of_functions([],f,g,m,n); if nargout==1 y = f(w); else [y,deriv] = f(w); end end function test_this() m = 5; n = 3; w = randn(m+n,1); f = subvec([],m+n,1,m); g = subvec([],m+n,m+1,n); h = outerprod_of_functions([],f,g,m,n); test_MV2DF(h,w); end
github
bsxfan/meta-embeddings-master
interleave.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/interleave.m
2,028
utf_8
0cdd5849311559d9813888914f7530cd
function [y,deriv] = interleave(w,functions) % interleave is an MV2DF (see MV2DF_API_DEFINITION.readme) which % represents the new function, s(w), obtained by interleaving the outputs of % f() and g() thus: % % S(w) = [f(w)';g(w)']; % s(w) = S(:); if nargin==0 test_this(); return; end if isempty(w) y = @(w)interleave(w,functions); return; end if isa(w,'function_handle') outer = interleave([],functions); y = compose_mv(outer,w,[]); return; end % if ~isa(f,'function_handle') % f = const_mv2df([],f); % end % if ~isa(g,'function_handle') % g = const_mv2df([],g); % end w = w(:); m = length(functions); k = length(w); if nargout==1 y1 = functions{1}(w); n = length(y1); y = zeros(m,n); y(1,:) = y1; for i=2:m y(i,:) = functions{i}(w); end y = y(:); return; end deriv = cell(1,m); [y1,deriv{1}] = functions{1}(w); n = length(y1); y = zeros(m,n); y(1,:) = y1; for i=2:m [y(i,:),deriv{i}] = functions{i}(w); end y = y(:); deriv = @(g2) deriv_this(g2,deriv,m,n,k); function [g,hess,linear] = deriv_this(y,deriv,m,n,k) y = reshape(y,m,n); if nargout==1 g = deriv{1}(y(1,:).'); for i=2:m g = g+ deriv{i}(y(i,:).'); end return; end hess = cell(1,m); lin = false(1,m); [g,hess{1},lin(1)] = deriv{1}(y(1,:).'); linear = lin(1); for i=2:m [gi,hess{i},lin(i)] = deriv{i}(y(i,:).'); g = g + gi; linear = linear && lin(i); end hess = @(d) hess_this(d,hess,lin,m,n,k); function [h,Jv] = hess_this(d,hess,lin,m,n,k) if all(lin) h = []; else h = zeros(k,1); end if nargout>1 Jv = zeros(m,n); for i=1:m [hi,Jv(i,:)] = hess{i}(d); if ~lin(i) h = h + hi; end end Jv = Jv(:); else for i=1:m hi = hess{i}(d); if ~lin(i) h = h + hi; end end end function test_this() w = []; f = exp_mv2df(w); g = square_mv2df(w); h = identity_trans(w); s = interleave(w,{f,g,h}); w = randn(5,1); test_MV2DF(s,w);
github
bsxfan/meta-embeddings-master
shift_function.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/shift_function.m
896
utf_8
82abefaa89d6e02403f0b543a3c69a0b
function [y,deriv] = shift_function(w,shift,f) % This is an MV2DF (see MV2DF_API_DEFINITION.readme) which % represents the new function, % % g(w) = shift(w)+f(w), % % where shift is scalar-valued and f is matrix-valued. % % % Here shift and f are function handles to MV2DF's. if nargin==0 test_this(); return; end if isempty(w) s = stack(w,shift,f); map = @(s) s(2:end)+s(1); transmap = @(y) [sum(y);y]; y = linTrans(s,map,transmap); return; end if isa(w,'function_handle') f = shift_function([],shift,f); y = compose_mv(f,w,[]); return; end f = shift_function([],shift,f); if nargout==1 y = f(w); else [y,deriv] = f(w); end function test_this() m = 5; n = 10; data = randn(m,n); shift = 3; w = [data(:);shift]; g = subvec([],m*n+1,1,m*n); shift = subvec([],m*n+1,m*n+1,1); f = shift_function([],shift,g); test_MV2DF(f,w);
github
bsxfan/meta-embeddings-master
dotprod_of_functions.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/dotprod_of_functions.m
952
utf_8
2999899143500736ecbc06d5afc09df0
function [y,deriv] = dotprod_of_functions(w,f,g) % This is an MV2DF (see MV2DF_API_DEFINITION.readme) which % represents the new function, % % g(w) = f(w)'g(w) % % where f(w) and g(w) are column vectors of the same size. % % Here f,g are function handles to MV2DF's. if nargin==0 test_this(); return; end function A = extractA(w) A = w(1:length(w)/2); A = A(:).'; end function B = extractB(w) B = w(1+length(w)/2:end); B = B(:) ; end if isempty(w) s = stack(w,f,g); y = mm_special(s,@(w)extractA(w),@(w)extractB(w)); return; end if isa(w,'function_handle') f = dotprod_of_functions([],f,g); y = compose_mv(f,w,[]); return; end f = dotprod_of_functions([],f,g); if nargout==1 y = f(w); else [y,deriv] = f(w); end end function test_this() m = 5; w = randn(2*m,1); f = subvec([],2*m,1,m); g = subvec([],2*m,m+1,m); h = dotprod_of_functions([],f,g); test_MV2DF(h,w); end
github
bsxfan/meta-embeddings-master
dottimes_of_functions.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/dottimes_of_functions.m
641
utf_8
45195e5dddb789f3431e2f84495b06c7
function [y,deriv] = dottimes_of_functions(w,A,B) % This is an MV2DF (see MV2DF_API_DEFINITION.readme) % % w --> A(w) .* B(w) % % Here A and B are function handles to MV2DF's. if nargin==0 test_this(); return; end if isempty(w) s = stack(w,A,B); y = dottimes(s); return; end if isa(w,'function_handle') f = dottimes_of_functions([],A,B); y = compose_mv(f,w,[]); return; end f = dottimes_of_functions([],A,B); [y,deriv] = f(w); function test_this() M = 4; X = []; Xt = transpose_mv2df(X,M,M); A = UtU(X,M,M); B = UtU(Xt,M,M); f = dottimes_of_functions(X,A,B); test_MV2DF(f,randn(16,1));
github
bsxfan/meta-embeddings-master
replace_hessian.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/replace_hessian.m
1,399
utf_8
1e948d50795df5102876278fd5022da8
function [y,deriv] = replace_hessian(w,f,cstep) % This is an MV2DF. See MV2DF_API_DEFINITION.readme. % if nargin==0 test_this(); return; end if isempty(w) y = @(w)replace_hessian(w,f,cstep); return; end if isa(w,'function_handle') outer = replace_hessian([],f,cstep); y = compose_mv(outer,w,[]); return; end if nargout==1 y = f(w); else [y,derivf] = f(w); deriv = @(dy) deriv_this(dy,derivf,f,w,cstep); end end function [g,hess,linear] = deriv_this(dy,derivf,f,w,cstep) g = derivf(dy); if nargout>1 linear = false; hess = @(dx) hess_this(dx,dy,f,w,cstep); end end function [h,Jv] = hess_this(dx,dy,f,w,cstep) if cstep h = cstep_approxHess(dx,dy,f,w); else h = rstep_approxHess(dx,dy,f,w); end if nargout>1 error('replace_hessian cannot compute Jv'); %Jv = zeros(size(dy)); end end function x = rstep_approxHess(dx,dy,f,x0) alpha = sqrt(eps); x2 = x0 + alpha*dx; [dummy,deriv2] = f(x2); x1 = x0 - alpha*dx; [dummy,deriv1] = f(x1); g2 = deriv2(dy); g1 = deriv1(dy); x = (g2-g1)/(2*alpha); end function p = cstep_approxHess(dx,dy,f,x0) x = x0 + 1e-20i*dx; [dummy,deriv] = f(x); g = deriv(dy); p = 1e20*imag(g); end function test_this() A = randn(5); B = randn(5,1); map = @(w) 5*w; h = linTrans([],map,map); f = solve_AXeqB([],5); g = replace_hessian([],f,true); g = g(h); w = [A(:);B(:)]; test_MV2DF(g,w); end
github
bsxfan/meta-embeddings-master
product_of_functions.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/product_of_functions.m
745
utf_8
ae86bc0a8429bacd6044704a6a8a0e06
function [y,deriv] = product_of_functions(w,A,B,m,k,n) % This is an MV2DF (see MV2DF_API_DEFINITION.readme) % % w --> vec ( reshape(A(w),m,k) * reshape(B(w),k,n) ) % % Here A and B are function handles to MV2DF's. if nargin==0 test_this(); return; end if isempty(w) s = stack(w,A,B); y = gemm(s,m,k,n); return; end if isa(w,'function_handle') f = product_of_functions([],A,B,m,k,n); y = compose_mv(f,w,[]); return; end f = product_of_functions([],A,B,m,k,n); [y,deriv] = f(w); function test_this() M = 4; N = 4; X = []; Xt = transpose_mv2df(X,M,N); A = UtU(X,M,N); B = UtU(Xt,N,M); %A = A(randn(16,1)); %B = B(randn(16,1)); f = product_of_functions(X,A,B,4,4,4); test_MV2DF(f,randn(16,1));
github
bsxfan/meta-embeddings-master
stack.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/stack.m
3,136
utf_8
cbfe5ccd3255b5021692c3eb13e1798f
function [y,deriv] = stack(w,f,g,eqlen) % STACK is an MV2DF (see MV2DF_API_DEFINITION.readme) which % represents the new function, s(w), obtained by stacking the outputs of % f() and g() thus: % s(w) = [f(w);g(w)] if nargin==0 test_this(); return; end if ~exist('eqlen','var') eqlen = false; end if isempty(w) y = @(w)stack(w,f,g,eqlen); return; end if isa(w,'function_handle') outer = stack([],f,g,eqlen); y = compose_mv(outer,w,[]); return; end % if ~isa(f,'function_handle') % f = const_mv2df([],f); % end % if ~isa(g,'function_handle') % g = const_mv2df([],g); % end w = w(:); if nargout==1 y1 = f(w); y2 = g(w); n1 = length(y1); n2 = length(y2); if eqlen, assert(n1==n2,'length(f(w))=%i must equal length(g(w))=%i.',n1,n2); end y = [y1;y2]; return; end [y1,deriv1] = f(w); [y2,deriv2] = g(w); y = [y1;y2]; n1 = length(y1); n2 = length(y2); if eqlen, assert(n1==n2,'length(f(w))=%i must equal length(g(w))=%i.',n1,n2); end deriv = @(g2) deriv_this(g2,deriv1,deriv2,n1); function [g,hess,linear] = deriv_this(y,deriv1,deriv2,n1) if nargout==1 g1 = deriv1(y(1:n1)); g2 = deriv2(y(n1+1:end)); g = g1 + g2; return; end [g1,hess1,lin1] = deriv1(y(1:n1)); [g2,hess2,lin2] = deriv2(y(n1+1:end)); g = g1+g2; linear = lin1 && lin2; hess = @(d) hess_this(d,hess1,hess2,lin1,lin2); function [h,Jv] = hess_this(d,hess1,hess2,lin1,lin2) if nargout>1 [h1,Jv1] = hess1(d); [h2,Jv2] = hess2(d); Jv = [Jv1;Jv2]; else [h1] = hess1(d); [h2] = hess2(d); end if lin1 && lin2 h = []; elseif ~lin1 && ~lin2 h = h1 + h2; elseif lin2 h = h1; else h = h2; end function test_this() fprintf('-------------- Test 1 ------------------------\n'); fprintf('Stack [f(w);g(w)]: f() is non-linear and g() is non-linear:\n'); A = randn(4,5); B = randn(5,4); w = []; f = gemm(w,4,5,4); g = gemm(subvec(w,40,1,20),2,5,2); s = stack(w,f,g); w = [A(:);B(:)]; test_MV2DF(s,w); fprintf('--------------------------------------\n\n'); fprintf('-------------- Test 2 ------------------------\n'); fprintf('Stack [f(w);g(w)]: f() is linear and g() is non-linear:\n'); A = randn(4,5); B = randn(5,4); w = [A(:);B(:)]; T = randn(40); f = @(w) linTrans(w,@(x)T*x,@(y)T.'*y); g = @(w) gemm(w,4,5,4); s = @(w) stack(w,f,g); test_MV2DF(s,w); fprintf('--------------------------------------\n\n'); fprintf('-------------- Test 3 ------------------------\n'); fprintf('Stack [f(w);g(w)]: f() is non-linear and g() is linear:\n'); A = randn(4,5); B = randn(5,4); w = [A(:);B(:)]; T = randn(40); f = @(w) linTrans(w,@(x)T*x,@(y)T.'*y); g = @(w) gemm(w,4,5,4); s = @(w) stack(w,g,f); test_MV2DF(s,w); fprintf('--------------------------------------\n\n'); fprintf('-------------- Test 4 ------------------------\n'); fprintf('Stack [f(w);g(w)]: f() is linear and g() is linear:\n'); w = randn(10,1); T1 = randn(11,10); f = @(w) linTrans(w,@(x)T1*x,@(y)T1.'*y); T2 = randn(12,10); g = @(w) linTrans(w,@(x)T2*x,@(y)T2.'*y); s = @(w) stack(w,g,f); test_MV2DF(s,w); fprintf('--------------------------------------\n\n');
github
bsxfan/meta-embeddings-master
scale_and_translate.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/scale_and_translate.m
1,341
utf_8
121b1cd2e23a3d7111f310db8e3b6a05
function [y,deriv] = scale_and_translate(w,vectors,params,m,n) % This is an MV2DF (see MV2DF_API_DEFINITION.readme) which % represents the new function, obtained by scaling and translating the % column vectors of the output matrix of the function vectors(w). The % scaling and translation parameters, params(w) is also a function of w. % % The output, y is calulated as follows: % % V = reshape(vectors(w),m,n); % [scal;offs] = params(w); where scal is scalar and offs is m-by-1 % y = bsxfun(@plus,scal*V,offs); % y = y(:); % % Usage examples: % % s = @(w) sum_of_functions(w,[1,-1],f,g) % % Here f,g are function handles to MV2DF's. if nargin==0 test_this(); return; end if isempty(w) s = stack(w,vectors,params); y = calibrateScores(s,m,n); return; end if isa(w,'function_handle') f = scale_and_translate([],vectors,params,m,n); y = compose_mv(f,w,[]); return; end f = scale_and_translate([],vectors,params,m,n); if nargout==1 y = f(w); else [y,deriv] = f(w); end function test_this() m = 5; n = 10; data = randn(m,n); offs = randn(m,1); scal = 3; w = [data(:);scal;offs]; vectors = subvec([],m*n+m+1,1,m*n); %vectors = randn(size(data)); params = subvec([],m*n+m+1,m*n+1,m+1); %params = [scal;offs]; f = scale_and_translate([],vectors,params,m,n); test_MV2DF(f,w);
github
bsxfan/meta-embeddings-master
compose_mv.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/utility_funcs/Optimization_Toolkit/MV2DF/function_combination/compose_mv.m
2,958
utf_8
108f7eb78b4ff77e907d369fc9ae14db
function [y,deriv] = compose_mv(outer,inner,x) % COMPOSE_MV is an MV2DF (see MV2DF_API_DEFINITION.readme) which represents % the combination of two functions. If 'outer' is an MV2DF for a function % g() and 'inner' for a function f(), then this MV2DF represents g(f(x)). %feature scopedaccelenablement off if nargin==0 test_this(); return; end if isempty(x) y = @(w)compose_mv(outer,inner,w); return; end if isa(x,'function_handle') fh = compose_mv(outer,inner,[]); % fh =@(x) outer(inner(x)) y = compose_mv(fh,x,[]); % y =@(w) outer(inner(x(w))) return; end % if ~isa(outer,'function_handle') % outer = const_mv2df([],outer); % end % if ~isa(inner,'function_handle') % inner = const_mv2df([],inner); % end if nargout==1 y = outer(inner(x)); return; end [y1,deriv1] = inner(x); [y,deriv2] = outer(y1); deriv = @(g3) deriv_this(deriv1,deriv2,g3); function [g,hess,linear] = deriv_this(deriv1,deriv2,g3) if nargout==1 g = deriv1(deriv2(g3)); return; end [g2,hess2,lin2] = deriv2(g3); [g,hess1,lin1] = deriv1(g2); hess =@(d) hess_this(deriv1,hess1,hess2,lin1,lin2,d); linear = lin1 && lin2; function [h,Jv] = hess_this(deriv1,hess1,hess2,lin1,lin2,d) if nargout==1 if ~lin2 [h1,Jv1] = hess1(d); h2 = hess2(Jv1); h2 = deriv1(h2); elseif ~lin1 h1 = hess1(d); end else [h1,Jv1] = hess1(d); [h2,Jv] = hess2(Jv1); if ~lin2 h2 = deriv1(h2); end end if lin1 && lin2 h=[]; elseif (~lin1) && (~lin2) h = h1+h2; elseif lin1 h = h2; else % if lin2 h = h1; end function test_this() fprintf('-------------- Test 1 ------------------------\n'); fprintf('Composition g(f(w)): f() is non-linear and g() is non-linear:\n'); A = randn(4,5); B = randn(5,4); w = [A(:);B(:)]; f = @(w) gemm(w,4,5,4); g1 = gemm(f,2,4,2); test_MV2DF(g1,w); fprintf('--------------------------------------\n\n'); fprintf('-------------- Test 2 ------------------------\n'); fprintf('Composition g(f(w)): f() is linear and g() is non-linear:\n'); A = randn(4,5); B = randn(5,4); w = [A(:);B(:)]; T = randn(40); f = @(w) linTrans(w,@(x)T*x,@(y)T.'*y); g2 = gemm(f,4,5,4); test_MV2DF(g2,w); fprintf('--------------------------------------\n\n'); fprintf('-------------- Test 3 ------------------------\n'); fprintf('Composition g(f(w)): f() is non-linear and g() is linear:\n'); A = randn(4,5); B = randn(5,4); w = [A(:);B(:)]; f = @(w) gemm(w,4,5,4); T = randn(16); g3 = linTrans(f,@(x)T*x,@(y)T.'*y); test_MV2DF(g3,w); fprintf('--------------------------------------\n\n'); fprintf('-------------- Test 4 ------------------------\n'); fprintf('Composition g(f(w)): f() is linear and g() is linear:\n'); w = randn(10,1); T1 = randn(11,10); f = @(w) linTrans(w,@(x)T1*x,@(y)T1.'*y); T2 = randn(5,11); g4 = linTrans(f,@(x)T2*x,@(y)T2.'*y); test_MV2DF(g4,w); fprintf('--------------------------------------\n\n');
github
bsxfan/meta-embeddings-master
pav_calibration.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/calibration/pav_calibration.m
2,716
utf_8
2a9298835be5d7757fb4d660a5a2d7b3
function [pav_trans,score_bounds,llr_bounds] = pav_calibration(tar,non,small_val) % Creates a calibration transformation function using the PAV algorithm. % Inputs: % tar: A vector of target scores. % non: A vector of non-target scores. % small_val: An offset to make the transformation function % invertible. small_val is subtracted from the left-hand side % of the bin and added to the right-hand side (and the bin % height is linear between its left and right ends). % Outputs: % pav_trans: The transformation function. It takes in scores and % outputs (calibrated) log-likelihood ratios. % score_bounds: The left and right ends of the line segments % that make up the transformation. % llr_bounds: The lower and upper ends of the line segments that % make up the transformation. if nargin==0 test_this() return else assert(nargin==3) assert(size(tar,1)==1) assert(size(non,1)==1) assert(length(tar)>0) assert(length(non)>0) end largeval = 1e6; scores = [-largeval tar non largeval]; Pideal = [ones(1,length(tar)+1),zeros(1,length(non)+1)]; [scores,perturb] = sort(scores); Pideal = Pideal(perturb); [Popt,width,height] = pavx(Pideal); data_prior = (length(tar)+1)/length(Pideal); llr = logit(Popt) - logit(data_prior); bnd_ndx = make_bnd_ndx(width); score_bounds = scores(bnd_ndx); llr_bounds = llr(bnd_ndx); llr_bounds(1:2:end) = llr_bounds(1:2:end) - small_val; llr_bounds(2:2:end) = llr_bounds(2:2:end) + small_val; pav_trans = @(s) pav_transform(s,score_bounds,llr_bounds); end function scr_out = pav_transform(scr_in,score_bounds,llr_bounds) scr_out = zeros(1,length(scr_in)); for ii=1:length(scr_in) x = scr_in(ii); [x1,x2,v1,v2] = get_line_segment_vals(x,score_bounds,llr_bounds); scr_out(ii) = (v2 - v1) * (x - x1) / (x2 - x1) + v1; end end function bnd_ndx = make_bnd_ndx(width) len = length(width)*2; c = cumsum(width); bnd_ndx = zeros(1,len); bnd_ndx(1:2:len) = [1 c(1:end-1)+1]; bnd_ndx(2:2:len) = c; end function [x1,x2,v1,v2] = get_line_segment_vals(x,score_bounds,llr_bounds) p = find(x>=score_bounds,1,'last'); x1 = score_bounds(p); x2 = score_bounds(p+1); v1 = llr_bounds(p); v2 = llr_bounds(p+1); end function test_this() ntar = 10; nnon = 12; tar = 2*randn(1,ntar)+2; non = 2*randn(1,nnon)-2; tarnon = [tar non]; scores = [-inf tarnon inf]; Pideal = [ones(1,length(tar)+1),zeros(1,length(non)+1)]; [scores,perturb] = sort(scores); Pideal = Pideal(perturb); [Popt,width,height] = pavx(Pideal); data_prior = (length(tar)+1)/length(Pideal); llr = logit(Popt) - logit(data_prior); [dummy,pinv] = sort(perturb); tmp = llr(pinv); llr = tmp(2:end-1) pav_trans = pav_calibration(tar,non,0); pav_trans(tarnon) end
github
bsxfan/meta-embeddings-master
align_with_ndx.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/classes/@Scores/align_with_ndx.m
2,628
utf_8
5899b5e5bd43dea8280d84cea8fdf0ec
function aligned_scr = align_with_ndx(scr,ndx) % The ordering in the output Scores object corresponds to ndx, so % aligning several Scores objects with the same ndx will result in % them being comparable with each other. % Inputs: % scr: a Scores object % ndx: a Key or Ndx object % Outputs: % aligned_scr: scr resized to size of 'ndx' and reordered % according to the ordering of modelset and segset in 'ndx'. if nargin==1 test_this(); return end assert(nargin==2) assert(isa(scr,'Scores')) assert(isa(ndx,'Key')||isa(ndx,'Ndx')) assert(scr.validate()) assert(ndx.validate()) aligned_scr = Scores(); aligned_scr.modelset = ndx.modelset; aligned_scr.segset = ndx.segset; m = length(ndx.modelset); n = length(ndx.segset); [hasmodel,rindx] = ismember(ndx.modelset,scr.modelset); rindx = rindx(hasmodel); [hasseg,cindx] = ismember(ndx.segset,scr.segset); cindx = cindx(hasseg); aligned_scr.scoremat = zeros(m,n); aligned_scr.scoremat(hasmodel,hasseg) = double(scr.scoremat(rindx,cindx)); aligned_scr.scoremask = false(m,n); aligned_scr.scoremask(hasmodel,hasseg) = scr.scoremask(rindx,cindx); assert(sum(aligned_scr.scoremask(:)) <= sum(hasmodel)*sum(hasseg)); if isa(ndx,'Ndx') aligned_scr.scoremask = aligned_scr.scoremask & ndx.trialmask; else aligned_scr.scoremask = aligned_scr.scoremask & (ndx.tar | ndx.non); end if sum(hasmodel)<m log_warning('models reduced from %i to %i\n',m,sum(hasmodel)); end if sum(hasseg)<n log_warning('testsegs reduced from %i to %i\n',n,sum(hasseg)); end if isa(ndx,'Key') %supervised tar = ndx.tar & aligned_scr.scoremask; non = ndx.non & aligned_scr.scoremask; missing = sum(ndx.tar(:)) - sum(tar(:)); if missing > 0 log_warning('%i of %i targets missing.\n',missing,sum(ndx.tar(:))); end missing = sum(ndx.non(:)) - sum(non(:)); if missing > 0 log_warning('%i of %i non-targets missing.\n',missing,sum(ndx.non(:))); end else mask = ndx.trialmask & aligned_scr.scoremask; missing = sum(ndx.trialmask(:)) - sum(mask(:)); if missing > 0 log_warning('%i of %i trials missing\n',missing,sum(ndx.trialmask(:))); end end assert(all(isfinite(aligned_scr.scoremat(aligned_scr.scoremask(:))))) assert(aligned_scr.validate()) end function test_this() key = Key(); key.modelset = {'1','2','3'}; key.segset = {'a','b','c'}; key.tar = logical(eye(3)); key.non = ~key.tar; scr = Scores(); scr.scoremat = [1 2 3; 4 5 6; 7 8 9]; scr.scoremask = true(3); scr.modelset = {'3','2','1'}; scr.segset = {'c','b','a'}; scores = scr.scoremat, scr = scr.align_with_ndx(key); scores = scr.scoremat, end
github
bsxfan/meta-embeddings-master
filter.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/classes/@Scores/filter.m
2,622
utf_8
ebaa2297b42e23384ffa07c12bdcc005
function outscr = filter(inscr,modlist,seglist,keep) % Removes some of the information in a Scores object. Useful for % creating a gender specific score set from a pooled gender score % set. Depending on the value of 'keep', the two input lists % indicate the models and test segments (and their associated % scores) to retain or discard. % Inputs: % inscr: A Scores object. % modlist: A cell array of strings which will be compared with % the modelset of 'inscr'. % seglist: A cell array of strings which will be compared with % the segset of 'inscr'. % keep: A boolean indicating whether modlist and seglist are the % models to keep or discard. % Outputs: % outscr: A filtered version of 'inscr'. if nargin == 0 test_this(); return end assert(nargin==4) assert(isa(inscr,'Scores')) assert(iscell(modlist)) assert(iscell(seglist)) assert(inscr.validate()) if keep keepmods = modlist; keepsegs = seglist; else keepmods = setdiff(inscr.modelset,modlist); keepsegs = setdiff(inscr.segset,seglist); end keepmodidx = ismember(inscr.modelset,keepmods); keepsegidx = ismember(inscr.segset,keepsegs); outscr = Scores(); outscr.modelset = inscr.modelset(keepmodidx); outscr.segset = inscr.segset(keepsegidx); outscr.scoremat = inscr.scoremat(keepmodidx,keepsegidx); outscr.scoremask = inscr.scoremask(keepmodidx,keepsegidx); assert(outscr.validate()) if length(inscr.modelset) > length(outscr.modelset) log_info('Number of models reduced from %d to %d.\n',length(inscr.modelset),length(outscr.modelset)); end if length(inscr.segset) > length(outscr.segset) log_info('Number of test segments reduced from %d to %d.\n',length(inscr.segset),length(outscr.segset)); end end function test_this() scr = Scores(); scr.modelset = {'aaa','bbb','ccc','ddd'}; scr.segset = {'11','22','33','44','55'}; scr.scoremat = [1,2,3,4,5;6,7,8,9,10;11,12,13,14,15;16,17,18,19,20]; scr.scoremask = true(4,5); fprintf('scr.modelset\n'); disp(scr.modelset) fprintf('scr.segset\n'); disp(scr.segset) fprintf('scr.scoremat\n'); disp(scr.scoremat) modlist = {'bbb','ddd'} seglist = {'11','55'} keep = true out = Scores.filter(scr,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.scoremat\n'); disp(out.scoremat) fprintf('out.scoremask\n'); disp(out.scoremask) keep = false out = Scores.filter(scr,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.scoremat\n'); disp(out.scoremat) fprintf('out.scoremask\n'); disp(out.scoremask) end
github
bsxfan/meta-embeddings-master
filter.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/classes/@Key/filter.m
3,047
utf_8
9274e13ab0bf80ca9a90fd6f46da8ff0
function outkey = filter(inkey,modlist,seglist,keep) % Removes some of the information in a key. Useful for creating a % gender specific key from a pooled gender key. Depending on the % value of 'keep', the two input lists indicate the strings to % retain or the strings to discard. % Inputs: % inkey: A Key object. % modlist: A cell array of strings which will be compared with % the modelset of 'inkey'. % seglist: A cell array of strings which will be compared with % the segset of 'inkey'. % keep: A boolean indicating whether modlist and seglist are the % models to keep or discard. % Outputs: % outkey: A filtered version of 'inkey'. if nargin == 0 test_this(); return else assert(nargin==4) end assert(isa(inkey,'Key')) assert(iscell(modlist)) assert(iscell(seglist)) assert(inkey.validate()) if keep keepmods = modlist; keepsegs = seglist; else keepmods = setdiff(inkey.modelset,modlist); keepsegs = setdiff(inkey.segset,seglist); end keepmodidx = ismember(inkey.modelset,keepmods); keepsegidx = ismember(inkey.segset,keepsegs); outkey = Key(); outkey.modelset = inkey.modelset(keepmodidx); outkey.segset = inkey.segset(keepsegidx); outkey.tar = inkey.tar(keepmodidx,keepsegidx); outkey.non = inkey.non(keepmodidx,keepsegidx); assert(outkey.validate()) if length(inkey.modelset) > length(outkey.modelset) log_info('Number of models reduced from %d to %d.\n',length(inkey.modelset),length(outkey.modelset)); end if length(inkey.segset) > length(outkey.segset) log_info('Number of test segments reduced from %d to %d.\n',length(inkey.segset),length(outkey.segset)); end end function test_this() key = Key(); key.modelset = {'aaa','bbb','ccc','ddd'}; key.segset = {'11','22','33','44','55'}; key.tar = logical([1,0,0,1,0;0,1,0,1,1;0,0,0,1,0;1,1,0,0,0]); key.non = logical([0,1,0,0,0;1,0,0,0,0;1,1,1,0,0;0,0,1,1,1]); fprintf('key.modelset\n'); disp(key.modelset) fprintf('key.segset\n'); disp(key.segset) fprintf('key.tar\n'); disp(key.tar) fprintf('key.non\n'); disp(key.non) modlist = {'bbb','ddd'} seglist = {'11','55'} keep = true out = Key.filter(key,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.tar\n'); disp(out.tar) fprintf('out.non\n'); disp(out.non) keep = false out = Key.filter(key,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.tar\n'); disp(out.tar) fprintf('out.non\n'); disp(out.non) modlist = {'bbb','ddd','eee'} seglist = {'11','66','77','55'} keep = true out = Key.filter(key,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.tar\n'); disp(out.tar) fprintf('out.non\n'); disp(out.non) keep = false out = Key.filter(key,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.tar\n'); disp(out.tar) fprintf('out.non\n'); disp(out.non) end
github
bsxfan/meta-embeddings-master
read_hdf5.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/classes/@Key/read_hdf5.m
1,196
utf_8
4057278a996259de22fed6ee29c5d3b2
function key = read_hdf5(infilename) % Reads a Key object from an hdf5 file. % Inputs: % infilename: The name for the hdf5 file to read. % Outputs: % key: A Key object created from the information in the hdf5 % file. assert(nargin==1) assert(isa(infilename,'char')) key = Key(); key.modelset = h5strings_to_cell(infilename,'/ID/row_ids'); key.segset = h5strings_to_cell(infilename,'/ID/column_ids'); oldformat = false; info = hdf5info(infilename); datasets = info.GroupHierarchy.Datasets; for ii=1:length(datasets) if strcmp(datasets(ii).Name,'/target_mask') oldformat = true; end end if oldformat key.tar = logical(hdf5read(infilename,'/target_mask','V71Dimensions',true)); key.non = logical(hdf5read(infilename,'/nontarget_mask','V71Dimensions',true)); else trialmask = hdf5read(infilename,'/trial_mask','V71Dimensions',true); key.tar = trialmask > 0.5; key.non = trialmask < -0.5; end assert(key.validate()) function cellstrarr = h5strings_to_cell(infilename,attribname) tmp = hdf5read(infilename,attribname,'V71Dimensions',true); numentries = length(tmp); cellstrarr = cell(numentries,1); for ii=1:numentries cellstrarr{ii} = tmp(ii).Data; end
github
bsxfan/meta-embeddings-master
filter.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/classes/@Ndx/filter.m
2,788
utf_8
6d39760ecafc786f43259d1adb98a810
function outndx = filter(inndx,modlist,seglist,keep) % Removes some of the information in an Ndx. Useful for creating a % gender specific Ndx from a pooled gender Ndx. Depending on the % value of 'keep', the two input lists indicate the strings to % retain or the strings to discard. % Inputs: % inndx: An Ndx object. % modlist: A cell array of strings which will be compared with % the modelset of 'inndx'. % seglist: A cell array of strings which will be compared with % the segset of 'inndx'. % keep: A boolean indicating whether modlist and seglist are the % models to keep or discard. % Outputs: % outndx: A filtered version of 'inndx'. if nargin == 0 test_this(); return end assert(nargin==4) assert(isa(inndx,'Ndx')) assert(inndx.validate()) assert(iscell(modlist)) assert(iscell(seglist)) if keep keepmods = modlist; keepsegs = seglist; else keepmods = setdiff(inndx.modelset,modlist); keepsegs = setdiff(inndx.segset,seglist); end keepmodidx = ismember(inndx.modelset,keepmods); keepsegidx = ismember(inndx.segset,keepsegs); outndx = Ndx(); outndx.modelset = inndx.modelset(keepmodidx); outndx.segset = inndx.segset(keepsegidx); outndx.trialmask = inndx.trialmask(keepmodidx,keepsegidx); assert(outndx.validate()) if length(inndx.modelset) > length(outndx.modelset) log_info('Number of models reduced from %d to %d.\n',length(inndx.modelset),length(outndx.modelset)); end if length(inndx.segset) > length(outndx.segset) log_info('Number of test segments reduced from %d to %d.\n',length(inndx.segset),length(outndx.segset)); end end function test_this() ndx = Ndx(); ndx.modelset = {'aaa','bbb','ccc','ddd'}; ndx.segset = {'11','22','33','44','55'}; ndx.trialmask = true(4,5); fprintf('ndx.modelset\n'); disp(ndx.modelset) fprintf('ndx.segset\n'); disp(ndx.segset) fprintf('ndx.trialmask\n'); disp(ndx.trialmask) modlist = {'bbb','ddd'} seglist = {'11','55'} keep = true out = Ndx.filter(ndx,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.trialmask\n'); disp(out.trialmask) keep = false out = Ndx.filter(ndx,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.trialmask\n'); disp(out.trialmask) modlist = {'bbb','ddd','eee'} seglist = {'11','66','77','55'} keep = true out = Ndx.filter(ndx,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.trialmask\n'); disp(out.trialmask) keep = false out = Ndx.filter(ndx,modlist,seglist,keep); fprintf('out.modelset\n'); disp(out.modelset) fprintf('out.segset\n'); disp(out.segset) fprintf('out.trialmask\n'); disp(out.trialmask) end
github
bsxfan/meta-embeddings-master
read_hdf5.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/classes/@Ndx/read_hdf5.m
838
utf_8
424ae971c22eb22cf8c27af6130b9698
function ndx = read_hdf5(infilename) % Creates an Ndx object from the information in an hdf5 file. % Inputs: % infilename: The name of the hdf5 file contain the information % necessary to construct an Ndx object. % Outputs: % ndx: An Ndx object containing the information in the input % file. assert(nargin==1) assert(isa(infilename,'char')) ndx = Ndx(); ndx.modelset = h5strings_to_cell(infilename,'/ID/row_ids'); ndx.segset = h5strings_to_cell(infilename,'/ID/column_ids'); ndx.trialmask = logical(hdf5read(infilename,'/trial_mask','V71Dimensions',true)); assert(ndx.validate()) function cellstrarr = h5strings_to_cell(infilename,attribname) tmp = hdf5read(infilename,attribname,'V71Dimensions',true); numentries = length(tmp); cellstrarr = cell(numentries,1); for ii=1:numentries cellstrarr{ii} = tmp(ii).Data; end
github
bsxfan/meta-embeddings-master
filter_on_right.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/classes/@Id_Map/filter_on_right.m
1,885
utf_8
deb124220c828ae065475bc93957d53f
function out_idmap = filter_on_right(in_idmap,idlist,keep) % Removes some of the information in an idmap. Depending on the % value of 'keep', the idlist indicates the strings to retain or % the strings to discard. % Inputs: % in_idmap: An Id_Map object to be pruned. % idlist: A cell array of strings which will be compared with % the rightids of 'in_idmap'. % keep: A boolean indicating whether idlist contains the ids to % keep or to discard. % Outputs: % out_idmap: A filtered version of 'in_idmap'. if nargin == 0 test_this(); return end assert(nargin==3) assert(isa(in_idmap,'Id_Map')) assert(in_idmap.validate()) assert(iscell(idlist)) if keep keepids = idlist; else keepids = setdiff(in_idmap.rightids,idlist); end keep_idx = ismember(in_idmap.rightids,keepids); out_idmap = Id_Map(); out_idmap.leftids = in_idmap.leftids(keep_idx); out_idmap.rightids = in_idmap.rightids(keep_idx); assert(out_idmap.validate(false)) end function test_this() idmap = Id_Map(); idmap.leftids = {'aaa','bbb','ccc','bbb','ddd','eee'}; idmap.rightids = {'11','22','33','44','55','22'}; fprintf('idmap.leftids\n'); disp(idmap.leftids) fprintf('idmap.rightids\n'); disp(idmap.rightids) idlist = {'22','44'} keep = true out = Id_Map.filter_on_right(idmap,idlist,keep); fprintf('out.leftids\n'); disp(out.leftids) fprintf('out.rightids\n'); disp(out.rightids) keep = false out = Id_Map.filter_on_right(idmap,idlist,keep); fprintf('out.leftids\n'); disp(out.leftids) fprintf('out.rightids\n'); disp(out.rightids) idlist = {'11','33','66'} keep = true out = Id_Map.filter_on_right(idmap,idlist,keep); fprintf('out.leftids\n'); disp(out.leftids) fprintf('out.rightids\n'); disp(out.rightids) keep = false out = Id_Map.filter_on_right(idmap,idlist,keep); fprintf('out.leftids\n'); disp(out.leftids) fprintf('out.rightids\n'); disp(out.rightids) end
github
bsxfan/meta-embeddings-master
read_hdf5.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/classes/@Id_Map/read_hdf5.m
777
utf_8
47581f23817e49ffc325aed95a088106
function idmap = read_hdf5(infilename) % Creates an Id_Map object from the information in an hdf5 file. % Inputs: % infilename: The name of the hdf5 file containing the information % necessary to construct an Id_Map object. % Outputs: % idmap: An Id_Map object containing the information in the input % file. assert(nargin==1) assert(isa(infilename,'char')) idmap = Id_Map(); idmap.leftids = h5strings_to_cell(infilename,'/left_ids'); idmap.rightids = h5strings_to_cell(infilename,'/right_ids'); assert(idmap.validate()) function cellstrarr = h5strings_to_cell(infilename,attribname) tmp = hdf5read(infilename,attribname,'V71Dimensions',true); numentries = length(tmp); cellstrarr = cell(numentries,1); for ii=1:numentries cellstrarr{ii} = tmp(ii).Data; end
github
bsxfan/meta-embeddings-master
filter_on_left.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/bosaris_toolkit/classes/@Id_Map/filter_on_left.m
1,871
utf_8
27abe0c92b6ff488892e389fee1fb5e9
function out_idmap = filter_on_left(in_idmap,idlist,keep) % Removes some of the information in an idmap. Depending on the % value of 'keep', the idlist indicates the strings to retain or % the strings to discard. % Inputs: % in_idmap: An Id_Map object to be pruned. % idlist: A cell array of strings which will be compared with % the leftids of 'in_idmap'. % keep: A boolean indicating whether idlist contains the ids to % keep or to discard. % Outputs: % out_idmap: A filtered version of 'in_idmap'. if nargin == 0 test_this(); return end assert(nargin==3) assert(isa(in_idmap,'Id_Map')) assert(in_idmap.validate()) assert(iscell(idlist)) if keep keepids = idlist; else keepids = setdiff(in_idmap.leftids,idlist); end keep_idx = ismember(in_idmap.leftids,keepids); out_idmap = Id_Map(); out_idmap.leftids = in_idmap.leftids(keep_idx); out_idmap.rightids = in_idmap.rightids(keep_idx); assert(out_idmap.validate(false)) end function test_this() idmap = Id_Map(); idmap.leftids = {'aaa','bbb','ccc','bbb','ddd'}; idmap.rightids = {'11','22','33','44','55'}; fprintf('idmap.leftids\n'); disp(idmap.leftids) fprintf('idmap.rightids\n'); disp(idmap.rightids) idlist = {'bbb','ddd'} keep = true out = Id_Map.filter_on_left(idmap,idlist,keep); fprintf('out.leftids\n'); disp(out.leftids) fprintf('out.rightids\n'); disp(out.rightids) keep = false out = Id_Map.filter_on_left(idmap,idlist,keep); fprintf('out.leftids\n'); disp(out.leftids) fprintf('out.rightids\n'); disp(out.rightids) idlist = {'bbb','ddd','eee'} keep = true out = Id_Map.filter_on_left(idmap,idlist,keep); fprintf('out.leftids\n'); disp(out.leftids) fprintf('out.rightids\n'); disp(out.rightids) keep = false out = Id_Map.filter_on_left(idmap,idlist,keep); fprintf('out.leftids\n'); disp(out.leftids) fprintf('out.rightids\n'); disp(out.rightids) end
github
bsxfan/meta-embeddings-master
L_BFGS.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/optimization/L_BFGS.m
5,021
utf_8
ccfcc8e580c4dfa191a42bfcbaf055cb
function [w,y,mem,logs] = L_BFGS(obj,w,maxiters,timeout,mem,stpsz0,callback) % L-BFGS Quasi-Newton unconstrained optimizer. % -- This has a small interface change from LBFGS.m -- % % Inputs: % obj: optimization objective, with interface: [y,grad] = obj(w), % where w is the parameter vector, y is the scalar objective value % and grad is a function handle, so that grad(1) gives the gradient % (same size as w). % w: the initial parameter vector % maxiters: max number of LBFGS iterations (line search iterations do not % count towards this limit). % timeout: LBFGS will stop when timeout (in seconds) is reached. % mem is either: (i) A struct with previously computed LBFGS data, to % allow resumption of iteration. % (ii) An integer: the size of the LBFGS memory. A good % default is 20. % %some linesearch magic numbers maxfev = 20; %max number of function evaluations stpmin = 1e-15; %same as Poblano default stpmax = 1e15; %same as Poblano default ftol = 1e-5; % as recommended by Nocedal (c1 in his book) gtol = 0.9; % as recommended by Nocedal (c2 in his book) xtol = 1e-15; %same as Poblano default quiet = false; %termination parameters %stopTol = 1e-5; %same as Poblano relFuncTol = 1e-6; %same as Poblano if ~exist('stpsz0','var') || isempty(stpsz0) stpsz0 = 1; end stpsz = stpsz0; if ~exist('timeout','var') || isempty(timeout) timeout = 15*60; fprintf('timeout defaulted to 15 minutes'); end; if ~exist('callback','var') || isempty(callback) ncbLogs = 0; else ncbLogs = length( callback(w) ); end; tic; dim = length(w); if ~isstruct(mem) m = mem; mem = []; mem.m = m; mem.sz = 0; mem.rho = zeros(1,m); mem.S = zeros(dim,m); mem.Y = zeros(dim,m); else m = mem.m; end if ~exist('y','var') || isempty(y) [y,grad] = obj(w); g = grad(1); fprintf('LBFGS 0: obj = %g, ||g||=%g\n',y,sqrt(g'*g)); end initial_y = y; logs = zeros(3+ncbLogs, maxiters); nlogs = 0; gmag = sqrt(g'*g); k = 0; while true if gmag< eps fprintf('LBFGS converged with tiny gradient\n'); break; end % choose direction p = -Hprod(g,mem); assert(g'*p<0,'p is not downhill'); % line search g0 = g; y0 = y; w0 = w; [w,y,grad,g,alpha,info,nfev] = minpack_cvsrch(obj,w,y,g,p,stpsz,... ftol,gtol,xtol, ... stpmin,stpmax,maxfev,quiet); stpsz = 1; delta_total = abs(initial_y-y); delta = abs(y0-y); if delta_total>eps relfunc = delta/delta_total; else relfunc = delta; end gmag = sqrt(g'*g); if info==1 %Wolfe is happy sk = w-w0; yk = g-g0; dot = sk'*yk; assert(dot>0); if mem.sz==m mem.S(:,1:m-1) = mem.S(:,2:m); mem.Y(:,1:m-1) = mem.Y(:,2:m); mem.rho(:,1:m-1) = mem.rho(:,2:m); else mem.sz = mem.sz + 1; end sz = mem.sz; mem.S(:,sz) = sk; mem.Y(:,sz) = yk; mem.rho(sz) = 1/dot; fprintf('LBFGS %i: ||g||/n = %g, rel = %g\n',k+1,gmag/length(g),relfunc); else fprintf('LBFGS %i: NO UPDATE, info = %i, ||g||/n = %g, rel = %g\n',k+1,info,gmag/length(g),relfunc); end time = toc; nlogs = nlogs+1; if ncbLogs > 0 logs(:,nlogs) = [time; y; nfev; callback(w)']; disp(logs(4:end,nlogs)'); else logs(:,nlogs) = [time;y;nfev]; end k = k + 1; if k>=maxiters fprintf('LBFGS stopped: maxiters exceeded\n'); break; end if time>timeout fprintf('LBFGS stopped: timeout\n'); break; end if relfunc < relFuncTol fprintf('\nTDN: stopped with minimal function change\n'); break; end end logs = logs(:,1:nlogs); end function r = Hprod(q,mem) if mem.sz==0 r = q; return; end sz = mem.sz; S = mem.S; Y = mem.Y; rho = mem.rho; alpha = zeros(1,sz); for i=sz:-1:1 alpha(i) = rho(i)*S(:,i)'*q; q = q - alpha(i)*Y(:,i); end yy = sum(Y(:,sz).^2,1); r = q/(rho(sz)*yy); for i=1:sz beta = rho(i)*Y(:,i)'*r; r = r + S(:,i)*(alpha(i)-beta); end end
github
bsxfan/meta-embeddings-master
create_PYCRP.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/CRP/create_PYCRP.m
13,438
utf_8
97417297bf1d08ceaa6be2bbfe82c2bb
function PYCRP = create_PYCRP(alpha,beta,e,n) % alpha: alpha>=0, concentration % beta: 0<= beta <=1, discount if nargin==0 %test_this2(); test_Gibbsmatrix() return; end if nargin==4 PYCRP = create_PYCRP(1,0); PYCRP.set_expected_number_tables(e,n,alpha,beta); return; else assert(nargin==2); end assert(alpha>=0); assert(beta>=0 && beta<=1); PYCRP.logprob = @logprob; PYCRP.logprob3 = @logprob3; PYCRP.sample = @sample; PYCRP.expected_number_tables = @expected_number_tables; PYCRP.set_expected_number_tables = @set_expected_number_tables; PYCRP.ent = @ent; PYCRP.getParams = @getParams; PYCRP.GibbsMatrix = @GibbsMatrix; PYCRP.slowGibbsMatrix = @slowGibbsMatrix; PYCRP.merge = @merge; PYCRP.merge_all_pairs = @merge_all_pairs; function [concentration,discount] = getParams() concentration = alpha; discount = beta; end function e = expected_number_tables(n) e = ent(alpha,beta,n); end function e = ent(alpha,beta,n) if alpha==0 && beta==0 e = 1; elseif isinf(alpha) e = n; elseif alpha>0 && beta>0 A = gammaln(alpha + beta + n) + gammaln(alpha + 1) ... - log(beta) - gammaln(alpha+n) - gammaln(alpha+beta); B = alpha/beta; e = B*expm1(A-log(B)); %exp(A)-B elseif alpha>0 && beta==0 e = alpha.*( psi(n+alpha) - psi(alpha) ); elseif alpha==0 && beta>0 A = gammaln(beta + n) - log(beta) - gammaln(n) - gammaln(beta); e = exp(A); end end function [flag,concentration,discount] = set_expected_number_tables(e,n,concentration,discount) if ~isempty(concentration) && ~isempty(discount) error('you can''t specify both parameters'); end if isempty(concentration) && isempty(discount) error('you must specify one parameter'); end if e<1 || e>n error('expectation must be between 1 and %i',n); end if isempty(concentration) assert(discount>=0 && discount<1); beta = discount; if beta==0 && e==1 alpha = 0; concentration = alpha; flag = 1; return; elseif e==n alpha = inf; concentration = alpha; flag = 1; return; end min_e = ent(0,beta,n); if e < min_e error('e=%g is impossible at discount=%g, minimum is e=%g',e,beta,min_e); end f = @(logalpha) ent(exp(logalpha),beta,n) - e; [logalpha,~,flag] = fzero(f,0); alpha = exp(logalpha); concentration = alpha; elseif isempty(discount) assert(concentration>=0); alpha = concentration; if alpha==0 && e==1 beta = 0; discount = beta; flag = 1; return; elseif e==n beta = 1; discount = beta; flag = 1; return; end min_e = ent(alpha,0,n); if e < min_e error('e=%g is impossible at concentration=%g, minimum is e=%min_e',e,alpha,min_e); end f = @(logitbeta) ent(alpha,sigmoid(logitbeta),n) - e; [logitbeta,~,flag] = fzero(f,0); beta = sigmoid(logitbeta); discount = beta; end end function y = sigmoid(x) y = 1./(1+exp(-x)); end function deltalogP = merge(i,j,counts) if i==j % no merge deltalogP = 0; return; end if isinf(alpha) || (beta==1) || (alpha==0 && beta==0) error('degenerate cases not handled'); end K = length(counts); T = sum(counts); if alpha>0 && beta>0 deltalogP = gammaln(counts(i) + counts(j) - beta) ... - gammaln(counts(i) - beta) - gammaln(counts(j) - beta) ... - log(beta) + gammaln(1-beta) ... - log(alpha/beta + K-1); elseif beta==0 && alpha>0 deltalogP = -log(alpha) + gammaln(counts(i)+counts(j)) ... - gammaln(counts(i)) - gammaln(counts(j)); elseif alpha==0 && beta>0 deltalogP = -log(beta) -log(K-1) + gammaln(1-beta) ... - gammaln(counts(i) - beta) - gammaln(counts(j) - beta) ... + gammaln(counts(i) + counts(j) - beta); end end function Y = mergeConst(K) if isinf(alpha) || (beta==1) || (alpha==0 && beta==0) error('degenerate cases not handled'); end if alpha>0 && beta>0 %Y = K*log(beta) + gammaln(alpha/beta + K) - K*gammaln(1-beta); Y = log(beta) + log(alpha/beta + K-1) - gammaln(1-beta); elseif beta==0 && alpha>0 %Y = K*log(alpha); Y = log(alpha); elseif beta>0 && alpha==0 %Y = (K-1)*log(beta) + gammaln(K) - K*gammaln(1-beta); Y = log(beta) + log(K-1) - gammaln(1-beta); end end %vectorization helps a lot (loopy version below is much slower) function deltalogP = merge_all_pairs(counts) K = length(counts); delta = counts-beta; gammalndelta = gammaln(delta); deltaC = mergeConst(K);%-mergeConst(K-1); oldlogP = bsxfun(@plus,gammalndelta+deltaC,gammalndelta.'); deltalogP = gammaln(bsxfun(@plus,counts-beta,counts.')) - oldlogP; deltalogP(1:K+1:end) = 0; end %loopy version is much, much slower % function deltalogP = merge_all_pairs2(counts) % K = length(counts); % delta = counts-beta; % gammalndelta = gammaln(delta); % deltaC = mergeConst(K-1)-mergeConst(K); % deltalogP = zeros(K,K); % for i=1:K-1 % for j=i+1:K % deltalogP(i,j) = deltaC + gammaln(delta(i)+counts(j)) - gammalndelta(i) - gammalndelta(j); % end % end % end function logP = logprob(counts) %Wikipedia K = length(counts); T = sum(counts); if isinf(alpha) && beta==1 %singleton tables if all(counts==1) logP = 0; else logP = -inf; end return; end if alpha==0 && beta==0 %single table if K==1 logP = 0; else logP = -inf; end return; end if alpha>0 && beta>0 % 2-param Pitman-Yor generalization logP = gammaln(alpha) - gammaln(alpha+T) + K*log(beta) ... + gammaln(alpha/beta + K) - gammaln(alpha/beta) ... + sum(gammaln(counts-beta)) ... - K*gammaln(1-beta); elseif beta==0 && alpha>0 % classical CRP logP = gammaln(alpha) + K*log(alpha) - gammaln(alpha+T) + sum(gammaln(counts)); elseif beta>0 && alpha==0 logP = (K-1)*log(beta) + gammaln(K) - gammaln(T) ... - K*gammaln(1-beta) + sum(gammaln(counts-beta)); end end % Seems wrong % function logP = logprob2(counts) % Goldwater % % % % K = length(counts); % T = sum(counts); % if beta>0 %Pitman-Yor generalization % logP = gammaln(1+alpha) - gammaln(alpha+T) ... % + sum(beta*(1:K-1)+alpha) ... % + sum(gammaln(counts-beta)) ... % - K*gammaln(1-beta); % else %1 parameter CRP % logP = gammaln(1+alpha) + (K-1)*log(alpha) - gammaln(alpha+T) + sum(gammaln(counts)); % end % % end % Agrees with Wikipedia version (faster for small counts) function logP = logprob3(counts) logP = 0; n = 0; for k=1:length(counts) % seat first customer at new table if k>1 logP = logP +log((alpha+(k-1)*beta)/(n+alpha)); end n = n + 1; % seat the rest at this table for i = 2:counts(k) logP = logP + log((i-1-beta)/(n+alpha)); n = n + 1; end end end % GibbsMatrix. Computes matrix of conditional log-probabilities % suitable for Gibbs sampling, or pseudolikelihood calculation. % Input: % labels: n-vector, maps each of n customers to a table in 1..m % Output: % logP: (m+1)-by-n matrix of **unnormalized** log-probabilities % logP(i,j) = log P(customer j at table i | seating of all others) + const % table m+1 is a new table function [logP,empties] = GibbsMatrix(labels) m = max(labels); n = length(labels); blocks = sparse(labels,1:n,true); counts = full(sum(blocks,2)); %original table sizes logP = repmat(log([counts-beta;alpha+m*beta]),1,n); %most common values for every row %return; empties = false(1,n); %new empty table when customer j removed for i=1:m cmin = counts(i) - 1; tar = blocks(i,:); if cmin==0 %table empty logP(i,tar) = log(alpha + (m-1)*beta); empties(tar) = true; else logP(i,tar) = log(cmin-beta); end end logP(m+1,empties) = -inf; end function logP = slowGibbsMatrix(labels) m = max(labels); n = length(labels); blocks = sparse(labels,1:n,true,m+1,n); counts = full(sum(blocks,2)); %original table sizes logP = zeros(m+1,n); for j=1:n cj = counts; tj = labels(j); cj(tj) = cj(tj) - 1; nz = cj>0; k = sum(nz); if k==m logP(nz,j) = log(cj(nz) - beta); logP(m+1,j) = log(alpha + m*beta); else %new empty table logP(nz,j) = log(cj(nz) - beta); logP(tj,j) = log(alpha + k*beta); logP(m+1,j) = -inf; end end end function [labels,counts] = sample(T) labels = zeros(1,T); counts = zeros(1,T); labels(1) = 1; K = 1; %number of classes counts(1) = 1; for i=2:T p = zeros(K+1,1); p(1:K) = counts(1:K) - beta; p(K+1) = alpha + K*beta; [~,k] = max(randgumbel(K+1,1) + log(p)); labels(i) = k; if k>K K = K + 1; assert(k==K); counts(k) = 1; else counts(k) = counts(k) + 1; end end counts = counts(1:K); labels = labels(randperm(T)); end end function test_this2() T = 20; e = 10; N = 1000; crp1 = create_PYCRP(0,[],e,T); [concentration,discount] = crp1.getParams() crp2 = create_PYCRP([],0,e,T); [concentration,discount] = crp2.getParams() K1 = zeros(1,T); K2 = zeros(1,T); for i=1:N [~,counts] = crp1.sample(T); K = length(counts); K1(K) = K1(K) + 1; [~,counts] = crp2.sample(T); K = length(counts); K2(K) = K2(K) + 1; end e1 = sum((1:T).*K1)/N e2 = sum((1:T).*K2)/N close all; subplot(2,1,1);bar(1:T,K1); subplot(2,1,2);bar(1:T,K2); K1 = K1/sum(K1); K2 = K2/sum(K2); %dlmwrite('K1.table',[(1:T)',K1'],' '); %dlmwrite('K2.table',[(1:T)',K2'],' '); for i=1:T fprintf('(%i,%6.4f) ',2*i-1,K1(i)) end fprintf('\n'); for i=1:T fprintf('(%i,%6.4f) ',2*i,K2(i)) end fprintf('\n'); end function test_Gibbsmatrix() alpha = randn^2; beta = rand; PYCRP = create_PYCRP(alpha,beta); labels = [1 1 1 2 1 3 4 4] logP = exp(PYCRP.slowGibbsMatrix(labels)) logP = exp(PYCRP.GibbsMatrix(labels)) end function test_this() alpha1 = 0.0; beta1 = 0.6; crp1 = create_PYCRP(alpha1,beta1); alpha2 = 0.1; beta2 = 0.6; crp2 = create_PYCRP(alpha2,beta2); close all; figure; hold; for i=1:100; L1 = crp1.sample(100); L2 = crp2.sample(100); C1=full(sum(int2onehot(L1),2)); C2=full(sum(int2onehot(L2),2)); x11 = crp1.logprob(C1); x12 = crp2.logprob3(C1); x22 = crp2.logprob3(C2); x21 = crp1.logprob(C2); plot(x11,x12,'.g'); plot(x21,x22,'.b'); end figure;hold; crp = crp1; for i=1:100; L1 = crp.sample(100); C1=full(sum(int2onehot(L1),2)); x = crp.logprob(C1); y = crp.logprob3(C1); plot(x,y); end end
github
bsxfan/meta-embeddings-master
rand_fake_Dirichlet.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/language_recognition/synth_data/rand_fake_Dirichlet.m
810
utf_8
3070cfe2d8487d8ae48c7740fdc24c2d
function R = rand_fake_Dirichlet(alpha,m,n) % This is no longer Dirichlet. I replaced it with a faster ad-hoc % distribution. % % Generates m-by-n matrix of n samples from m-category Dirichlet, with % concentration parameter: alpha > 0. if nargin==0 test_this(); return; end %R = reshape(randgamma(alpha,1,m*n),m,n); R = exp(alpha*randn(m,n).^2); R = bsxfun(@rdivide,R,sum(R,1)); end function E = app_exp(X) XX = X.^2/2; XXX = XX.*X/3; XXXX = XXX.*X/4; E = XXXX+ XXX + XX + X+1; end function test_this() close all; m = 400; %alpha = 1/(2*m); alpha = 2; n = 5000; R = rand_fake_Dirichlet(alpha,m,n); maxR = max(R,[],1); hist(maxR,100); % n = 50; % R = randDirichlet(alpha,m,n); % hist(R(:),100); end
github
bsxfan/meta-embeddings-master
create_T_backend.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/language_recognition/T_backend/create_T_backend.m
6,482
utf_8
ee013ab7facb848049ba586dfb7b6f33
function TBE = create_T_backend(nu,dim,K) % Create a (multivariate) T-distribution generative backend for multiclass classification. % The classes have different means, but the scatter matrix and degrees of % freedom are common to all clases. % % This object provides a method for supervised ML training (EM algorithm), % as well as a method for scoring at runtime (class log-likelihoods). % % Inputs: % nu: scalar >0, degrees of freedom % dim: data dimensionality % K: number of classes % % Typical usage: % > TBE = create_T-backend(nu,dim,K); %nu is fixed by user and not learnt during training % > TBE.train(TrainData,L,10); % TrainData: dim-by-N, L: K-by-N, (sparse) one-hot labels % > LLH = TBE.logLH(TestData) % % For EM algorithm, see: % Geoffrey J. McClachlan and Thriyambakam Krishnan, The EM Algorithm and Extensions, % 2nd Ed. John Wiley & Sons, 2008. Section 2.6 EXAMPLE 2.6: MULTIVARIATE t-DISTRIBUTION WITH KNOWN % DEGREES OF FREEDOM if nargin==0 test_this(); return; end assert(nu>0); Mu = zeros(dim,K); C = eye(dim); R = []; RMu = []; muWmu = []; logdetC = 0; prepare(); TBE.logLH = @logLH; TBE.getParams = @getParams; TBE.setParams = @setParams; TBE.train = @train; TBE.simulate = @simulate; TBE.randParams = @randParams; TBE.test_error_rate = @test_error_rate; TBE.cross_entropy = @cross_entropy; function [Mu1,C1] = getParams() Mu1 = Mu; C1 = C; end function setParams(Mu0,C0) Mu = Mu0; C = C0; prepare(); end function [obj,XE] = train(X,L,niters) [d,N] = size(X); assert(d==dim); [k,n] = size(L); assert(k==K && n==N); obj = zeros(1,niters+1); obj_i = EM_objective(X,L); obj(1) = obj_i; doXE = nargout>=2; if doXE XE = zeros(1,niters+1); XE_i = cross_entropy(X,L); XE(1) = XE_i; fprintf('%i: %g, %g\n',0,obj_i,XE_i); else fprintf('%i: %g\n',0,obj_i); end for i=1:niters EM_iteration(X,L); obj_i = EM_objective(X,L); obj(i+1) = obj_i; if doXE XE_i = cross_entropy(X,L); XE(i+1) = XE_i; fprintf('%i: %g, %g\n',i,obj_i,XE_i); else fprintf('%i: %g\n',i,obj_i); end end end %Class log-likelihood scores, with all irrelevant constants omitted function LLH = logLH(X,df) %inputs: % X: dim-by-N, data % df: [optional default df = nu], scalar, df>0, degrees of freedom parameter % %output: % LLH: K-by-N, class log-likelihoods if ~exist('df','var') || isempty(df) df = nu; else assert(df>0); end Delta = delta(X); LLH = (-0.5*(df+dim))*log1p(Delta/df); end function prepare() R = chol(C); % R'R = C and W = inv(C) = inv(R)*inv(R') RMu = R.'\Mu; % dim-dy-K muWmu = sum(RMu.^2,1); % 1-by-K logdetC = 2*sum(log(diag(R))); end function Delta = delta(X) %input X: dim-by-N, data %output Delta: K-by-N, squared Mahalanobis distances between data and means RX = R.'\X; % dim-by-N Delta = bsxfun(@minus,sum(RX.^2,1),(2*RMu).'*RX); %K-by-N Delta = bsxfun(@plus,Delta,muWmu.'); end function EM_iteration(X,L) Delta = sum(L.*delta(X),1); %1-by-N u = (nu+dim)./(nu+Delta); %1-by-N posterior expectations of hiddden precision scaling factors Lu = bsxfun(@times,L,u); %K-by-N normLu = bsxfun(@rdivide,Lu,sum(Lu,2)); newMu = X*normLu.'; %dim-by-K diff = X - newMu*L; newC = (bsxfun(@times,diff,u)*diff.')/sum(u); setParams(newMu,newC); end function obj = EM_objective(X,L) % X: dim-by-N, data % K: K-by-N, one-hot labels % obj: scalar LLH = logLH(X); N = size(X,2); obj = L(:).'*LLH(:) - (N/2)*logdetC ; end function randParams(ncov,muscale) assert(ncov>=dim); D = randn(dim,ncov); C = D*D.'; setParams(zeros(dim,K),C); Mu = muscale*simulate(K); setParams(Mu,C); end function [X,L] = simulate(N,df,L) if ~exist('L','var') || isempty(L) L = sparse(randi(K,1,N),1:N,1,K,N); end if ~exist('df','var') || isempty(df) df = ceil(nu); end u = sum(randn(df,N).^2,1)/df; % chi^2 with df dregrees of freedom, scaled so that <u>=1 X = Mu*L + bsxfun(@rdivide,R.'*randn(dim,N),sqrt(u)); end %assuming flat prior for now function e = test_error_rate(X,L) N = size(X,2); LLH = TBE.logLH(X); [~,labels] = max(LLH,[],1); Lhat = sparse(labels,1:N,1,K,N); e = 1-(L(:).'*Lhat(:))/N; end %assuming flat prior for now function e = cross_entropy(X,L,df) if ~exist('df','var') || isempty(df) df = nu; else assert(df>0); end LLH = TBE.logLH(X,df); P = exp(bsxfun(@minus,LLH,max(LLH,[],1))); P = bsxfun(@rdivide,P,sum(P,1)); e = -mean(log(full(sum(L.*P,1))),2)/log(K); end end function test_this() close all; dim = 100; % data dimensionality K = 10; % numer of classes nu = 3; % degrees of freedom (t-distribition parameter) N = K*1000; %create test and train data TBE0 = create_T_backend(nu,dim,K); TBE0.randParams(dim,5/sqrt(dim)); [X,L] = TBE0.simulate(N); [Xtest,Ltest] = TBE0.simulate(N); TBE = create_T_backend(nu,dim,K); [obj,XE] = TBE.train(X,L,20); subplot(1,2,1);plot(obj);title('error-rate'); subplot(1,2,2);plot(XE);title('cross-entropy'); train_error_rate = TBE.test_error_rate(X,L), test_error_rate = TBE.test_error_rate(Xtest,Ltest), train_XE = TBE.cross_entropy(X,L), test_XE = TBE.cross_entropy(Xtest,Ltest), df = [0.1:0.1:10]; XE = zeros(2,length(df)); for i=1:length(df) XE(1,i) = TBE.cross_entropy(X,L,df(i)); XE(2,i) = TBE.cross_entropy(Xtest,Ltest,df(i)); end figure;plot(df,XE(1,:),df,XE(2,:)); grid;xlabel('df');ylabel('XE'); legend('train','test'); end
github
bsxfan/meta-embeddings-master
train_TLDIvector.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/language_recognition/TLDIvector/train_TLDIvector.m
4,374
utf_8
6029b83917586ea3e2977c8fad616093
function [W,Mu,TT] = train_TLDIvector(stats_or_ivectors,N,T,TT,nu,labels,niters,W,Mu) % Inputs: % stats_or_ivectors: can be either F, or ivectors % F: dm-by-n first-order stats (m: UBM size; d: feature dim; n: no segments) % ivectors: k-by-n, classical i-vector point-estimates % N: m-by-n zero order stats % T: dm-by-k factor loading matrix % TT: [optional] k^2-by-m, vectorized precomputed T_i'T_i, i=1:m % nu: scalar, nu>0, degrees of freedom % labels: 1-by-n, label vector, with label values in 1:L, where L is % number of languages. % niters: number of VBEM iterations to do % % W: k-by-k within class precision [optional, for initialization] % Mu: k-by-L language means [optional, for initialization] % % % Outputs: % W: k-by-k within-class precision estimate % Mu: k-by-L class mean estimates if nargin==0 test_this(); return; end [A,B,k,n] = getPosteriorNatParams(stats_or_ivectors,N,T,TT); L = max(labels); if ~exist('Mu','var') || isempty(Mu) W = eye(k); Mu = zeros(k,L); else assert(all(size(W)==k)); [k2,L2] = size(Mu); assert(k2==k && L==L2); end for iter=1:niters WMu = W*Mu; C = zeros(size(W)); Pmeans = zeros(k,n); for ell=1:L tt = find(labels==ell); % E-step for t=tt Pt = W + reshape(B(:,t),k,k); %posterior precision Pmean = Pt\(WMu(:,ell)+A(:,t)); %posterior mean Pmeans(:,t) = Pmean; C = C + inv(Pt); end %M-step D = Pmeans(:,tt); Mu(:,ell) = mean(D,2); D = bsxfun(@minus,D,Mu(:,ell)); C = C + D*D.'; end C = C/n; W = inv(C), Mu = Mu, end end function test_this close all; %dimensions d = 10; %feature dimension m = 10; %no components k = 3; %ivector dimension n = 1000; %number of segments L = 2; %number of languages mindur = 2; maxdur = 100; niters = 3; T = randn(d*m,k); W = randn(k,k*2); W = W*W.'/k; UBM.logweights = randn(m,1)/5; UBM.Means = 5*randn(d,m); Mu = randn(k,L); [F,N,labels] = make_data(UBM,Mu,W,T,m,d,n,mindur,maxdur); dur = sum(N,1); L1 = labels==1; L2 = labels==2; TT = precomputeTT(T,d,k,m); ivectors = stats2ivectors(F,N,T,TT); LR1 = [1,-1]* score_LDIvector(F,N,T,TT,W,Mu); %LR2 = [1,-1]* score_LDIvector(ivectors,N,T,TT,W,Mu); subplot(4,1,1);plot(dur(L1),LR1(L1),'.r',dur(L2),LR1(L2),'.g'); [W2,Mu2] = train_LDIvector(F,N,T,[],labels,niters); [W3,Mu3] = train_LDIvector(ivectors,N,T,[],labels,niters); [W4,Mu4,map] = train_standaloneLGBE(ivectors,labels); LR2 = [1,-1]* score_LDIvector(F,N,T,[],W2,Mu2); LR3 = [1,-1]* score_CPF(ivectors,N,T,TT,W3,Mu3); LR4 = [1,-1]*map(ivectors); subplot(4,1,2);plot(dur(L1),LR2(L1),'.r',dur(L2),LR2(L2),'.g'); subplot(4,1,3);plot(dur(L1),LR3(L1),'.r',dur(L2),LR3(L2),'.g'); subplot(4,1,4);plot(dur(L1),LR4(L1),'.r',dur(L2),LR4(L2),'.g'); end function [F,N,labels,relConf] = make_data(UBM,Mu,W,T,m,d,n,mindur,maxdur) [k,L] = size(Mu); labels = randi(L,1,n); Labels = sparse(labels,1:n,1,L,n); %L-by-n one-hot class labels x = Mu*Labels+chol(W)\randn(k,n); %i-vectors Tx = T*x; dur = randi(1+maxdur-mindur,1,n) + mindur -1; dm = d*m; F = zeros(dm,n); N = zeros(m,n); logweights = UBM.logweights; prior = exp(logweights-max(logweights)); prior = prior/sum(prior); priorConfusion = exp(-prior.'*log(prior))-1; relConf = zeros(1,n); for i=1:n D = dur(i); states = randcatgumbel(UBM.logweights,D); States = sparse(states,1:D,1,m,D); X = (reshape(Tx(:,i),d,m)+UBM.Means)*States + randn(d,D); Q = bsxfun(@minus,UBM.Means.'*X,0.5*sum(X.^2,1)); Q = bsxfun(@plus,Q,UBM.logweights-0.5*sum(UBM.Means.^2,1).'); Q = exp(bsxfun(@minus,Q,max(Q,[],1))); Q = bsxfun(@rdivide,Q,sum(Q,1)); CE = -(States(:).'*log(Q(:)))/D; %cross entropy relConf(i) = (exp(CE)-1)/priorConfusion; Ni = sum(Q,2); Fi = X*Q.'; N(:,i) = Ni; F(:,i) = Fi(:); end end
github
bsxfan/meta-embeddings-master
create_diagonalized_C.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/language_recognition/TLDIvector/create_diagonalized_C.m
4,986
utf_8
c1a642f817fa817097bf89b070af4c04
function C = create_diagonalized_C(B,R,RM,Ra,W,M,a) % Creates object to represent: C = inv(lambda W + B), % % Inputs: % B: positive definite matrix (i-vector dimension) % R: chol(W), so that R'R=W (i-vector dimension) % RM: R*M, where M has language means in columns % Ra: (R')\a, vector (i-vector dimension) % W,M,a: optional for verification with slow version if nargin==0 test_this(); return; end dim = length(Ra); K = (R.'\B)/R; [V,D] = eig(K); %K = V*D*V' e = diag(D); %eigenvalues mWm = sum(RM.^2,1); %vector of m'Wm, for every language VRM = V.'*RM; VRa = V.'*Ra; VRaVRa = VRa.^2; VRMVRM = VRM.^2; VRMVRa = bsxfun(@times,VRa,VRM); C.traceCW = @traceCW; C.logdetCW = @logdetCW; C.quad = @quad; C.slowQuad = @slowQuad; C.slow_traceCW = @slow_traceCW; C.slow_logdetCW = @slow_logdetCW; C.lambda_by_root = @lambda_by_root; C.lambda_by_min = @lambda_by_min; C.lambda_by_fixed_point = @lambda_by_fixed_point; %C.slow_xCWCx = @slow_xCWCx; %C.xCWCx = @xCWCx; %C.xCx = @xCx; %C.slow_xCx = @slow_xCx; function log_lambda = lambda_by_root(nu,log_lambda,ell) f = @(log_lambda) log_lambda - log((nu+dim)/(nu+energy(log_lambda,ell))); log_lambda = fzero(f,log_lambda); end function log_lambda = lambda_by_fixed_point(nu,log_lambda,ell,niters) f = @(log_lambda) log((nu+dim)/(nu+energy(log_lambda,ell))); for i=1:niters log_lambda = f(log_lambda); end end function log_lambda = lambda_by_min(nu,log_lambda) f = @(log_lambda) (log_lambda - log((nu+dim)/(nu+energy(log_lambda))))^2; log_lambda = fminsearch(f,log_lambda); end function y = energy(log_lambda,ell) lambda = exp(log_lambda); y = quad(lambda,ell) + traceCW(lambda); %fprintf('%i: energy = %g\n%',ell,y); end function y = quad(lambda,ell) s = lambda + e; ss = s.^2; mWmu = sum(bsxfun(@rdivide, lambda*VRMVRM(:,ell) + VRMVRa(:,ell), s),1); muWmu = sum(bsxfun(@rdivide,bsxfun(@plus,... lambda^2*VRMVRM(:,ell) + ... (2*lambda)*VRMVRa(:,ell), ... VRaVRa), ss),1); y = mWm(ell) + muWmu -2*mWmu; end function y = slowQuad(lambda) P = lambda*W + B; cholP = chol(P); Mu = cholP\(cholP'\bsxfun(@plus,lambda*W*M,a)); delta = R*(Mu-M); y = sum(delta.^2,1); %y = sum(Mu.*(W*M),1); end % function y = xCx(lambda,x) % z = V'*((R.')\x); % s = lambda + e; % y = sum(z.^2./s,1); % end % % function y = xCWCx(lambda,x) % z = V'*((R.')\x); % s = lambda + e; % y = sum(z.^2./s.^2,1); % end % % function y = slow_xCx(lambda,x) % P = lambda*W+B; % y = x'*(P\x); % end % % function y = slow_xCWCx(lambda,x) % P = lambda*W+B; % z = P\x; % y = z.'*W*z; % end function [y,back] = traceCW(lambda) s = lambda + e; r = 1./s; y = sum(r,1); back = @back_this; function dlambda = back_this(dy) dr = dy; ds = (-dr)*r./s; dlambda = sum(ds,1); end end function y = slow_traceCW(lambda) P = lambda*W + B; cholP = chol(P); X = cholP.'\R.'; y = X(:).'*X(:); end function [y,back] = logdetCW(lambda) s = log(lambda) + log1p(e/lambda); y = -sum(s,1); back = @(dy) (-dy)*sum(1./(lambda+e)); end function y = slow_logdetCW(lambda) P = lambda*W + B; cholP = chol(P); y = 2*( sum(log(diag(R))) - sum(log(diag(cholP))) ); end end function test_this() dim = 400; L = 1; RR = randn(dim,dim);W = RR*RR'; RR = randn(dim,dim);B = RR*RR'; a = randn(dim,1); M = randn(dim,L); R = chol(W); C = create_diagonalized_C(B,R,R*M,(R')\a,W,M,a); lambda = rand/rand; %x = randn(dim,1); %[C.xCx(lambda,x),C.slow_xCx(lambda,x)] %tic;C.quad(lambda);toc %tic;C.slowQuad(lambda);toc %C.quad(lambda) %C.slowQuad(lambda) %[C.traceCW(lambda),C.slow_traceCW(lambda)] %[C.logdetCW(lambda),C.slow_logdetCW(lambda)] %[C.xCWCx(lambda,x),C.slow_xCWCx(lambda,x)] C.lambda_by_root(1,1) C.lambda_by_root(1,10) C.lambda_by_root(1,0.1) C.lambda_by_min(1,1) C.lambda_by_min(1,10) C.lambda_by_min(1,0.1) a = a*0; B = B*0; C = create_diagonalized_C(B,R,R*M,(R')\a,W,M,a); C.lambda_by_root(0.1,0.01) C.lambda_by_root(1,10) C.lambda_by_root(10,0.1) C.lambda_by_min(1,10) end
github
bsxfan/meta-embeddings-master
create_augmenting_backend.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/language_recognition/augmentation/create_augmenting_backend.m
3,599
utf_8
852abc76e3f7dfa8796f7015880bc788
function ABE = create_augmenting_backend(nu,dim,T,K,L) % Inputs: % nu: scalar nu>0, t-distribution degrees of freedom % dim: ivector dimension % T: i-vector extr\zctor T-matrix % K: UBM size % L: number of languages if nargin==0 test_this(); return; end assert(dim==size(T,2)); TBE = create_T_backend(nu,dim,L); augment = []; ABE.train = @train; ABE.logLH = @logLH; ABE.test_error_rate = @test_error_rate; ABE.cross_entropy = @cross_entropy; function [obj,AX] = train(X,Z,Labels,niters,ntiters) % X: ivectors % Z: zero-order stats % Labels: sparse one-hot label matrix if ~exist('niters','var') || isempty(niters) niters = 1; end if ~exist('ntiters','var') || isempty(ntiters) ntiters = 10; end assert(size(Labels,1)==L); assert(size(Labels,2)==size(X,2)); assert(size(Labels,2)==size(Z,2)); assert(size(Z,1)==K); assert(size(X,1)==dim); AX = X; obj = []; for i=1:niters obj_i = TBE.train(AX,Labels,ntiters); % starts with parameters from prev. iteration obj = [obj(:);obj_i(:)]; [Mu,C] = TBE.getParams(); augment = augment_i_vectors(T,K,Mu,C); if i<niters || nargout>=2 AX = augment(X,Z); end end end function [LLH,X] = logLH(X,Z) if exist('Z','var') && ~isempty(Z) X = augment(X,Z); end LLH = TBE.logLH(X); end %assuming flat prior for now function e = test_error_rate(X,Z,Labels) N = size(X,2); LLH = logLH(X,Z); [~,labels] = max(LLH,[],1); Lhat = sparse(labels,1:N,1,L,N); e = 1-(Labels(:).'*Lhat(:))/N; end %assuming flat prior for now function e = cross_entropy(X,Z,Labels) LLH = logLH(X,Z); P = exp(bsxfun(@minus,LLH,max(LLH,[],1))); P = bsxfun(@rdivide,P,sum(P,1)); e = -mean(log(full(sum(Labels.*P,1))),2)/log(L); end end function test_this() big = true; if big L = 10; %languages K = 1024; %UBM size nu = 2; %df dim = 400; %ivector dim fdim = 40; % feature dim minDur = 3*100; %3 sec maxDur = 30*100; %30 sec M = randn(dim,L); T = randn(K*fdim,dim); RR = randn(dim,2*dim);W = RR*RR'; Ntrain = 100; Ntest = 100; else L = 3; %languages K = 10; %UBM size nu = 2; %df dim = 40; %ivector dim fdim = 5; % feature dim minDur = 3*100; %3 sec maxDur = 30*100; %30 sec M = randn(dim,L); T = randn(K*fdim,dim); RR = randn(dim,2*dim);W = RR*RR'/100; Ntrain = 100; Ntest = 100; end fprintf('generating data\n'); [F,trainZ,trainLabels] = rand_ivector(M,nu,W,2,K,T,minDur,maxDur,Ntrain); [trainX,TT] = stats2ivectors(F,trainZ,T); [F,testZ,testLabels] = rand_ivector(M,nu,W,2,K,T,minDur,maxDur,Ntest); testX = stats2ivectors(F,testZ,T,TT); F = []; fprintf('training\n'); ABE = create_augmenting_backend(nu,dim,T,K,L); ABE.train(trainX,trainZ,trainLabels,2); train_error_rate = ABE.test_error_rate(trainX,trainZ,trainLabels), test_error_rate = ABE.test_error_rate(testX,testZ,testLabels), train_XE = ABE.cross_entropy(trainX,trainZ,trainLabels), test_XE = ABE.cross_entropy(testX,testZ,testLabels), end
github
bsxfan/meta-embeddings-master
testBackprop_rs.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/test/testBackprop_rs.m
2,198
utf_8
9d88acaf06002d97bf8eb2fdc07bf7b8
function total = testBackprop_rs(block,X,delta,mask) %same as testFBblock, but with real step if ~iscell(X) X = {X}; end dX = cellrndn(X); if exist('mask','var') assert(length(mask)==length(X)); dX = cellmask(dX,mask); end cX1 = cellstep(X,dX,delta); cX2 = cellstep(X,dX,-delta); DX = cell(size(X)); [Y,back] = block(X{:}); DY = randn(size(Y)); [DX{:}] = back(DY); %DX = J'*DY dot1 = celldot(DX,dX); %dX' * J' * DY cY1 = block(cX1{:}); cY2 = block(cX2{:}); [Y2,dY2] = recover(cY1,cY2,delta); %dY2 = J*dX dot2 = DY(:).'*dY2(:); %DY' * J* DX Y_diff = max(abs(Y(:)-Y2(:))), jacobian_diff = abs(dot1-dot2), total = Y_diff + jacobian_diff; if total < 1e-6 fprintf('\ntotal error=%g\n',total); else fprintf(2,'\ntotal error=%g\n',total); end end function R = cellrndn(X) if ~iscell(X) R = randn(size(X)); else R = cell(size(X)); for i=1:numel(X) R{i} = cellrndn(X{i}); end end end function C = cellstep(X,dX,delta) assert(all(size(X)==size(dX))); if ~iscell(X) C = X + delta*dX; else C = cell(size(X)); for i=1:numel(X) C{i} = cellstep(X{i},dX{i},delta); end end end function [R,D] = recover(cX1,cX2,delta) assert(all(size(cX1)==size(cX2))); if ~iscell(cX1) R = (cX1+cX2)/2; D = (cX1-cX2)/(2*delta); else R = cell(size(cX1)); D = cell(size(cX1)); for i=1:numel(cX1) [R{i},D{i}] = recover(cX1{i},cX2{i}); end end end function X = cellmask(X,mask) if ~iscell(X) assert(length(mask)==1); X = X*mask; else for i=1:numel(X) X{i} = cellmask(X{i},mask{i}); end end end function dot = celldot(X,Y) assert(all(size(X)==size(Y))); if ~iscell(X) dot = X(:).' * Y(:); else dot = 0; for i=1:numel(X) dot = dot + celldot(X{i},Y{i}); end end end
github
bsxfan/meta-embeddings-master
testBackprop_multi.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/test/testBackprop_multi.m
2,361
utf_8
ced4a5b7e925d5c00a2d991fb34d012c
function total = testBackprop_multi(block,nout,X,mask) % same as testBackprop, but handles multiple outputs if ~iscell(X) X = {X}; end dX = cellrndn(X); if exist('mask','var') assert(length(mask)==length(X)); dX = cellmask(dX,mask); end cX = cellcomplex(X,dX); DX = cell(size(X)); Y = cell(1,nout); [Y{:},back] = block(X{:}); DY = cell(size(Y)); for i=1:numel(DY) DY{i} = randn(size(Y{i})); end [DX{:}] = back(DY{:}); %DX = J'*DY dot1 = celldot(DX,dX); %dX' * J' * DY cY = cell(1,nout); Y2 = cell(1,nout); dY2 = cell(1,nout); [cY{:}] = block(cX{:}); for i=1:numel(cY) [Y2{i},dY2{i}] = recover(cY{i}); %dY2 = J*dX end dot2 = celldot(DY,dY2); %DY' * J* DX Y_diff = 0; for i=1:nout Y_diff = Y_diff + max(abs(Y{i}(:)-Y2{i}(:))); end Y_diff, jacobian_diff = abs(dot1-dot2), total = Y_diff + jacobian_diff; if total < 1e-6 fprintf('\ntotal error=%g\n',total); else fprintf(2,'\ntotal error=%g\n',total); end end function R = cellrndn(X) if ~iscell(X) R = randn(size(X)); else R = cell(size(X)); for i=1:numel(X) R{i} = cellrndn(X{i}); end end end function X = cellmask(X,mask) if ~iscell(X) assert(length(mask)==1); X = X*mask; else for i=1:numel(X) X{i} = cellmask(X{i},mask{i}); end end end function C = cellcomplex(X,dX) assert(all(size(X)==size(dX))); if ~iscell(X) C = complex(X,1e-20*dX); else C = cell(size(X)); for i=1:numel(X) C{i} = cellcomplex(X{i},dX{i}); end end end function [R,D] = recover(cX) if ~iscell(cX) R = real(cX); D = 1e20*imag(cX); else R = cell(size(cX)); D = cell(size(cX)); for i=1:numel(cX) [R{i},D{i}] = recover(cX{i}); end end end function dot = celldot(X,Y) assert(all(size(X)==size(Y))); if ~iscell(X) dot = X(:).' * Y(:); else dot = 0; for i=1:numel(X) dot = dot + celldot(X{i},Y{i}); end end end
github
bsxfan/meta-embeddings-master
testBackprop.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/test/testBackprop.m
2,015
utf_8
fc73fa404f5441c097eb63f249106078
function total = testBackprop(block,X,mask) if ~iscell(X) X = {X}; end dX = cellrndn(X); if exist('mask','var') assert(length(mask)==length(X)); dX = cellmask(dX,mask); end cX = cellcomplex(X,dX); DX = cell(size(X)); [Y,back] = block(X{:}); DY = randn(size(Y)); [DX{:}] = back(DY); %DX = J'*DY dot1 = celldot(DX,dX); %dX' * J' * DY cY = block(cX{:}); [Y2,dY2] = recover(cY); %dY2 = J*dX dot2 = DY(:).'*dY2(:); %DY' * J* DX Y_diff = max(abs(Y(:)-Y2(:))), jacobian_diff = abs(dot1-dot2), total = Y_diff + jacobian_diff; if total < 1e-6 fprintf('\ntotal error=%g\n',total); else fprintf(2,'\ntotal error=%g\n',total); end end function R = cellrndn(X) if ~iscell(X) R = randn(size(X)); else R = cell(size(X)); for i=1:numel(X) R{i} = cellrndn(X{i}); end end end function X = cellmask(X,mask) if ~iscell(X) assert(length(mask)==1); X = X*mask; else for i=1:numel(X) X{i} = cellmask(X{i},mask{i}); end end end function C = cellcomplex(X,dX) assert(all(size(X)==size(dX))); if ~iscell(X) C = complex(X,1e-20*dX); else C = cell(size(X)); for i=1:numel(X) C{i} = cellcomplex(X{i},dX{i}); end end end function [R,D] = recover(cX) if ~iscell(cX) R = real(cX); D = 1e20*imag(cX); else R = cell(size(cX)); D = cell(size(cX)); for i=1:numel(cX) [R{i},D{i}] = recover(cX{i}); end end end function dot = celldot(X,Y) assert(all(size(X)==size(Y))); if ~iscell(X) dot = X(:).' * Y(:); else dot = 0; for i=1:numel(X) dot = dot + celldot(X{i},Y{i}); end end end
github
bsxfan/meta-embeddings-master
create_univariate_Laplace_node.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/create_univariate_Laplace_node.m
2,432
utf_8
723752e00cd25de77113d0e0c21ac71e
function node = create_univariate_Laplace_node(prior) if nargin==0 test_this(); return; end value = prior.sample(); %posterior stuff post_mu = []; %approximate posterior mean post_h = []; %approximate posterior hessian (- precision) %logpost = []; %unnormalized true log posterior node.get = @get; node.sample = @sample; node.condition_on_child = @condition_on_child; node.logPosterior_at_mode = @logPosterior_at_mode; function val = get() val = value; end % samples from prior/posterior % if n is given, draws n samples and does not change internal value % if n is not given, draws one sample and does change internal value function val = sample(n) if nargin==0 n = 1; end if isempty(post_mu) val = prior.sample(n); else val = post_mu + randn(1,n)/sqrt(-post_h); end if nargin==0 value = val; end end function [logPost,mode] = logPosterior_at_mode() if isempty(post_mu) [logPost,mode] = prior.logPosterior_at_mode(); else mode = post_mu; logPost = log(-post_h)/2; end end function [mu,sigma,logpost] = condition_on_child(llh_message) s0 = value; f = @(s) - llh_message.llh(s) - prior.logPDF(s); [mu,fmin,flag] = fminsearch(f,s0); assert(flag==1,'fminsearch failed'); h = llh_message.Hessian(mu) + prior.Hessian(mu); post_mu = mu; post_h = h; sigma = 1/sqrt(-h); if nargout>=3 logpost = @(s) fmin - f(s); end end end function test_this() close all; mu = 0; v = 5; wsz = 100; prior = create_uvg_Prior(mu,v); alpha_node = create_univariate_Laplace_node(prior); logalpha0 = alpha_node.get(); w_node = create_symmetricDirichlet_node(logalpha0,wsz); %logw0 = w_node.get(); ncm = w_node.inferParent(); [mu,sigma,logpost] = alpha_node.condition_on_child(ncm); x = (-1:0.01:1)*4*sigma + mu; y = exp(logpost(x)); lap = exp((x-mu).^2/(-2*sigma^2)); logalpha = alpha_node.sample(); plot(x,y,'g',x,lap,'r--',logalpha,0,'r*',logalpha0,0,'g*');grid; legend('posterior','laplace','laplace sample','true value'); end
github
bsxfan/meta-embeddings-master
create_symmetricDirichlet_node.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/create_symmetricDirichlet_node.m
5,749
utf_8
29d843a52a81df9405bb868555c339bf
function node = create_symmetricDirichlet_node(logalpha,sz) % Creates symmetric Dirichlet node (part of a Bayesian network), that is % equippped to do alternating Gibbs sampling. This node expects a % non-conjugate (upstream) hyper-prior to supply the Dirichlet parameter % alpha. It also expects (downstream) one or more categorical % distributions (conjugate), all parametrized IID by the vector w, % where w = {w_i} are the category probabilities. % % Inputs: % sz: the number of categories % % Output: % node.sample: function handle to do a Gibbs sampling step, sampling from % P(w | alpha, counts). The function returns messages to all % its neighbours: % log(w): downstream to the conjugate categorical % children. % likelhood function for log alpha: log P(w | log alpha) % to the non-conjugate % upstream parent. if nargin==0 test_this(); return; end alpha = exp(logalpha); counts = 0; w = randg(alpha+counts,sz,1); w = w/sum(w); logw = log(w); node.get = @get; node.sample = @sample; node.condition_on_child = @condition_on_child; node.condition_on_parent = @condition_on_parent; node.inferParent = @inferParent; node.logPosterior_at_default = @logPosterior_at_default; function logP = logPosterior_at_default() % default: w = 1/sz alpha_c = alpha + counts; total = sum(alpha_c); logP = (sz-total)*log(sz) + gammaln(total) - sum(gammaln(alpha_c)); end function val = get() val = logw; end function condition_on_parent(logalpha_new) logalpha = logalpha_new; alpha = exp(logalpha); end function condition_on_child(observed_counts) counts = observed_counts(:); end function val = sample(n) if nargin==0 n = 1; end w = randg(alpha+counts,sz,n); w = w/sum(w); val = log(w); if nargin==0 logw = val; end end % Outputs: % ncm: non-conjugate-message (likelihood function) sent to hyper-prior for alpha function ncm = inferParent(givenChild) if nargin==0 || ~givenChild %infer parent given the current value of this node sumlogw = sum(logw); ncm.llh = @(logalpha) llh_this(logalpha,sz,sumlogw); ncm.Hessian = @(logalpha) llh_Hessian(logalpha,sz,sumlogw); else %infer parent after collapsing this node ncm.llh = @(logalpha) llh_collapsed(logalpha,counts); ncm.Hessian = @(logalpha) collapsed_Hessian(logalpha,counts); end end end function [y,y1] = llh_collapsed(logalpha,counts) alpha = exp(logalpha); sz = length(counts); sumC = full(sum(counts)); y = gammaln(sz*alpha) - gammaln(sz*alpha+sumC) + ... sum(gammaln(bsxfun(@plus,alpha,counts)),1) - sz*gammaln(alpha); if nargout>1 y1 = alpha.*( sz*psi(sz*alpha) - sz*psi(sz*alpha+sumC) + ... sum(psi(bsxfun(@plus,alpha,counts)),1) - sz*psi(alpha) ); end end function h = collapsed_Hessian(logalpha,counts) alpha = exp(logalpha); sz = length(counts); sumC = full(sum(counts)); y1 = alpha.*( sz*psi(sz*alpha) - sz*psi(sz*alpha+sumC) + ... sum(psi(bsxfun(@plus,alpha,counts)),1) - sz*psi(alpha) ); h = y1 + alpha.^2.*( sz^2*psi(1,sz*alpha) - sz^2*psi(1,sz*alpha+sumC) + ... sum(psi(1,bsxfun(@plus,alpha,counts)),1) - sz*psi(1,alpha) ); end function [y,y1] = llh_this(logalpha,sz,sumlogw) alpha = exp(logalpha); y = expm1(logalpha)*sumlogw + gammaln(sz*alpha) - sz*gammaln(alpha); if nargout>1 y1 = alpha.*(sumlogw + sz*psi(sz*alpha) - sz*psi(alpha) ); end end function h = llh_Hessian(logalpha,sz,sumlogw) alpha = exp(logalpha); y1 = alpha.*(sumlogw + sz*psi(sz*alpha) - sz*psi(alpha) ); h = y1 + alpha.*(sz^2*alpha.*psi(1,sz*alpha) - sz*alpha.*psi(1,alpha) ); end function test_this() close all; sz = 100; n = 1000; logalpha0 = 3; wnode = create_symmetricDirichlet_node(logalpha0,sz); logw0 = wnode.get(); labelnode = create_Label_node(logw0,n); counts = labelnode.inferParent(); wnode.condition_on_child(counts); wnode.sample(); ncm = wnode.inferParent(); logalpha = -5:0.01:5; [y,y1] = ncm.llh(logalpha); delta = 1e-3; [yplus,y1plus] = ncm.llh(logalpha+delta); [ymin,y1min] = ncm.llh(logalpha-delta); rstep1 = (yplus-ymin)/(2*delta); rstep2 = (y1plus-y1min)/(2*delta); h = ncm.Hessian(logalpha); subplot(2,2,1);plot(logalpha,y,logalpha,y1,logalpha,rstep1,'--',... logalpha,h,logalpha,rstep2,'--');legend('y','y1','rstep1','hess','rstep2');grid; subplot(2,2,3);plot(logalpha,exp(y-max(y)),logalpha0,0,'g*');grid; ncm = wnode.inferParent(true); logalpha = -5:0.01:10; [y,y1] = ncm.llh(logalpha); delta = 1e-3; [yplus,y1plus] = ncm.llh(logalpha+delta); [ymin,y1min] = ncm.llh(logalpha-delta); rstep1 = (yplus-ymin)/(2*delta); rstep2 = (y1plus-y1min)/(2*delta); h = ncm.Hessian(logalpha); subplot(2,2,2);plot(logalpha,y,logalpha,y1,logalpha,rstep1,'--',... logalpha,h,logalpha,rstep2,'--');legend('y','y1','rstep1','hess','rstep2');grid; subplot(2,2,4);plot(logalpha,exp(y-max(y)),logalpha0,0,'g*');grid; end
github
bsxfan/meta-embeddings-master
createDPMM.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/createDPMM.m
1,065
utf_8
6c6b4270dc5b4c5c841b1f8101fad8d6
function model = createDPMM(W,B,crp) if nargin==0 test_this(); return; end cholW = chol(W); cholB = chol(B); dim = size(W,1); model.sample = @sample; function [X,Means,hlabels,counts] = sample(n) [labels,counts] = crp.sample(n); m = length(counts); hlabels = sparse(labels,1:n,true,m,n); Means = cholB\randn(dim,m); X = cholW\randn(dim,n) + Means*hlabels; end end function P = sampleP(dim,tame) R = rand(dim,dim-1)/tame; P = eye(dim) + R*R.'; end function test_this() dim = 2; tame = 10; sep = 50; small = false; if small n = 8; ent = 3; else n = 1000; ent = 10; end crp = create_PYCRP([],0,ent,n); W = sep*sampleP(dim,tame); B = sampleP(dim,tame); model = createDPMM(W,B,crp); [X,Means,hlabels,counts] = model.sample(n); counts close all; plot(X(1,:),X(2,:),'.b',Means(1,:),Means(2,:),'*r'); end
github
bsxfan/meta-embeddings-master
create_truncGMM.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/create_truncGMM.m
11,488
utf_8
60dcde7a91887483186b7ebd904866fc
function model = create_truncGMM(W,F,alpha,m) % This is a truncated version of DP micture model, with a specified maximum number of % components. The observations are realted to the hidden cluster variables % like in an SPLDA model. The hidden variable for cluster i is z_i in R^d. % The observations, x_j are in R^D, where D>= d. The prior for the z_i is % IID: N(z_i | 0, I). The observations that belong to cluster i are % conditionally IID: N(x_j | F z_i, W^{-1} ). The SPLDA model parameters % are: % F: D-by-d, factor loading matrix % W: D-by-D, within cluster precision (inverse covariance) % % The other parameters are for the symmetric Dirichlet prior on mixture % weights, which has parameters alpha and m, where m is the maximum number % of mixture components: weights ~ Dir(alpha,m). % More generally, alpha may be an m-by-1 vector, for a non-symmetric Dirichlet % weight prior. if nargin==0 test_this(); return; end cholW = chol(W); dim = size(W,1); alpha = alpha(:); E = F'*W*F; %meta-embedding precision (before diagonalization) [V,Lambda] = eig(E); %E = V*Lambda*V'; P = V.'*(F.'*W); % projection to extract 1st-order meta-embedding stats Lambda = diag(Lambda); % The diagonal Lambda is the meta-embedding precision after % diagonalization. % We now have the likelihood, or meta-embedding: % P(x | z) \propto exp[ z'Px - 1/2 z' Lambda z ], where z is the % hidden variable after diagonalization. % % The (normal) posterior for z, given n observations {x_j} has natural % parameters: % sum_j P x_j and I + n Lambda FV = F*V; %projects from diagonalized Z to cluster means A = []; logThresh = log(1e-10); model.sampleData = @sampleData; model.sampleWeights = @sampleWeights; model.sampleZ = @sampleZ; model.sampleLabels = @sampleLabels; model.setData = @setData; model.label_log_posterior = @label_log_posterior; model.Means_given_labels = @Means_given_labels; model.fullGibbs_iteration = @fullGibbs_iteration; model.collapsedGibbs_iteration = @collapsedGibbs_iteration; model.mfvb_iteration = @mfvb_iteration; function setData(X) A = P*X; end % function Means = Z2Means(Z) % Means = FV*Z; % end %hlabels: m-by-n %Mu: D-by-m, posterior means for m cluster centroids %counts: 1-by-m, cluster occupancy counts (soft if hlabels is soft) %Q: posterior covariance for cluster i is: F*V*inv(diag(Q(:,i)))*V'*F.' function [Mu,Q,counts] = Means_given_labels(hlabels) if ~islogical(hlabels) [m,n] = size(hlabels); [~,L] = max(log(hlabels)-log(-log(rand(m,n))),[],1); hlabels = sparse(L,1:n,true,m,n); end counts = full(sum(hlabels,2)); %m-by-1 Q = 1 + Lambda*counts.'; % d-by-m Zhat = (A*hlabels.') ./ Q; %d-by-m Mu = FV*Zhat; end % hlabels (one hot columns), m-by-n % A = P*X, d-by-n function Z = sampleZ(hlabels,counts) %counts = full(sum(hlabels,2)); %m-by-1 Q = 1 + Lambda*counts.'; % d-by-m Zhat = (A*hlabels.') ./ Q; %d-by-m d = size(A,1); Z = Zhat + randn(d,m) ./ sqrt(Q); end function [weights,counts] = sampleWeights(hlabels) counts = sum(hlabels,2); weights = randDirichlet(alpha+counts,m,1); end % Z: d-by-m % A: d-by-n % weights: m-by-1 function hlabels = sampleLabels(Z,weights) n = size(A,2); Gumbel = -log(-log(rand(m,n))); %ZLambdaZ = sum(Z.*bsxfun(@times,Lambda,Z),1); % m-by-1 ZLambdaZ = Lambda.'*Z.^2; % m-by-1 Score = bsxfun(@plus,log(weights)-ZLambdaZ.'/2,Z.'*A); %m-by-n [~,L] = max(Gumbel+Score,[],1); hlabels = sparse(L,1:n,true,m,n); end function hlabels = fullGibbs_iteration(hlabels) [weights,counts] = sampleWeights(hlabels); Z = sampleZ(hlabels,counts); hlabels = sampleLabels(Z,weights); end % hlabels (one hot columns), m-by-n % A = P*X, d-by-n function [Zhat,Q] = mfvb_Z(respbilties,counts) %counts = sum(respbilties,2); %m-by-1 Q = 1 + Lambda*counts.'; % d-by-m Zhat = (A*respbilties.') ./ Q; %d-by-m end function [post_alpha,counts] = mfvb_Weights(respbilties) counts = sum(respbilties,2); post_alpha = alpha+counts; end % Z: d-by-m % A: d-by-n % weights: m-by-1 function respbilties = mfvb_Labels(Zhat,Q,post_alpha) ZLambdaZ = Lambda.'*Zhat.^2 + sum(bsxfun(@rdivide,Lambda,Q),1); % expected value log_weights = psi(post_alpha) - psi(sum(post_alpha)); % expected value R = bsxfun(@plus,log_weights-ZLambdaZ.'/2,Zhat.'*A); %m-by-n mx = max(R,[],1); R = bsxfun(@minus,R,mx); R(R<logThresh) = -inf; R = exp(R); R = bsxfun(@rdivide,R,sum(R,1)); respbilties = R; end function respbilties = mfvb_iteration(respbilties) [post_alpha,counts] = mfvb_Weights(respbilties); [Zhat,Q] = mfvb_Z(respbilties,counts); respbilties = mfvb_Labels(Zhat,Q,post_alpha); end function logPrior = label_log_prior(counts) % Compute P(labels) by marginalizing over hidden weights. The output is % in the form of un-normalized log probability. We use the % candidate's formula: % P(labels) = P(labels|weights) P(weights) / P(weights | labels) % where we conveniently set weights = 1/m. We ignore P(weights), % because we do not compute the normalizer. Since weights are uniform, % we can also ignore P(labels|weights). We need to compute % P(weights | labels) = Dir(weights | alpha + counts), with the % normalizer, which is a function of the counts (and the labels). logPrior = - logDirichlet(ones(m,1)/m,counts+alpha); % - log P(weights | labels) end function [llh,counts] = label_log_likelihood(hlabels) AL = A*hlabels.'; % d-by-m counts = sum(hlabels,2); %m-by-1 Q = Lambda*counts.'; % d-by-m logdetQ = sum(log1p(Q),1); Q = 1 + Q; %centroid posterior precisions Mu = AL ./ Q; %centroid posterior means llh = (Mu(:).'*AL(:) - sum(logdetQ,2))/2; end function [logP,counts] = label_log_posterior(hlabels) if ~islogical(hlabels) [m,n] = size(hlabels); [~,L] = max(log(hlabels)-log(-log(rand(m,n))),[],1); hlabels = sparse(L,1:n,true,m,n); end [logP,counts] = label_log_likelihood(hlabels); logP = logP + label_log_prior(counts); end function hlabels = collapsedGibbs_iteration(hlabels) n = size(A,2); for j=1:n hlabels(:,j) = false; AL0 = A*hlabels.'; % d-by-m counts0 = sum(hlabels,2); %m-by-1 nB0 = Lambda*counts0.'; % d-by-m counts1 = counts0+1; AL1 = bsxfun(@plus,AL0,A(:,j)); nB1 = bsxfun(@plus,nB0,Lambda); logdetQ0 = sum(log1p(nB0),1); logdetQ1 = sum(log1p(nB1),1); K0 = sum(AL0.^2./(1+nB0),1); K1 = sum(AL1.^2./(1+nB1),1); llh = (K1 - K0 - logdetQ1 + logdetQ0)/2; logPrior0 = gammaln(counts0+alpha); logPrior1 = gammaln(counts1+alpha); logPost = llh + (logPrior1 - logPrior0).'; [~,c] = max(logPost - log(-log(rand(1,m))),[],2); hlabels(c,j) = true; end end function hlabels = collapsedGibbs_slow(hlabels) n = size(A,2); for j = 1:n logP = zeros(m,1); hlabels(:,j) = false; for i=1:m hlabels(i,j) = true; logP(i) = label_log_posterior(hlabels); hlabels(i,j) = false; end [~,c] = max(logP-log(-log(rand(m,1))),[],1); hlabels(c,j) = true; end end function [X,Means,Z,weights,hlabels] = sampleData(n) d = size(F,2); weights = randDirichlet(alpha,m,1); Z = randn(d,m); Means = F*Z; [~,labels] = max(bsxfun(@minus,log(weights(:)),log(-log(rand(m,n)))),[],1); hlabels = sparse(labels,1:n,true,m,n); X = cholW\randn(dim,n) + Means*hlabels; end end function P = sampleP(dim,tame) R = rand(dim,dim-1)/tame; P = eye(dim) + R*R.'; end function test_this() dim = 2; tame = 10; sep = 2; %increase to move clusters further apart in simulated data small = false; alpha0 = 60; %increase to get more clusters if small n = 8; m = 20; else n = 1000; m = 100; end alpha = alpha0/m; W = sep*sampleP(dim,tame); B = sampleP(dim,tame); F = inv(chol(B)); EER = testEER(W,F,1000) pause(4) model = create_truncGMM(W,F,alpha,m); [X,Means,Z,weights,truelabels] = model.sampleData(n); counts = full(sum(truelabels,2).'); nz = counts>0; nzcounts = counts(nz) close all; cg_labels = sparse(randi(m,1,n),1:n,true,m,n); %random label init %cg_labels = sparse(ones(1,n),1:n,true,m,n); %single cluster init bg_labels = cg_labels; mf_labels = cg_labels; model.setData(X); niters = 1000; cg_delta = zeros(1,niters); bg_delta = zeros(1,niters); mf_delta = zeros(1,niters); mft = 0; bgt = 0; cgt = 0; cg_wct = zeros(1,niters); bg_wct = zeros(1,niters); mf_wct = zeros(1,niters); oracle = model.label_log_posterior(truelabels); for i=1:niters tic; bg_labels = model.fullGibbs_iteration(bg_labels); bgt = bgt + toc; bg_wct(i) = bgt; tic; cg_labels = model.collapsedGibbs_iteration(cg_labels); cgt = cgt + toc; cg_wct(i) = cgt; tic; mf_labels = model.mfvb_iteration(mf_labels); mft = mft + toc; mf_wct(i) = mft; cg_delta(i) = model.label_log_posterior(cg_labels) - oracle; bg_delta(i) = model.label_log_posterior(bg_labels) - oracle; mf_delta(i) = model.label_log_posterior(mf_labels) - oracle; [bgMu,~,bg_counts] = model.Means_given_labels(bg_labels); [cgMu,~,cg_counts] = model.Means_given_labels(cg_labels); [mfMu,~,mf_counts] = model.Means_given_labels(mf_labels); bg_nz = bg_counts>0; cg_nz = cg_counts>0; mf_nz = mf_counts>0; subplot(2,2,1);plot(X(1,:),X(2,:),'.b',Means(1,nz),Means(2,nz),'*r',bgMu(1,bg_nz),bgMu(2,bg_nz),'*g');title('full Gibbs'); subplot(2,2,2);plot(X(1,:),X(2,:),'.b',Means(1,nz),Means(2,nz),'*r',cgMu(1,cg_nz),cgMu(2,cg_nz),'*g');title('collapsed Gibbs'); subplot(2,2,3);plot(X(1,:),X(2,:),'.b',Means(1,nz),Means(2,nz),'*r',mfMu(1,mf_nz),mfMu(2,mf_nz),'*g');title('mean field VB'); subplot(2,2,4);semilogx(cg_wct(1:i),cg_delta(1:i),... bg_wct(1:i),bg_delta(1:i),... mf_wct(1:i),mf_delta(1:i)); xlabel('wall clock');ylabel('log P(sampled labels) - log P(true labels)') legend('clpsd Gibbs','full Gibbs','mfVB','Location','SouthEast'); pause(0.1); end end
github
bsxfan/meta-embeddings-master
test_GMM_Gibbs.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/test_GMM_Gibbs.m
3,062
utf_8
23d78374c004d789decbe42ff4a4e0a9
function test_GMM_Gibbs() close all; dim = 500; tame = 10; sep = 0.6e-3; %increase to move clusters further apart in smulated data %sep = sep*200; %sep = 1; alpha0 = 200; %increase to get more clusters n = 1000; m = 300; alpha = alpha0/m; W = sep*sampleP(dim,tame); %B = sampleP(dim,tame); %F = inv(chol(B)); d = 100; F = randn(dim,d); EER = testEER(W,F,1000) pause(4) model = create_truncGMM(W,F,alpha,m); [X,Means,Z,weights,truelabels] = model.sampleData(n); counts = full(sum(truelabels,2).'); nz = counts>0; nzcounts = counts(nz) close all; labels = sparse(randi(m,1,n),1:n,true,m,n); %random label init %labels = sparse(ones(1,n),1:n,true,m,n); %single cluster init model.setData(X); niters = 4000; delta = zeros(1,niters); wct = 0; time = delta; oracle = model.label_log_posterior(truelabels); for i=1:niters tic;labels = model.fullGibbs_iteration(labels);wct = wct+toc; time(i) = wct; %labels = model.collapsedGibbs_iteration(labels); %labels = model.mfvb_iteration(labels); delta(i) = model.label_log_posterior(labels) - oracle; counts = full(sum(labels,2).'); fprintf('%i: delta = %g, clusters = %i\n',i,delta(i),sum(counts>0)); end labels = sparse(randi(m,1,n),1:n,true,m,n); %random label init niters = 50; delta2 = zeros(1,niters); wct = 0; time2 = delta2; for i=1:niters %tic;labels = model.fullGibbs_iteration(labels);wct = wct+toc; tic;labels = model.collapsedGibbs_iteration(labels);wct = wct+toc; %labels = model.mfvb_iteration(labels); time2(i) = wct; delta2(i) = model.label_log_posterior(labels) - oracle; counts = full(sum(labels,2).'); fprintf('%i: delta = %g, clusters = %i\n',i,delta2(i),sum(counts>0)); end plot(time,delta,time2,delta2,'-*');legend('full','collapsed'); title(sprintf('D=%i, d=%i, EER=%g',dim,d,EER)); end function EER = testEER(W,F,nspk) [D,d] = size(F); Z = randn(d,nspk); Enroll = F*Z + chol(W)\randn(D,nspk); Tar = F*Z + chol(W)\randn(D,nspk); Non = F*randn(d,nspk) + chol(W)\randn(D,nspk); E = F'*W*F; %meta-embedding precision (before diagonalization) [V,Lambda] = eig(E); %E = V*Lambda*V'; P = V.'*(F.'*W); % projection to extract 1st-order meta-embedding stats Lambda = diag(Lambda); Aenroll = P*Enroll; Atar = P*Tar; Anon = P*Non; logMEE = @(A,n) ( sum(bsxfun(@rdivide,A.^2,1+n*Lambda),1) - sum(log1p(n*Lambda),1) ) /2; score = @(A1,A2) logMEE(A1+A2,2) - logMEE(A1,1) - logMEE(A2,1); tar = score(Aenroll,Atar); non = score(Aenroll,Anon); EER = eer(tar,non); end function P = sampleP(dim,tame) R = rand(dim,dim-1)/tame; P = eye(dim) + R*R.'; end
github
bsxfan/meta-embeddings-master
create_GibbsGMM.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/create_GibbsGMM.m
11,427
utf_8
39c2d8aee27ef2a790747bef2aae64c2
function model = create_GibbsGMM(W,F,alphaPrior,m) % This is a truncated version of DP micture model, with a specified maximum number of % components. The observations are realted to the hidden cluster variables % like in an SPLDA model. The hidden variable for cluster i is z_i in R^d. % The observations, x_j are in R^D, where D>= d. The prior for the z_i is % IID: N(z_i | 0, I). The observations that belong to cluster i are % conditionally IID: N(x_j | F z_i, W^{-1} ). The SPLDA model parameters % are: % F: D-by-d, factor loading matrix % W: D-by-D, within cluster precision (inverse covariance) % % The other parameters are for the symmetric Dirichlet prior on mixture % weights, which has parameters alpha and m, where m is the maximum number % of mixture components: weights ~ Dir(alpha,m). % More generally, alpha may be an m-by-1 vector, for a non-symmetric Dirichlet % weight prior. if nargin==0 test_this(); return; end cholW = chol(W); dim = size(W,1); alpha = alpha(:); E = F'*W*F; %meta-embedding precision (before diagonalization) [V,Lambda] = eig(E); %E = V*Lambda*V'; P = V.'*(F.'*W); % projection to extract 1st-order meta-embedding stats Lambda = diag(Lambda); % The diagonal Lambda is the meta-embedding precision after % diagonalization. % We now have the likelihood, or meta-embedding: % P(x | z) \propto exp[ z'Px - 1/2 z' Lambda z ], where z is the % hidden variable after diagonalization. % % The (normal) posterior for z, given n observations {x_j} has natural % parameters: % sum_j P x_j and I + n Lambda FV = F*V; %projects from diagonalized Z to cluster means A = []; logThresh = log(1e-10); model.sampleData = @sampleData; model.sampleWeights = @sampleWeights; model.sampleZ = @sampleZ; model.sampleLabels = @sampleLabels; model.setData = @setData; model.label_log_posterior = @label_log_posterior; model.Means_given_labels = @Means_given_labels; model.fullGibbs_iteration = @fullGibbs_iteration; model.collapsedGibbs_iteration = @collapsedGibbs_iteration; model.mfvb_iteration = @mfvb_iteration; function setData(X) A = P*X; end % function Means = Z2Means(Z) % Means = FV*Z; % end %hlabels: m-by-n %Mu: D-by-m, posterior means for m cluster centroids %counts: 1-by-m, cluster occupancy counts (soft if hlabels is soft) %Q: posterior covariance for cluster i is: F*V*inv(diag(Q(:,i)))*V'*F.' function [Mu,Q,counts] = Means_given_labels(hlabels) if ~islogical(hlabels) [m,n] = size(hlabels); [~,L] = max(log(hlabels)-log(-log(rand(m,n))),[],1); hlabels = sparse(L,1:n,true,m,n); end counts = full(sum(hlabels,2)); %m-by-1 Q = 1 + Lambda*counts.'; % d-by-m Zhat = (A*hlabels.') ./ Q; %d-by-m Mu = FV*Zhat; end % hlabels (one hot columns), m-by-n % A = P*X, d-by-n function Z = sampleZ(hlabels,counts) %counts = full(sum(hlabels,2)); %m-by-1 Q = 1 + Lambda*counts.'; % d-by-m Zhat = (A*hlabels.') ./ Q; %d-by-m d = size(A,1); Z = Zhat + randn(d,m) ./ sqrt(Q); end function [weights,counts] = sampleWeights(hlabels) counts = sum(hlabels,2); weights = randDirichlet(alpha+counts,m,1); end % Z: d-by-m % A: d-by-n % weights: m-by-1 function hlabels = sampleLabels(Z,weights) n = size(A,2); Gumbel = -log(-log(rand(m,n))); %ZLambdaZ = sum(Z.*bsxfun(@times,Lambda,Z),1); % m-by-1 ZLambdaZ = Lambda.'*Z.^2; % m-by-1 Score = bsxfun(@plus,log(weights)-ZLambdaZ.'/2,Z.'*A); %m-by-n [~,L] = max(Gumbel+Score,[],1); hlabels = sparse(L,1:n,true,m,n); end function hlabels = fullGibbs_iteration(hlabels) [weights,counts] = sampleWeights(hlabels); Z = sampleZ(hlabels,counts); hlabels = sampleLabels(Z,weights); end % hlabels (one hot columns), m-by-n % A = P*X, d-by-n function [Zhat,Q] = mfvb_Z(respbilties,counts) %counts = sum(respbilties,2); %m-by-1 Q = 1 + Lambda*counts.'; % d-by-m Zhat = (A*respbilties.') ./ Q; %d-by-m end function [post_alpha,counts] = mfvb_Weights(respbilties) counts = sum(respbilties,2); post_alpha = alpha+counts; end % Z: d-by-m % A: d-by-n % weights: m-by-1 function respbilties = mfvb_Labels(Zhat,Q,post_alpha) ZLambdaZ = Lambda.'*Zhat.^2 + sum(bsxfun(@rdivide,Lambda,Q),1); % expected value log_weights = psi(post_alpha) - psi(sum(post_alpha)); % expected value R = bsxfun(@plus,log_weights-ZLambdaZ.'/2,Zhat.'*A); %m-by-n mx = max(R,[],1); R = bsxfun(@minus,R,mx); R(R<logThresh) = -inf; R = exp(R); R = bsxfun(@rdivide,R,sum(R,1)); respbilties = R; end function respbilties = mfvb_iteration(respbilties) [post_alpha,counts] = mfvb_Weights(respbilties); [Zhat,Q] = mfvb_Z(respbilties,counts); respbilties = mfvb_Labels(Zhat,Q,post_alpha); end function logPrior = label_log_prior(counts) % Compute P(labels) by marginalizing over hidden weights. The output is % in the form of un-normalized log probability. We use the % candidate's formula: % P(labels) = P(labels|weights) P(weights) / P(weights | labels) % where we conveniently set weights = 1/m. We ignore P(weights), % because we do not compute the normalizer. Since weights are uniform, % we can also ignore P(labels|weights). We need to compute % P(weights | labels) = Dir(weights | alpha + counts), with the % normalizer, which is a function of the counts (and the labels). logPrior = - logDirichlet(ones(m,1)/m,counts+alpha); % - log P(weights | labels) end function [llh,counts] = label_log_likelihood(hlabels) AL = A*hlabels.'; % d-by-m counts = sum(hlabels,2); %m-by-1 Q = Lambda*counts.'; % d-by-m logdetQ = sum(log1p(Q),1); Q = 1 + Q; %centroid posterior precisions Mu = AL ./ Q; %centroid posterior means llh = (Mu(:).'*AL(:) - sum(logdetQ,2))/2; end function [logP,counts] = label_log_posterior(hlabels) if ~islogical(hlabels) [m,n] = size(hlabels); [~,L] = max(log(hlabels)-log(-log(rand(m,n))),[],1); hlabels = sparse(L,1:n,true,m,n); end [logP,counts] = label_log_likelihood(hlabels); logP = logP + label_log_prior(counts); end function hlabels = collapsedGibbs_iteration(hlabels) n = size(A,2); for j=1:n hlabels(:,j) = false; AL0 = A*hlabels.'; % d-by-m counts0 = sum(hlabels,2); %m-by-1 nB0 = Lambda*counts0.'; % d-by-m counts1 = counts0+1; AL1 = bsxfun(@plus,AL0,A(:,j)); nB1 = bsxfun(@plus,nB0,Lambda); logdetQ0 = sum(log1p(nB0),1); logdetQ1 = sum(log1p(nB1),1); K0 = sum(AL0.^2./(1+nB0),1); K1 = sum(AL1.^2./(1+nB1),1); llh = (K1 - K0 - logdetQ1 + logdetQ0)/2; logPrior0 = gammaln(counts0+alpha); logPrior1 = gammaln(counts1+alpha); logPost = llh + (logPrior1 - logPrior0).'; [~,c] = max(logPost - log(-log(rand(1,m))),[],2); hlabels(c,j) = true; end end function hlabels = collapsedGibbs_slow(hlabels) n = size(A,2); for j = 1:n logP = zeros(m,1); hlabels(:,j) = false; for i=1:m hlabels(i,j) = true; logP(i) = label_log_posterior(hlabels); hlabels(i,j) = false; end [~,c] = max(logP-log(-log(rand(m,1))),[],1); hlabels(c,j) = true; end end function [X,Means,Z,weights,hlabels] = sampleData(n) weights = randDirichlet(alpha,m,1); Z = randn(dim,m); Means = F*Z; [~,labels] = max(bsxfun(@minus,log(weights(:)),log(-log(rand(m,n)))),[],1); hlabels = sparse(labels,1:n,true,m,n); X = cholW\randn(dim,n) + Means*hlabels; end end function P = sampleP(dim,tame) R = rand(dim,dim-1)/tame; P = eye(dim) + R*R.'; end function test_this() dim = 2; tame = 10; sep = 500; %increase to move clusters further apart in smulated data small = false; alpha0 = 50; %increase to get more clusters if small n = 8; m = 20; else n = 1000; m = 100; end alpha = alpha0/m; W = sep*sampleP(dim,tame); B = sampleP(dim,tame); F = inv(chol(B)); model = create_truncGMM(W,F,alpha,m); [X,Means,Z,weights,truelabels] = model.sampleData(n); counts = full(sum(truelabels,2).'); nz = counts>0; nzcounts = counts(nz) close all; cg_labels = sparse(randi(m,1,n),1:n,true,m,n); %random label init %cg_labels = sparse(ones(1,n),1:n,true,m,n); %single cluster init bg_labels = cg_labels; mf_labels = cg_labels; model.setData(X); niters = 1000; cg_delta = zeros(1,niters); bg_delta = zeros(1,niters); mf_delta = zeros(1,niters); mft = 0; bgt = 0; cgt = 0; cg_wct = zeros(1,niters); bg_wct = zeros(1,niters); mf_wct = zeros(1,niters); oracle = model.label_log_posterior(truelabels); for i=1:niters tic; bg_labels = model.fullGibbs_iteration(bg_labels); bgt = bgt + toc; bg_wct(i) = bgt; tic; cg_labels = model.collapsedGibbs_iteration(cg_labels); cgt = cgt + toc; cg_wct(i) = cgt; tic; mf_labels = model.mfvb_iteration(mf_labels); mft = mft + toc; mf_wct(i) = mft; cg_delta(i) = model.label_log_posterior(cg_labels) - oracle; bg_delta(i) = model.label_log_posterior(bg_labels) - oracle; mf_delta(i) = model.label_log_posterior(mf_labels) - oracle; [bgMu,~,bg_counts] = model.Means_given_labels(bg_labels); [cgMu,~,cg_counts] = model.Means_given_labels(cg_labels); [mfMu,~,mf_counts] = model.Means_given_labels(mf_labels); bg_nz = bg_counts>0; cg_nz = cg_counts>0; mf_nz = mf_counts>0; subplot(2,2,1);plot(X(1,:),X(2,:),'.b',Means(1,nz),Means(2,nz),'*r',bgMu(1,bg_nz),bgMu(2,bg_nz),'*g');title('full Gibbs'); subplot(2,2,2);plot(X(1,:),X(2,:),'.b',Means(1,nz),Means(2,nz),'*r',cgMu(1,cg_nz),cgMu(2,cg_nz),'*g');title('collapsed Gibbs'); subplot(2,2,3);plot(X(1,:),X(2,:),'.b',Means(1,nz),Means(2,nz),'*r',mfMu(1,mf_nz),mfMu(2,mf_nz),'*g');title('mean field VB'); subplot(2,2,4);semilogx(cg_wct(1:i),cg_delta(1:i),... bg_wct(1:i),bg_delta(1:i),... mf_wct(1:i),mf_delta(1:i)); xlabel('wall clock');ylabel('log P(sampled labels) - log P(true labels)') legend('clpsd Gibbs','full Gibbs','mfVB','Location','SouthEast'); pause(0.1); end end
github
bsxfan/meta-embeddings-master
randg.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/randg.m
2,448
utf_8
bf1edfa92d41e108e3e1e2ef55461799
function G = randg(alpha,m,n) % Generates an m-by-n matrix of random gamma variates, having scale = 1 % and shape alpha. % Inputs: % alpha: scalar, vector or matrix % m,n: [optional] size of output matrix. If not given, the size is the % same as that of alpha. If given, then alpha should be m-by-n, or an % m-vector, or an n-row. % Output: % G: m-by-n matrix of gamma variates % % % Uses the method of: % Marsaglia & Tsang, "A Simple Method for Generating Gamma Variables", % 2000, ACM Transactions on Mathematical Software. 26(3). % % See also: % https://en.wikipedia.org/wiki/Gamma_distribution#Generating_gamma- % distributed_random_variables % % The speed is roughly independent of alpha. if nargin==0 test_this(); return; end if exist('m','var') assert(exist('n','var')>0,'illegal argument combination'); [mm,nn] = size(alpha); if isscalar(alpha) alpha = alpha*ones(m,n); elseif nn==1 && mm==m && n>1 alpha = repmat(alpha,1,n); elseif mm==1 && nn==n && m>1 alpha = repmat(alpha,m,1); else assert(m==mm && n==nn,'illegal argument combination'); end else [m,n] = size(alpha); end N = m*n; alpha = reshape(alpha,1,N); G = zeros(1,N); req = 1:N; small = alpha < 1; if any(small) ns = sum(small); sa = alpha(small); G(small) = randg(1+sa,1,ns).*rand(1,ns).^(1./sa); req(small)=[]; end nreq = length(req); d = alpha(req) - 1/3; c = 1./sqrt(9*d); while nreq>0 x = randn(1,nreq); v = (1+c.*x).^3; u = rand(1,nreq); ok = ( v>0 ) & ( log(u) < x.^2/2 + d.*(1 - v + log(v)) ); G(req(ok)) = d(ok).*v(ok); d(ok) = []; c(ok) = []; req(ok) = []; nreq = length(req); % This version works nicely, but can be made faster (fewer logs), % at the cost slightly more complex code---see the paper. end G = reshape(G,m,n); end function test_this() alpha = [0.1,1,10]; G = randg(repmat(alpha,10000,1)); mu = mean(G,1); v = mean(bsxfun(@minus,G,alpha).^2,1); [alpha;mu;v] alpha = pi; G = randg(alpha,10000,1); mu = mean(G,1); v = mean(bsxfun(@minus,G,alpha).^2,1); [alpha;mu;v] end
github
bsxfan/meta-embeddings-master
test_GMM_Gibbs_Balerion.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/test_GMM_Gibbs_Balerion.m
3,075
utf_8
e0afdf1916c50ecfbb2769db53b73d08
function test_GMM_Gibbs_Balerion() close all; dim = 500; tame = 10; sep = 0.6e-3; %increase to move clusters further apart in smulated data %sep = sep*200; %sep = 1; alpha0 = 1000; %increase to get more clusters n = 100000; m = 2000; alpha = alpha0/m; W = sep*sampleP(dim,tame); %B = sampleP(dim,tame); %F = inv(chol(B)); d = 100; F = randn(dim,d); EER = testEER(W,F,1000) pause(4) model = create_truncGMM(W,F,alpha,m); [X,Means,Z,weights,truelabels] = model.sampleData(n); counts = full(sum(truelabels,2).'); nz = counts>0; nzcounts = counts(nz) close all; labels = sparse(randi(m,1,n),1:n,true,m,n); %random label init %labels = sparse(ones(1,n),1:n,true,m,n); %single cluster init model.setData(X); niters = 2000; delta = zeros(1,niters); wct = 0; time = delta; oracle = model.label_log_posterior(truelabels); for i=1:niters tic;labels = model.fullGibbs_iteration(labels);wct = wct+toc; time(i) = wct; %labels = model.collapsedGibbs_iteration(labels); %labels = model.mfvb_iteration(labels); delta(i) = model.label_log_posterior(labels) - oracle; counts = full(sum(labels,2).'); fprintf('%i: delta = %g, clusters = %i\n',i,delta(i),sum(counts>0)); end labels = sparse(randi(m,1,n),1:n,true,m,n); %random label init niters = 50; delta2 = zeros(1,niters); wct = 0; time2 = delta2; for i=1:niters %tic;labels = model.fullGibbs_iteration(labels);wct = wct+toc; tic;labels = model.collapsedGibbs_iteration(labels);wct = wct+toc; %labels = model.mfvb_iteration(labels); time2(i) = wct; delta2(i) = model.label_log_posterior(labels) - oracle; counts = full(sum(labels,2).'); fprintf('%i: delta = %g, clusters = %i\n',i,delta2(i),sum(counts>0)); end plot(time,delta,time2,delta2,'-*');legend('full','collapsed'); title(sprintf('D=%i, d=%i, EER=%g',dim,d,EER)); end function EER = testEER(W,F,nspk) [D,d] = size(F); Z = randn(d,nspk); Enroll = F*Z + chol(W)\randn(D,nspk); Tar = F*Z + chol(W)\randn(D,nspk); Non = F*randn(d,nspk) + chol(W)\randn(D,nspk); E = F'*W*F; %meta-embedding precision (before diagonalization) [V,Lambda] = eig(E); %E = V*Lambda*V'; P = V.'*(F.'*W); % projection to extract 1st-order meta-embedding stats Lambda = diag(Lambda); Aenroll = P*Enroll; Atar = P*Tar; Anon = P*Non; logMEE = @(A,n) ( sum(bsxfun(@rdivide,A.^2,1+n*Lambda),1) - sum(log1p(n*Lambda),1) ) /2; score = @(A1,A2) logMEE(A1+A2,2) - logMEE(A1,1) - logMEE(A2,1); tar = score(Aenroll,Atar); non = score(Aenroll,Anon); EER = eer(tar,non); end function P = sampleP(dim,tame) R = rand(dim,dim-1)/tame; P = eye(dim) + R*R.'; end
github
bsxfan/meta-embeddings-master
dualAveraging.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/NUTS-matlab-master/dualAveraging.m
3,700
utf_8
95a22ca6047c33503568b405eb9968ef
function [theta, epsilonbar, epsilon_seq, epsilonbar_seq] = dualAveraging(f, theta0, delta, n_warmup, n_updates) % function [theta, epsilonbar, epsilon_seq, epsilonbar_seq] = dualAveraging(f, n_warmup, theta0, delta, n_updates) % % Adjusts the step-size of NUTS by the dual-averaging (stochastic % optimization) algorithm of Hoffman and Gelman (2014). % % Args: % f - function handle: returns the log probability of the target and % its gradient. % theta0 - column vector: the initial state of the chain % delta - double in the range [0, 1]: the target "acceptance rate" of NUTS. % n_warmup - int: the number of NUTS iterations for the dual-averaging % algorithm. % n_updates - int: the number of updates to be printed till the completion % of the step-size adjustment. % % Returns: % theta - last state of the chain after the step-size adjustment, which % can be used as the initial state for the sampling stage (no need for % additional 'burn-in' samples % epsilonbar - step-size corresponding to the target "acceptance rate". % epsilon_seq, epsilonbar_seq - column vectors: the whole history of the % attempted and averaged step-size. It can be used to diagnose the % convergence of the dual-averaging algorithm. % Default argment values. if nargin < 3 delta = 0.8; end if nargin < 4 n_warmup = 500; end if nargin < 5 n_updates = 5; end % Calculate the number of iterations per update. n_itr_per_update = floor(n_warmup / n_updates); [logp, grad] = f(theta0); % Parameters for NUTS max_tree_depth = 12; % Choose a reasonable first epsilon by a simple heuristic. [epsilon, nfevals_total] = find_reasonable_epsilon(theta0, grad, logp, f); % Parameters for the dual averaging algorithm. gamma = .05; t0 = 10; kappa = 0.75; mu = log(10 * epsilon); % Initialize dual averaging algorithm. epsilonbar = 1; epsilon_seq = zeros(n_warmup, 1); epsilonbar_seq = zeros(n_warmup, 1); epsilon_seq(1) = epsilon; Hbar = 0; theta = theta0; for i = 1:n_warmup [theta, ave_alpha, nfevals, logp, grad] = NUTS(f, epsilon, theta, logp, grad, max_tree_depth); nfevals_total = nfevals_total + nfevals; eta = 1 / (i + t0); Hbar = (1 - eta) * Hbar + eta * (delta - ave_alpha); epsilon = exp(mu - sqrt(i) / gamma * Hbar); epsilon_seq(i) = epsilon; eta = i^-kappa; epsilonbar = exp((1 - eta) * log(epsilonbar) + eta * log(epsilon)); epsilonbar_seq(i) = epsilonbar; % Update on the progress of simulation. if mod(i, n_itr_per_update) == 0 disp(['The ', num2str(i), ' iterations are complete.']) end end fprintf('Each iteration of NUTS required %.1f gradient evaluations during the step-size adjustment.\n', ... nfevals_total / (n_warmup + 1)); end function [epsilon, nfevals] = find_reasonable_epsilon(theta0, grad0, logp0, f) epsilon = 1; r0 = randn(length(theta0), 1); % Figure out what direction we should be moving epsilon. [~, rprime, ~, logpprime] = leapfrog(theta0, r0, grad0, epsilon, f); nfevals = 1; acceptprob = exp(logpprime - logp0 - 0.5 * (rprime' * rprime - r0' * r0)); a = 2 * (acceptprob > 0.5) - 1; % Keep moving epsilon in that direction until acceptprob crosses 0.5. while (acceptprob^a > 2^(-a)) epsilon = epsilon * 2^a; [~, rprime, ~, logpprime] = leapfrog(theta0, r0, grad0, epsilon, f); nfevals = nfevals + 1; acceptprob = exp(logpprime - logp0 - 0.5 * (rprime' * rprime - r0' * r0)); end end function [thetaprime, rprime, gradprime, logpprime] = leapfrog(theta, r, grad, epsilon, f) rprime = r + 0.5 * epsilon * grad; thetaprime = theta + epsilon * rprime; [logpprime, gradprime] = f(thetaprime); rprime = rprime + 0.5 * epsilon * gradprime; end
github
bsxfan/meta-embeddings-master
ESS.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/NUTS-matlab-master/ESS.m
2,793
utf_8
2f52219f2530dd16c3f9b2a395217f66
function [ess, auto_cor] = ESS(x, mu, sigma_sq) % function [ess, auto_cor] = ESS(x, mu, sigma_sq) % % Returns an estimate of effective sample sizes of a Markov chain 'x(:,i)' % for each i. The estimates are based on the monotone positive sequence estimator % of "Practical Markov Chain Monte Carlo" by Geyer (1992). The estimator is % ONLY VALID for reversible Markov chains. The inputs 'mu' and 'sigma_sq' are optional. % % Examples: % ess_for_mean = ESS(samples); % ess_for_second_moment = ESS(samples.^2) % % Args: % mu, sigma_sq - column vectors for the mean E(x) and variance Var(x) if the % analytical (or accurately estimated) value is available. If provided, % it can stabilize the estimate of auto-correlation of 'x(i,:)' and % hence its ESS. This is intended for research uses when one wants to % accurately quantify the asymptotic efficience of a MCMC algorithm. % % Returns: % ess - column vector of length size(x, 1) % auto_cor - cell array of length size(x, 1): the i-th cell contains the % auto-correlation estimate of 'x(i,:)' up to the lag at which the % auto-correlation can be considered insignificant by the monotonicity % criterion. if nargin < 2 mu = mean(x,2); sigma_sq = var(x,[],2); end d = size(x, 1); ess = zeros([d, 1]); auto_cor = cell(d, 1); % Difficult to avoid the loop for this estimator of ESS. for i = 1:d [ess(i), auto_cor{i}] = ESS_1d(x(i,:), mu(i), sigma_sq(i)); end end function [ess, auto_cor] = ESS_1d(x, mu, sigma_sq) [~, n] = size(x); auto_cor = []; lag = 0; even_auto_cor = computeAutoCorr(x, lag, mu, sigma_sq); auto_cor(end + 1) = even_auto_cor; auto_cor_sum = - even_auto_cor; lag = lag + 1; odd_auto_cor = computeAutoCorr(x, lag, mu, sigma_sq); auto_cor(end + 1) = odd_auto_cor; running_min = even_auto_cor + odd_auto_cor; while (even_auto_cor + odd_auto_cor > 0) && (lag + 2 < n) running_min = min(running_min, (even_auto_cor + odd_auto_cor)); auto_cor_sum = auto_cor_sum + 2 * running_min; lag = lag + 1; even_auto_cor = computeAutoCorr(x, lag, mu, sigma_sq); auto_cor(:, end + 1) = even_auto_cor; lag = lag + 1; odd_auto_cor = computeAutoCorr(x, lag, mu, sigma_sq); auto_cor(end + 1) = odd_auto_cor; end ess = n ./ auto_cor_sum; if auto_cor_sum < 0 % Rare, but can happen when 'x' shows strong negative correlations. ess = Inf; end end function [auto_corr] = computeAutoCorr(x, k, mu, sigma_sq) % Returns an estimate of the lag 'k' auto-correlation of a time series % ''. The estimator is biased towards zero due to the factor (n - k) / n. % See Geyer (1992) Section 3.1 and the reference therein for justification. n = length(x); t = 1:(n - k); auto_corr = (x(t) - mu) .* (x(t + k) - mu); auto_corr = mean(auto_corr) / sigma_sq * ((n - k) / n); end
github
bsxfan/meta-embeddings-master
NUTS.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/NUTS-matlab-master/NUTS.m
8,078
utf_8
7703b67677b18bbfd8fbcce670366463
function [theta, alpha_ave, nfevals, logp, grad] = NUTS(f, epsilon, theta0, logp0, grad0, max_tree_depth) % function [theta, grad, logp, nfevals, alpha_ave] = NUTS(f, epsilon, theta0, max_tree_depth, logp0, grad0) % % Carries out one iteration of No-U-Turn-Sampler. % % Args: % f - function handle: returns the log probability of the target and % its gradient. % epsilon - double: step size of leap-frog integrator % theta0 - column vector: current state of a Markov chain and the % initial state for the trajectory of Hamiltonian dynamcis. % % Optional args: % logp0 - double: log probability computed at theta0. See the comment on % 'grad0' for more info. % grad0 - column vector: gradient of the log probability computed at % theta0. If both 'grad0' and 'logp0' provided, it will save a bit % (one evaluation of 'f') of computation. The computational gain is % rather small when NUTS requires a long trajectory, so this is an % optional parameter. % max_tree_depth - int % % Returns: % theta - next state of the chain % logp - log probability computed at theta % alpha_ave - average acceptance probability of the states proposed at the % last doubling step of NUTS. It measures of the accuracy of the % numerical approximation of Hamiltonian dynamics and is used to find % an optimal step size value 'epsilon.' % nfevals - the number of log likelihood and gradient evaluations one % iteration of NUTS required % grad - gradient computed at theta (to feed into the next iteration of % NUTS if desired) % Copyright (c) 2011, Matthew D. Hoffman % All rights reserved. % % Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: % % Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. % Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. global nfevals; nfevals = 0; if nargin < 5 [logp0, grad0] = f(theta0); nfevals = nfevals + 1; end if nargin < 6 max_tree_depth = 10; end % Resample momenta. r0 = randn(size(theta0)); % Joint log-probability of theta and momenta r. joint = logp0 - 0.5 * (r0' * r0); % Resample u ~ uniform([0, exp(joint)]). % Equivalent to (log(u) - joint) ~ exponential(1). logu = joint - exprnd(1); % Initialize tree. thetaminus = theta0; thetaplus = theta0; rminus = r0; rplus = r0; gradminus = grad0; gradplus = grad0; % Initial height dir = 0. depth = 0; % If all else fails, the next sample is the previous sample. theta = theta0; grad = grad0; logp = logp0; % Initially the only valid point is the initial point. n = 1; % Main loop---keep going until the stop criterion is met. stop = false; while ~stop % Choose a direction. -1=backwards, 1=forwards. dir = 2 * (rand() < 0.5) - 1; % Double the size of the tree. if (dir == -1) [thetaminus, rminus, gradminus, ~, ~, ~, thetaprime, gradprime, logpprime, nprime, stopprime, alpha, nalpha] = ... build_tree(thetaminus, rminus, gradminus, logu, dir, depth, epsilon, f, joint); else [~, ~, ~, thetaplus, rplus, gradplus, thetaprime, gradprime, logpprime, nprime, stopprime, alpha, nalpha] = ... build_tree(thetaplus, rplus, gradplus, logu, dir, depth, epsilon, f, joint); end % Use Metropolis-Hastings to decide whether or not to move to a % point from the half-tree we just generated. if (~ stopprime && (rand() < nprime/n)) theta = thetaprime; logp = logpprime; grad = gradprime; end % Update number of valid points we've seen. n = n + nprime; % Decide if it's time to stop. stop = stopprime || stop_criterion(thetaminus, thetaplus, rminus, rplus); % Increment depth. depth = depth + 1; if depth > max_tree_depth disp('The current NUTS iteration reached the maximum tree depth.') break end end alpha_ave = alpha / nalpha; end function [thetaprime, rprime, gradprime, logpprime] = leapfrog(theta, r, grad, epsilon, f) rprime = r + 0.5 * epsilon * grad; thetaprime = theta + epsilon * rprime; [logpprime, gradprime] = f(thetaprime); rprime = rprime + 0.5 * epsilon * gradprime; global nfevals; nfevals = nfevals + 1; end function criterion = stop_criterion(thetaminus, thetaplus, rminus, rplus) thetavec = thetaplus - thetaminus; criterion = (thetavec' * rminus < 0) || (thetavec' * rplus < 0); end % The main recursion. function [thetaminus, rminus, gradminus, thetaplus, rplus, gradplus, thetaprime, gradprime, logpprime, nprime, stopprime, alphaprime, nalphaprime] = ... build_tree(theta, r, grad, logu, dir, depth, epsilon, f, joint0) if (depth == 0) % Base case: Take a single leapfrog step in the direction 'dir'. [thetaprime, rprime, gradprime, logpprime] = leapfrog(theta, r, grad, dir*epsilon, f); joint = logpprime - 0.5 * (rprime' * rprime); % Is the new point in the slice? nprime = logu < joint; % Is the simulation wildly inaccurate? stopprime = logu - 100 >= joint; % Set the return values---minus=plus for all things here, since the % "tree" is of depth 0. thetaminus = thetaprime; thetaplus = thetaprime; rminus = rprime; rplus = rprime; gradminus = gradprime; gradplus = gradprime; % Compute the acceptance probability. alphaprime = exp(logpprime - 0.5 * (rprime' * rprime) - joint0); if isnan(alphaprime) alphaprime = 0; else alphaprime = min(1, alphaprime); end nalphaprime = 1; else % Recursion: Implicitly build the height depth-1 left and right subtrees. [thetaminus, rminus, gradminus, thetaplus, rplus, gradplus, thetaprime, gradprime, logpprime, nprime, stopprime, alphaprime, nalphaprime] = ... build_tree(theta, r, grad, logu, dir, depth-1, epsilon, f, joint0); % No need to keep going if the stopping criteria were met in the first % subtree. if ~stopprime if (dir == -1) [thetaminus, rminus, gradminus, ~, ~, ~, thetaprime2, gradprime2, logpprime2, nprime2, stopprime2, alphaprime2, nalphaprime2] = ... build_tree(thetaminus, rminus, gradminus, logu, dir, depth-1, epsilon, f, joint0); else [~, ~, ~, thetaplus, rplus, gradplus, thetaprime2, gradprime2, logpprime2, nprime2, stopprime2, alphaprime2, nalphaprime2] = ... build_tree(thetaplus, rplus, gradplus, logu, dir, depth-1, epsilon, f, joint0); end % Choose which subtree to propagate a sample up from. if (rand() < nprime2 / (nprime + nprime2)) thetaprime = thetaprime2; gradprime = gradprime2; logpprime = logpprime2; end % Update the number of valid points. nprime = nprime + nprime2; % Update the stopping criterion. stopprime = stopprime || stopprime2 || stop_criterion(thetaminus, thetaplus, rminus, rplus); % Update the acceptance probability statistics. alphaprime = alphaprime + alphaprime2; nalphaprime = nalphaprime + nalphaprime2; end end end
github
bsxfan/meta-embeddings-master
ReNUTS.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/NUTS-matlab-master/Recycle/ReNUTS.m
10,790
utf_8
916dd2121fbfb133e73fe81c36d2961b
function [theta, re_theta, alpha_ave, nfevals, logp, grad] = ... ReNUTS(f, epsilon, theta0, nsample, logp0, grad0, max_tree_depth) % function [theta, grad, logp, nfevals, alpha_ave] = ... % ReNUTS(f, epsilon, theta0, n_recycle, logp0, grad0, max_tree_depth) % % Carries out one iteration of Recycled No-U-Turn-Sampler. % TODO: Update the documentation to reflect the recycling steps. % % Args: % f - function handle: returns the log probability of the target and % its gradient. % epsilon - double: step size of leap-frog integrator % theta0 - column vector: current state of a Markov chain and the % initial state for the trajectory of Hamiltonian dynamcis. % % Optional args: % logp0 - double: log probability computed at theta0. See the comment on % 'grad0' for more info. % grad0 - column vector: gradient of the log probability computed at % theta0. If both 'grad0' and 'logp0' provided, it will save a bit % (one evaluation of 'f') of computation. The computational gain is % rather small when NUTS requires a long trajectory, so this is an % optional parameter. % max_tree_depth - int % % Returns: % theta - next state of the chain % logp - log probability computed at theta % alpha_ave - average acceptance probability of the states proposed at the % last doubling step of NUTS. It measures of the accuracy of the % numerical approximation of Hamiltonian dynamics and is used to find % an optimal step size value 'epsilon.' % nfevals - the number of log likelihood and gradient evaluations one % iteration of NUTS required % grad - gradient computed at theta (to feed into the next iteration of % NUTS if desired) % Copyright (c) 2011, Matthew D. Hoffman % All rights reserved. % % Copyright (c) 2016, Akihiko Nishimrura, for the portions of the code % relating to the recycling algorithm of Nishimura and Dunson (2015). % All rights reserved. % % Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: % % Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. % Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. global nfevals; nfevals = 0; if nargin < 4 nsample = 0; end if nargin < 6 [logp0, grad0] = f(theta0); nfevals = nfevals + 1; end if nargin < 7 max_tree_depth = 10; end % Resample momenta. r0 = randn(size(theta0)); % Joint log-probability of theta and momenta r. joint = logp0 - 0.5 * (r0' * r0); % Resample u ~ uniform([0, exp(joint)]). % Equivalent to (log(u) - joint) ~ exponential(1). logu = joint - exprnd(1); % Initialize tree. thetaminus = theta0; thetaplus = theta0; rminus = r0; rplus = r0; gradminus = grad0; gradplus = grad0; % Initial height dir = 0. depth = 0; % If all else fails, the next sample is the previous sample. theta = theta0; grad = grad0; logp = logp0; % Initially the only valid point is the initial point. n = 1; % Recyclable samples. re_theta = theta; % Main loop---keep going until the stop criterion is met. stop = false; while ~stop % Choose a direction. -1=backwards, 1=forwards. dir = 2 * (rand() < 0.5) - 1; % Tell 'build_tree' function to store no more states than those that % might be used as an output in the end. Just to save some memory. nsampleprime = ceil(nsample * 2^depth / (n + 2^depth)); % Double the size of the tree. if (dir == -1) [thetaminus, rminus, gradminus, ~, ~, ~, thetaprime, gradprime, logpprime, nprime, stopprime, re_thetaprime, alpha, nalpha] = ... build_tree(thetaminus, rminus, gradminus, logu, dir, depth, epsilon, f, joint, nsampleprime); else [~, ~, ~, thetaplus, rplus, gradplus, thetaprime, gradprime, logpprime, nprime, stopprime, re_thetaprime, alpha, nalpha] = ... build_tree(thetaplus, rplus, gradplus, logu, dir, depth, epsilon, f, joint, nsampleprime); end % Use Metropolis-Hastings to decide whether or not to move to a % point from the half-tree we just generated. if (~ stopprime && (rand() < nprime / n)) theta = thetaprime; logp = logpprime; grad = gradprime; end % Update the collection of recyclable states have been generated so far. if n + nprime <= nsample re_theta = [re_theta, re_thetaprime]; else m = nsample * n / (n + nprime); m = floor(m) + ((m - floor(m)) > rand()); mprime = nsample - m; re_theta = [ ... re_theta(:, randperm(size(re_theta, 2), m)), ... re_thetaprime(:, randperm(size(re_thetaprime, 2), mprime))]; end % Update number of valid points we've seen. n = n + nprime; % Decide if it's time to stop. stop = stopprime || stop_criterion(thetaminus, thetaplus, rminus, rplus); % Increment depth. depth = depth + 1; if depth > max_tree_depth disp('The current NUTS iteration reached the maximum tree depth.') break end end alpha_ave = alpha / nalpha; % Duplicate recyclable samples if not enough of them were generated. if size(re_theta, 2) < nsample nrep = floor(nsample / size(re_theta, 2)); re_theta_extra = re_theta(:, randperm(size(re_theta, 2), nsample - n * nrep)); re_theta = [repmat(re_theta, 1, nrep), re_theta_extra]; end end function [thetaprime, rprime, gradprime, logpprime] = leapfrog(theta, r, grad, epsilon, f) rprime = r + 0.5 * epsilon * grad; thetaprime = theta + epsilon * rprime; [logpprime, gradprime] = f(thetaprime); rprime = rprime + 0.5 * epsilon * gradprime; global nfevals; nfevals = nfevals + 1; end function criterion = stop_criterion(thetaminus, thetaplus, rminus, rplus) thetavec = thetaplus - thetaminus; criterion = (thetavec' * rminus < 0) || (thetavec' * rplus < 0); end % The main recursion. function [thetaminus, rminus, gradminus, thetaplus, rplus, gradplus, thetaprime, gradprime, logpprime, nprime, stopprime, re_thetaprime, alphaprime, nalphaprime] = ... build_tree(theta, r, grad, logu, dir, depth, epsilon, f, joint0, nsampleprime) if (depth == 0) % Base case: Take a single leapfrog step in the direction 'dir'. [thetaprime, rprime, gradprime, logpprime] = leapfrog(theta, r, grad, dir*epsilon, f); joint = logpprime - 0.5 * (rprime' * rprime); % Is the new point in the slice? nprime = logu < joint; if nprime re_thetaprime = thetaprime; else re_thetaprime = []; end % Is the simulation wildly inaccurate? stopprime = logu - 100 >= joint; % Set the return values---minus=plus for all things here, since the % "tree" is of depth 0. thetaminus = thetaprime; thetaplus = thetaprime; rminus = rprime; rplus = rprime; gradminus = gradprime; gradplus = gradprime; % Compute the acceptance probability. alphaprime = exp(logpprime - 0.5 * (rprime' * rprime) - joint0); if isnan(alphaprime) alphaprime = 0; else alphaprime = min(1, alphaprime); end nalphaprime = 1; else % Recursion: Implicitly build the height depth-1 left and right subtrees. [thetaminus, rminus, gradminus, thetaplus, rplus, gradplus, thetaprime, gradprime, logpprime, nprime, stopprime, re_thetaprime, alphaprime, nalphaprime] = ... build_tree(theta, r, grad, logu, dir, depth-1, epsilon, f, joint0, nsampleprime); % No need to keep going if the stopping criteria were met in the first % subtree, and no sample can be recycled if the stopping criteria were % met. if stopprime re_thetaprime = []; nprime = 0; else nsampleprime2 = ceil(nsampleprime * 2^(depth - 1) / (nprime + 2^(depth - 1))); % The maximum number of states we would potentially recycle from the subtree. if (dir == -1) [thetaminus, rminus, gradminus, ~, ~, ~, thetaprime2, gradprime2, logpprime2, nprime2, stopprime2, re_thetaprime2, alphaprime2, nalphaprime2] = ... build_tree(thetaminus, rminus, gradminus, logu, dir, depth-1, epsilon, f, joint0, nsampleprime2); else [~, ~, ~, thetaplus, rplus, gradplus, thetaprime2, gradprime2, logpprime2, nprime2, stopprime2, re_thetaprime2, alphaprime2, nalphaprime2] = ... build_tree(thetaplus, rplus, gradplus, logu, dir, depth-1, epsilon, f, joint0, nsampleprime2); end % Choose which subtree to propagate a sample up from. if (rand() < nprime2 / (nprime + nprime2)) thetaprime = thetaprime2; gradprime = gradprime2; logpprime = logpprime2; end % Update the stopping criterion. stopprime = stopprime || stopprime2 || stop_criterion(thetaminus, thetaplus, rminus, rplus); % Combine the recyclable samples. if stopprime re_thetaprime = []; nprime = 0; else if nprime + nprime2 <= nsampleprime re_thetaprime = [re_thetaprime, re_thetaprime2]; else % No need to keep more recyclable states than the number of samples we % are going to return. mprime = nsampleprime * nprime / (nprime + nprime2); mprime = floor(mprime) + ((mprime - floor(mprime)) > rand()); mprime2 = nsampleprime - mprime; re_thetaprime = [ ... re_thetaprime(:, randperm(size(re_thetaprime, 2), mprime)), ... re_thetaprime2(:, randperm(size(re_thetaprime2, 2), mprime2))]; end % Update the number of valid points. nprime = nprime + nprime2; end % Update the acceptance probability statistics. alphaprime = alphaprime + alphaprime2; nalphaprime = nalphaprime + nalphaprime2; end end end
github
bsxfan/meta-embeddings-master
d2p.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/t-sne/d2p.m
3,155
utf_8
dc48b1dd0688d11671d81af50a0970de
function [P, beta] = d2p(D, u, tol) %D2P Identifies appropriate sigma's to get kk NNs up to some tolerance % % [P, beta] = d2p(D, kk, tol) % % Identifies the required precision (= 1 / variance^2) to obtain a Gaussian % kernel with a certain uncertainty for every datapoint. The desired % uncertainty can be specified through the perplexity u (default = 15). The % desired perplexity is obtained up to some tolerance that can be specified % by tol (default = 1e-4). % The function returns the final Gaussian kernel in P, as well as the % employed precisions per instance in beta. % % % (C) Laurens van der Maaten, 2008 % Maastricht University if ~exist('u', 'var') || isempty(u) u = 15; end if ~exist('tol', 'var') || isempty(tol) tol = 1e-4; end % Initialize some variables n = size(D, 1); % number of instances P = zeros(n, n); % empty probability matrix beta = ones(n, 1); % empty precision vector logU = log(u); % log of perplexity (= entropy) % Run over all datapoints for i=1:n if ~rem(i, 500) disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']); end % Set minimum and maximum values for precision betamin = -Inf; betamax = Inf; % Compute the Gaussian kernel and entropy for the current precision [H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i)); % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while abs(Hdiff) > tol && tries < 50 % If not, increase or decrease precision if Hdiff > 0 betamin = beta(i); if isinf(betamax) beta(i) = beta(i) * 2; else beta(i) = (beta(i) + betamax) / 2; end else betamax = beta(i); if isinf(betamin) beta(i) = beta(i) / 2; else beta(i) = (beta(i) + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(D(i, [1:i - 1, i + 1:end]), beta(i)); Hdiff = H - logU; tries = tries + 1; end % Set the final row of P P(i, [1:i - 1, i + 1:end]) = thisP; end disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]); disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]); disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]); end % Function that computes the Gaussian kernel values given a vector of % squared Euclidean distances, and the precision of the Gaussian kernel. % The function also computes the perplexity of the distribution. function [H, P] = Hbeta(D, beta) P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; % why not: H = exp(-sum(P(P > 1e-5) .* log(P(P > 1e-5)))); ??? P = P / sumP; end
github
bsxfan/meta-embeddings-master
x2p.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/t-sne/x2p.m
3,297
utf_8
e0d6a8b9bcdd6ebd97037e46252fe200
function [P, beta] = x2p(X, u, tol) %X2P Identifies appropriate sigma's to get kk NNs up to some tolerance % % [P, beta] = x2p(xx, kk, tol) % % Identifies the required precision (= 1 / variance^2) to obtain a Gaussian % kernel with a certain uncertainty for every datapoint. The desired % uncertainty can be specified through the perplexity u (default = 15). The % desired perplexity is obtained up to some tolerance that can be specified % by tol (default = 1e-4). % The function returns the final Gaussian kernel in P, as well as the % employed precisions per instance in beta. % % % (C) Laurens van der Maaten, 2008 % Maastricht University if ~exist('u', 'var') || isempty(u) u = 15; end if ~exist('tol', 'var') || isempty(tol) tol = 1e-4; end % Initialize some variables n = size(X, 1); % number of instances P = zeros(n, n); % empty probability matrix beta = ones(n, 1); % empty precision vector logU = log(u); % log of perplexity (= entropy) % Compute pairwise distances disp('Computing pairwise distances...'); sum_X = sum(X .^ 2, 2); D = bsxfun(@plus, sum_X, bsxfun(@plus, sum_X', -2 * X * X')); % Run over all datapoints disp('Computing P-values...'); for i=1:n if ~rem(i, 500) disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']); end % Set minimum and maximum values for precision betamin = -Inf; betamax = Inf; % Compute the Gaussian kernel and entropy for the current precision Di = D(i, [1:i-1 i+1:end]); [H, thisP] = Hbeta(Di, beta(i)); % Evaluate whether the perplexity is within tolerance Hdiff = H - logU; tries = 0; while abs(Hdiff) > tol && tries < 50 % If not, increase or decrease precision if Hdiff > 0 betamin = beta(i); if isinf(betamax) beta(i) = beta(i) * 2; else beta(i) = (beta(i) + betamax) / 2; end else betamax = beta(i); if isinf(betamin) beta(i) = beta(i) / 2; else beta(i) = (beta(i) + betamin) / 2; end end % Recompute the values [H, thisP] = Hbeta(Di, beta(i)); Hdiff = H - logU; tries = tries + 1; end % Set the final row of P P(i, [1:i - 1, i + 1:end]) = thisP; end disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]); disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]); disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]); end % Function that computes the Gaussian kernel values given a vector of % squared Euclidean distances, and the precision of the Gaussian kernel. % The function also computes the perplexity of the distribution. function [H, P] = Hbeta(D, beta) P = exp(-D * beta); sumP = sum(P); H = log(sumP) + beta * sum(D .* P) / sumP; P = P / sumP; end
github
bsxfan/meta-embeddings-master
create_PYCRP.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/CRP/create_PYCRP.m
13,438
utf_8
97417297bf1d08ceaa6be2bbfe82c2bb
function PYCRP = create_PYCRP(alpha,beta,e,n) % alpha: alpha>=0, concentration % beta: 0<= beta <=1, discount if nargin==0 %test_this2(); test_Gibbsmatrix() return; end if nargin==4 PYCRP = create_PYCRP(1,0); PYCRP.set_expected_number_tables(e,n,alpha,beta); return; else assert(nargin==2); end assert(alpha>=0); assert(beta>=0 && beta<=1); PYCRP.logprob = @logprob; PYCRP.logprob3 = @logprob3; PYCRP.sample = @sample; PYCRP.expected_number_tables = @expected_number_tables; PYCRP.set_expected_number_tables = @set_expected_number_tables; PYCRP.ent = @ent; PYCRP.getParams = @getParams; PYCRP.GibbsMatrix = @GibbsMatrix; PYCRP.slowGibbsMatrix = @slowGibbsMatrix; PYCRP.merge = @merge; PYCRP.merge_all_pairs = @merge_all_pairs; function [concentration,discount] = getParams() concentration = alpha; discount = beta; end function e = expected_number_tables(n) e = ent(alpha,beta,n); end function e = ent(alpha,beta,n) if alpha==0 && beta==0 e = 1; elseif isinf(alpha) e = n; elseif alpha>0 && beta>0 A = gammaln(alpha + beta + n) + gammaln(alpha + 1) ... - log(beta) - gammaln(alpha+n) - gammaln(alpha+beta); B = alpha/beta; e = B*expm1(A-log(B)); %exp(A)-B elseif alpha>0 && beta==0 e = alpha.*( psi(n+alpha) - psi(alpha) ); elseif alpha==0 && beta>0 A = gammaln(beta + n) - log(beta) - gammaln(n) - gammaln(beta); e = exp(A); end end function [flag,concentration,discount] = set_expected_number_tables(e,n,concentration,discount) if ~isempty(concentration) && ~isempty(discount) error('you can''t specify both parameters'); end if isempty(concentration) && isempty(discount) error('you must specify one parameter'); end if e<1 || e>n error('expectation must be between 1 and %i',n); end if isempty(concentration) assert(discount>=0 && discount<1); beta = discount; if beta==0 && e==1 alpha = 0; concentration = alpha; flag = 1; return; elseif e==n alpha = inf; concentration = alpha; flag = 1; return; end min_e = ent(0,beta,n); if e < min_e error('e=%g is impossible at discount=%g, minimum is e=%g',e,beta,min_e); end f = @(logalpha) ent(exp(logalpha),beta,n) - e; [logalpha,~,flag] = fzero(f,0); alpha = exp(logalpha); concentration = alpha; elseif isempty(discount) assert(concentration>=0); alpha = concentration; if alpha==0 && e==1 beta = 0; discount = beta; flag = 1; return; elseif e==n beta = 1; discount = beta; flag = 1; return; end min_e = ent(alpha,0,n); if e < min_e error('e=%g is impossible at concentration=%g, minimum is e=%min_e',e,alpha,min_e); end f = @(logitbeta) ent(alpha,sigmoid(logitbeta),n) - e; [logitbeta,~,flag] = fzero(f,0); beta = sigmoid(logitbeta); discount = beta; end end function y = sigmoid(x) y = 1./(1+exp(-x)); end function deltalogP = merge(i,j,counts) if i==j % no merge deltalogP = 0; return; end if isinf(alpha) || (beta==1) || (alpha==0 && beta==0) error('degenerate cases not handled'); end K = length(counts); T = sum(counts); if alpha>0 && beta>0 deltalogP = gammaln(counts(i) + counts(j) - beta) ... - gammaln(counts(i) - beta) - gammaln(counts(j) - beta) ... - log(beta) + gammaln(1-beta) ... - log(alpha/beta + K-1); elseif beta==0 && alpha>0 deltalogP = -log(alpha) + gammaln(counts(i)+counts(j)) ... - gammaln(counts(i)) - gammaln(counts(j)); elseif alpha==0 && beta>0 deltalogP = -log(beta) -log(K-1) + gammaln(1-beta) ... - gammaln(counts(i) - beta) - gammaln(counts(j) - beta) ... + gammaln(counts(i) + counts(j) - beta); end end function Y = mergeConst(K) if isinf(alpha) || (beta==1) || (alpha==0 && beta==0) error('degenerate cases not handled'); end if alpha>0 && beta>0 %Y = K*log(beta) + gammaln(alpha/beta + K) - K*gammaln(1-beta); Y = log(beta) + log(alpha/beta + K-1) - gammaln(1-beta); elseif beta==0 && alpha>0 %Y = K*log(alpha); Y = log(alpha); elseif beta>0 && alpha==0 %Y = (K-1)*log(beta) + gammaln(K) - K*gammaln(1-beta); Y = log(beta) + log(K-1) - gammaln(1-beta); end end %vectorization helps a lot (loopy version below is much slower) function deltalogP = merge_all_pairs(counts) K = length(counts); delta = counts-beta; gammalndelta = gammaln(delta); deltaC = mergeConst(K);%-mergeConst(K-1); oldlogP = bsxfun(@plus,gammalndelta+deltaC,gammalndelta.'); deltalogP = gammaln(bsxfun(@plus,counts-beta,counts.')) - oldlogP; deltalogP(1:K+1:end) = 0; end %loopy version is much, much slower % function deltalogP = merge_all_pairs2(counts) % K = length(counts); % delta = counts-beta; % gammalndelta = gammaln(delta); % deltaC = mergeConst(K-1)-mergeConst(K); % deltalogP = zeros(K,K); % for i=1:K-1 % for j=i+1:K % deltalogP(i,j) = deltaC + gammaln(delta(i)+counts(j)) - gammalndelta(i) - gammalndelta(j); % end % end % end function logP = logprob(counts) %Wikipedia K = length(counts); T = sum(counts); if isinf(alpha) && beta==1 %singleton tables if all(counts==1) logP = 0; else logP = -inf; end return; end if alpha==0 && beta==0 %single table if K==1 logP = 0; else logP = -inf; end return; end if alpha>0 && beta>0 % 2-param Pitman-Yor generalization logP = gammaln(alpha) - gammaln(alpha+T) + K*log(beta) ... + gammaln(alpha/beta + K) - gammaln(alpha/beta) ... + sum(gammaln(counts-beta)) ... - K*gammaln(1-beta); elseif beta==0 && alpha>0 % classical CRP logP = gammaln(alpha) + K*log(alpha) - gammaln(alpha+T) + sum(gammaln(counts)); elseif beta>0 && alpha==0 logP = (K-1)*log(beta) + gammaln(K) - gammaln(T) ... - K*gammaln(1-beta) + sum(gammaln(counts-beta)); end end % Seems wrong % function logP = logprob2(counts) % Goldwater % % % % K = length(counts); % T = sum(counts); % if beta>0 %Pitman-Yor generalization % logP = gammaln(1+alpha) - gammaln(alpha+T) ... % + sum(beta*(1:K-1)+alpha) ... % + sum(gammaln(counts-beta)) ... % - K*gammaln(1-beta); % else %1 parameter CRP % logP = gammaln(1+alpha) + (K-1)*log(alpha) - gammaln(alpha+T) + sum(gammaln(counts)); % end % % end % Agrees with Wikipedia version (faster for small counts) function logP = logprob3(counts) logP = 0; n = 0; for k=1:length(counts) % seat first customer at new table if k>1 logP = logP +log((alpha+(k-1)*beta)/(n+alpha)); end n = n + 1; % seat the rest at this table for i = 2:counts(k) logP = logP + log((i-1-beta)/(n+alpha)); n = n + 1; end end end % GibbsMatrix. Computes matrix of conditional log-probabilities % suitable for Gibbs sampling, or pseudolikelihood calculation. % Input: % labels: n-vector, maps each of n customers to a table in 1..m % Output: % logP: (m+1)-by-n matrix of **unnormalized** log-probabilities % logP(i,j) = log P(customer j at table i | seating of all others) + const % table m+1 is a new table function [logP,empties] = GibbsMatrix(labels) m = max(labels); n = length(labels); blocks = sparse(labels,1:n,true); counts = full(sum(blocks,2)); %original table sizes logP = repmat(log([counts-beta;alpha+m*beta]),1,n); %most common values for every row %return; empties = false(1,n); %new empty table when customer j removed for i=1:m cmin = counts(i) - 1; tar = blocks(i,:); if cmin==0 %table empty logP(i,tar) = log(alpha + (m-1)*beta); empties(tar) = true; else logP(i,tar) = log(cmin-beta); end end logP(m+1,empties) = -inf; end function logP = slowGibbsMatrix(labels) m = max(labels); n = length(labels); blocks = sparse(labels,1:n,true,m+1,n); counts = full(sum(blocks,2)); %original table sizes logP = zeros(m+1,n); for j=1:n cj = counts; tj = labels(j); cj(tj) = cj(tj) - 1; nz = cj>0; k = sum(nz); if k==m logP(nz,j) = log(cj(nz) - beta); logP(m+1,j) = log(alpha + m*beta); else %new empty table logP(nz,j) = log(cj(nz) - beta); logP(tj,j) = log(alpha + k*beta); logP(m+1,j) = -inf; end end end function [labels,counts] = sample(T) labels = zeros(1,T); counts = zeros(1,T); labels(1) = 1; K = 1; %number of classes counts(1) = 1; for i=2:T p = zeros(K+1,1); p(1:K) = counts(1:K) - beta; p(K+1) = alpha + K*beta; [~,k] = max(randgumbel(K+1,1) + log(p)); labels(i) = k; if k>K K = K + 1; assert(k==K); counts(k) = 1; else counts(k) = counts(k) + 1; end end counts = counts(1:K); labels = labels(randperm(T)); end end function test_this2() T = 20; e = 10; N = 1000; crp1 = create_PYCRP(0,[],e,T); [concentration,discount] = crp1.getParams() crp2 = create_PYCRP([],0,e,T); [concentration,discount] = crp2.getParams() K1 = zeros(1,T); K2 = zeros(1,T); for i=1:N [~,counts] = crp1.sample(T); K = length(counts); K1(K) = K1(K) + 1; [~,counts] = crp2.sample(T); K = length(counts); K2(K) = K2(K) + 1; end e1 = sum((1:T).*K1)/N e2 = sum((1:T).*K2)/N close all; subplot(2,1,1);bar(1:T,K1); subplot(2,1,2);bar(1:T,K2); K1 = K1/sum(K1); K2 = K2/sum(K2); %dlmwrite('K1.table',[(1:T)',K1'],' '); %dlmwrite('K2.table',[(1:T)',K2'],' '); for i=1:T fprintf('(%i,%6.4f) ',2*i-1,K1(i)) end fprintf('\n'); for i=1:T fprintf('(%i,%6.4f) ',2*i,K2(i)) end fprintf('\n'); end function test_Gibbsmatrix() alpha = randn^2; beta = rand; PYCRP = create_PYCRP(alpha,beta); labels = [1 1 1 2 1 3 4 4] logP = exp(PYCRP.slowGibbsMatrix(labels)) logP = exp(PYCRP.GibbsMatrix(labels)) end function test_this() alpha1 = 0.0; beta1 = 0.6; crp1 = create_PYCRP(alpha1,beta1); alpha2 = 0.1; beta2 = 0.6; crp2 = create_PYCRP(alpha2,beta2); close all; figure; hold; for i=1:100; L1 = crp1.sample(100); L2 = crp2.sample(100); C1=full(sum(int2onehot(L1),2)); C2=full(sum(int2onehot(L2),2)); x11 = crp1.logprob(C1); x12 = crp2.logprob3(C1); x22 = crp2.logprob3(C2); x21 = crp1.logprob(C2); plot(x11,x12,'.g'); plot(x21,x22,'.b'); end figure;hold; crp = crp1; for i=1:100; L1 = crp.sample(100); C1=full(sum(int2onehot(L1),2)); x = crp.logprob(C1); y = crp.logprob3(C1); plot(x,y); end end
github
bsxfan/meta-embeddings-master
trandn.m
.m
meta-embeddings-master/code/Niko/matlab/fous-y-tout/dpmm/trunc_gaussian/trandn.m
3,445
utf_8
319949967a84b816a6cc4d0b882c4c98
function x=trandn(l,u) %% truncated normal generator % * efficient generator of a vector of length(l)=length(u) % from the standard multivariate normal distribution, % truncated over the region [l,u]; % infinite values for 'u' and 'l' are accepted; % * Remark: % If you wish to simulate a random variable % 'Z' from the non-standard Gaussian N(m,s^2) % conditional on l<Z<u, then first simulate % X=trandn((l-m)/s,(u-m)/s) and set Z=m+s*X; % Reference: % Botev, Z. I. (2016). "The normal law under linear restrictions: % simulation and estimation via minimax tilting". Journal of the % Royal Statistical Society: Series B (Statistical Methodology). % doi:10.1111/rssb.12162 l=l(:);u=u(:); % make 'l' and 'u' column vectors if length(l)~=length(u) error('Truncation limits have to be vectors of the same length') end x=nan(size(l)); a=.66; % treshold for switching between methods % threshold can be tuned for maximum speed for each Matlab version % three cases to consider: % case 1: a<l<u I=l>a; if any(I) tl=l(I); tu=u(I); x(I)=ntail(tl,tu); end % case 2: l<u<-a J=u<-a; if any(J) tl=-u(J); tu=-l(J); x(J)=-ntail(tl,tu); end % case 3: otherwise use inverse transform or accept-reject I=~(I|J); if any(I) tl=l(I); tu=u(I); x(I)=tn(tl,tu); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x=ntail(l,u) % samples a column vector of length=length(l)=length(u) % from the standard multivariate normal distribution, % truncated over the region [l,u], where l>0 and % l and u are column vectors; % uses acceptance-rejection from Rayleigh distr. % similar to Marsaglia (1964); c=l.^2/2; n=length(l); f=expm1(c-u.^2/2); x=c-reallog(1+rand(n,1).*f); % sample using Rayleigh % keep list of rejected I=find(rand(n,1).^2.*x>c); d=length(I); while d>0 % while there are rejections cy=c(I); % find the thresholds of rejected y=cy-reallog(1+rand(d,1).*f(I)); idx=rand(d,1).^2.*y<cy; % accepted x(I(idx))=y(idx); % store the accepted I=I(~idx); % remove accepted from list d=length(I); % number of rejected end x=sqrt(2*x); % this Rayleigh transform can be delayed till the end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x=tn(l,u) % samples a column vector of length=length(l)=length(u) % from the standard multivariate normal distribution, % truncated over the region [l,u], where -a<l<u<a for some % 'a' and l and u are column vectors; % uses acceptance rejection and inverse-transform method; tol=2; % controls switch between methods % threshold can be tuned for maximum speed for each platform % case: abs(u-l)>tol, uses accept-reject from randn I=abs(u-l)>tol; x=l; if any(I) tl=l(I); tu=u(I); x(I)=trnd(tl,tu); end % case: abs(u-l)<tol, uses inverse-transform I=~I; if any(I) tl=l(I); tu=u(I); pl=erfc(tl/sqrt(2))/2; pu=erfc(tu/sqrt(2))/2; x(I)=sqrt(2)*erfcinv(2*(pl-(pl-pu).*rand(size(tl)))); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x=trnd(l,u) % uses acceptance rejection to simulate from truncated normal x=randn(size(l)); % sample normal % keep list of rejected I=find(x<l|x>u); d=length(I); while d>0 % while there are rejections ly=l(I); % find the thresholds of rejected uy=u(I); y=randn(size(ly)); idx=y>ly&y<uy; % accepted x(I(idx))=y(idx); % store the accepted I=I(~idx); % remove accepted from list d=length(I); % number of rejected end end
github
bsxfan/meta-embeddings-master
VB4HTPLDA_iteration.m
.m
meta-embeddings-master/code/Niko/matlab/clean/VB4HTPLDA/VB4HTPLDA_iteration.m
4,532
utf_8
3639a9571c692326b5102546e66240c3
function [F,W,obj] = VB4HTPLDA_iteration(nu,F,W,R,labels,weights) % Iteration of VB algorithm for HT-PLDA training. See HTPLDA_SGME_train_VB() % for details. The model parameters F and W are updated. % % Inputs: % nu: scalar, df > 0 (nu=inf is allowed: it signals G-PLDA) % F: D-by-d factor loading matrix, D > d % W: within-speaker precision, D-by-D, pos. def, % R: D-by-N i-vector data matrix (centered) % labels: M-by-N, one hot columns, labels for M speakers and N i-vectors % This is a large matrix and it is best represented as a sparse % logical matrix. if nargin==0 test_this; return; end scaling_mindiv = true; Z_mindiv = true; [D,d] = size(F); [M,N] = size(labels); % E-step P = F.'*W; % d-by-D B0 = P*F; % d-by-d common precision (up to scaling) [V,L] = eig(B0); % eigendecomposition B0 = V*L*V'; L is diagonal, V is orthonormal L = diag(L); VP = V.'*P; if isinf(nu) b = ones(1,N); else %G = W - P.'*(B0\P); G = W - VP.'*bsxfun(@ldivide,L,VP); % inv(B0) = V*inv(L)*V' q = sum(R.*(G*R),1); b = (nu+D-d)./(nu+q); %scaling %1-by-N end if exist('weights','var') && ~isempty(weights) b = b.*weights; end bR = bsxfun(@times,b,R); S = bR*R.'; % D-by-D weighted 2nd-order stats f = bR*labels.'; % D-by-M weighted 1st-order stats n = b*labels.'; % 1-by-M weighted 0-order stats tot_n = sum(n); logLPP = log1p(bsxfun(@times,n,L)); % d-by-M log eigenvalues of posterior precisions LPC = exp(-logLPP); % d-by-M eigenvalues of posterior covariances logdetPP = sum(logLPP,1); % logdets of posterior precisions tracePC = sum(LPC,1); % and the traces Z = V*(LPC.*(VP*f)); % d-by-M posterior means T = Z*f.'; % d-by-D R = bsxfun(@times,n,Z)*Z.' + V*bsxfun(@times,LPC*n(:),V.'); C = ( Z*Z.' + V*bsxfun(@times,sum(LPC,2),V.') ) / M; logdetW = 2*sum(log(diag(chol(W)))); logLH = (N/2)*logdetW + (D/2)*sum(log(b)) - 0.5*trprod(W,S) ... + trprod(T,P) -0.5*trprod(B0,R); if isinf(nu) obj = logLH - KLGauss(logdetPP,tracePC,Z); else obj = logLH - KLGauss(logdetPP,tracePC,Z) - KLgamma(nu,D,d,b); end % M-step F = T.'/R; FT = F*T; if scaling_mindiv && true W = inv((S - (FT+FT.')/2)/tot_n); else W = inv((S - (FT+FT.')/2)/N); end CC = chol(C)'; fprintf(' cov(z): trace = %g, logdet = %g\n',trace(C),2*sum(log(diag(CC)))); if Z_mindiv F = F*CC; end; end function y = trprod(A,B) y = A(:).'*B(:); end function kl = KLGauss(logdets,traces,Means) d = size(Means,1); M = length(logdets); kl = ( sum(traces) - sum(logdets) + trprod(Means,Means) - d*M)/2; end function kl = KLgamma(nu,D,d,lambdahat) % prior has expected value a0/b0 = 1 a0 = nu/2; b0 = nu/2; %Posterior a = (nu + D - d) / 2; b = a ./ lambdahat; %This value for a is a thumbsuck: mean-field VB gives instead a =(nu+D)/2, %while b is chosen to give lambdahat = a/b. %This gives a larger variance (a/b^2) than the mean-field would, which %is probbaly a good thing, since mean-field is known to underestimate variances. kl = sum(gammaln(a0) - gammaln(a) + a0*log(b/b0) + psi(a)*(a-a0) + a*(b0-b)./b); end function test_this() d = 2; D = 20; %required: xdim > zdim nu = 3; %required: nu >= 1, integer, DF fscal = 3; %increase fscal to move speakers apart F0 = randn(D,d)*fscal; W0 = randn(D,D+1); W0 = W0*W0.'; % HTPLDA = create_HTPLDA_extractor(F,nu,W); % [Pg,Hg,dg] = HTPLDA.getPHd(); N = 5000; em = N/10; %prior = create_PYCRP(0,[],em,n); prior = create_PYCRP([],0,em,N); [R,Z,precisions,labels] = sample_HTPLDA_database(nu,F0,prior,N,W0); M = max(labels); labels = sparse(labels,1:N,true,M,N); F = randn(D,d); W = eye(D); niters = 100; y = zeros(1,niters); for i=1:niters [F,W,obj] = VB4HTPLDA_iteration(nu,F,W,R,labels); fprintf('%i: %g\n',i,obj); y(i) = obj; end plot(y); end
github
bsxfan/meta-embeddings-master
VB4HTPLDA_iteration_2.m
.m
meta-embeddings-master/code/Niko/matlab/clean/VB4HTPLDA/VB4HTPLDA_iteration_2.m
4,534
utf_8
50e11eb8be6844dbc9c70f60f49c3c23
function [F,W,obj] = VB4HTPLDA_iteration_2(nu,F,W,R,labels,weights) % Iteration of VB algorithm for HT-PLDA training. See HTPLDA_SGME_train_VB() % for details. The model parameters F and W are updated. % % Inputs: % nu: scalar, df > 0 (nu=inf is allowed: it signals G-PLDA) % F: D-by-d factor loading matrix, D > d % W: within-speaker precision, D-by-D, pos. def, % R: D-by-N i-vector data matrix (centered) % labels: M-by-N, one hot columns, labels for M speakers and N i-vectors % This is a large matrix and it is best represented as a sparse % logical matrix. if nargin==0 test_this; return; end scaling_mindiv = true; Z_mindiv = true; [D,d] = size(F); [M,N] = size(labels); % E-step P = F.'*W; % d-by-D B0 = P*F; % d-by-d common precision (up to scaling) [V,L] = eig(B0); % eigendecomposition B0 = V*L*V'; L is diagonal, V is orthonormal L = diag(L); VP = V.'*P; if isinf(nu) b = ones(1,N); else %G = W - P.'*(B0\P); G = W - VP.'*bsxfun(@ldivide,L,VP); % inv(B0) = V*inv(L)*V' q = sum(R.*(G*R),1); b = (nu+D-d)./(nu+q); %scaling %1-by-N end if exist('weights','var') && ~isempty(weights) b = b.*weights; end bR = bsxfun(@times,b,R); S = bR*R.'; % D-by-D weighted 2nd-order stats f = bR*labels.'; % D-by-M weighted 1st-order stats n = b*labels.'; % 1-by-M weighted 0-order stats tot_n = sum(n); logLPP = log1p(bsxfun(@times,n,L)); % d-by-M log eigenvalues of posterior precisions LPC = exp(-logLPP); % d-by-M eigenvalues of posterior covariances tracePC = sum(LPC,1); % and the traces logdetPP = sum(logLPP,1); % logdets of posterior precisions Z = V*(LPC.*(VP*f)); % d-by-M posterior means T = Z*f.'; % d-by-D R = bsxfun(@times,n,Z)*Z.' + V*bsxfun(@times,LPC*n(:),V.'); C = ( Z*Z.' + V*bsxfun(@times,sum(LPC,2),V.') ) / M; logdetW = 2*sum(log(diag(chol(W)))); logLH = (N/2)*logdetW + (D/2)*sum(log(b)) - 0.5*trprod(W,S) ... + trprod(T,P) -0.5*trprod(B0,R); if isinf(nu) obj = logLH - KLGauss(logdetPP,tracePC,Z); else obj = logLH - KLGauss(logdetPP,tracePC,Z) - KLgamma(nu,D,d,b); end % M-step F = T.'/R; FT = F*T; if scaling_mindiv && true W = inv((S - (FT+FT.')/2)/tot_n); else W = inv((S - (FT+FT.')/2)/N); end CC = chol(C)'; fprintf(' cov(z): trace = %g, logdet = %g\n',trace(C),2*sum(log(diag(CC)))); if Z_mindiv F = F*CC; end; end function y = trprod(A,B) y = A(:).'*B(:); end function kl = KLGauss(logdets,traces,Means) d = size(Means,1); M = length(logdets); kl = ( sum(traces) - sum(logdets) + trprod(Means,Means) - d*M)/2; end function kl = KLgamma(nu,D,d,lambdahat) % prior has expected value a0/b0 = 1 a0 = nu/2; b0 = nu/2; %Posterior a = (nu + D - d) / 2; b = a ./ lambdahat; %This value for a is a thumbsuck: mean-field VB gives instead a =(nu+D)/2, %while b is chosen to give lambdahat = a/b. %This gives a larger variance (a/b^2) than the mean-field would, which %is probbaly a good thing, since mean-field is known to underestimate variances. kl = sum(gammaln(a0) - gammaln(a) + a0*log(b/b0) + psi(a)*(a-a0) + a*(b0-b)./b); end function test_this() d = 2; D = 20; %required: xdim > zdim nu = 3; %required: nu >= 1, integer, DF fscal = 3; %increase fscal to move speakers apart F0 = randn(D,d)*fscal; W0 = randn(D,D+1); W0 = W0*W0.'; % HTPLDA = create_HTPLDA_extractor(F,nu,W); % [Pg,Hg,dg] = HTPLDA.getPHd(); N = 5000; em = N/10; %prior = create_PYCRP(0,[],em,n); prior = create_PYCRP([],0,em,N); [R,Z,precisions,labels] = sample_HTPLDA_database(nu,F0,prior,N,W0); M = max(labels); labels = sparse(labels,1:N,true,M,N); F = randn(D,d); W = eye(D); niters = 100; y = zeros(1,niters); for i=1:niters [F,W,obj] = VB4HTPLDA_iteration(nu,F,W,R,labels); fprintf('%i: %g\n',i,obj); y(i) = obj; end plot(y); end
github
bsxfan/meta-embeddings-master
VB4HTPLDA_demo.m
.m
meta-embeddings-master/code/Niko/matlab/clean/VB4HTPLDA/VB4HTPLDA_demo.m
7,965
utf_8
52ba6282c157b56dd41335179ade4206
function VB4HTPLDA_demo % Demo and test code for VB training and SGME scoring of HT-PLDA model. % % Training and evaluation data are (independently) sampled from a model with % randomly generated data. A VB algorithm is used to estimate the parameters % of this model from the training data. The accuracy of the trained (VB) % model is compared (on both train and evaluation data) against the % (oracle) model that generated the data. % % The accuracy is given in terms of the calibration-sensitive binary cross % entropy (BXE) and (if available) also equal-error-rate EER. % % If the BOSARIS Toolkit (https://sites.google.com/site/bosaristoolkit/) is % available, BXE is shown not only for the 'raw' scores as given by this % model, but also for PAV-recalibrated scores, to give 'minBXE'. The latter % is what BXE could have been if calibration had been ideal. % Assemble model to generate data big = false; if ~big zdim = 2; %speaker identity variable size rdim = 20; %i-vector size. required: rdim > zdim nu = 3; %required: nu >= 1, integer, degrees of freedom for heavy-tailed channel noise fscal = 3; %increase fscal to move speakers apart else zdim = 100; %speaker identity variable size rdim = 512; %i-vector size. required: rdim > zdim nu = 3; %required: nu >= 1, integer, degrees of freedom for heavy-tailed channel noise fscal = 1/20; %increase fscal to move speakers apart end F = randn(rdim,zdim)*fscal; W = randn(rdim,2*rdim); W = W*W.';W = (rdim/trace(W))*W; model1 = create_HTPLDA_SGME_backend(nu,F,W); %oracle model %Generate synthetic labels nspeakers = 10000; recordings_per_speaker = 10; N = nspeakers*recordings_per_speaker; ilabels = repmat(1:nspeakers,recordings_per_speaker,1); ilabels = ilabels(:).'; % integer speaker labels hlabels = sparse(ilabels,1:N,true,nspeakers,N); %speaker label matrix with one-hot columns %and some training data Z = randn(zdim,nspeakers); Train = F*Z*hlabels + sample_HTnoise(nu,rdim,N,W); %train fprintf('*** Training on %i i-vectors of %i speakers ***\n',N,nspeakers); niters = 50; % Weights can be used to change relative importance of subsets of the training data % weights = 1 + rand(1,N); %In practice, obviously not like this! This is just a quick and dirty test. % [model2,obj] = HTPLDA_SGME_train_VB(Train,hlabels,nu,zdim,niters,[],[],weights); [model2,obj] = HTPLDA_SGME_train_VB(Train,hlabels,nu,zdim,niters); close all; plot(obj);title('VB lower bound'); [model3,obj3] = HTPLDA_SGME_train_VB(Train,hlabels,nu*10,zdim,niters); [model4,obj4] = HTPLDA_SGME_train_VB(Train,hlabels,nu/10,zdim,niters); [~,~,oracle_obj] = VB4HTPLDA_iteration(nu,F,W,Train,hlabels); fprintf('\n\nfinal train objective: %g\n',obj(end)); fprintf('nu*10 train objective: %g\n',obj3(end)); fprintf('nu/10 train objective: %g\n',obj4(end)); fprintf('oracle objective: %g\n',oracle_obj); fprintf('delta : %g\n',obj(end)-oracle_obj); %and some new validation data Zv = randn(zdim,nspeakers); Validation = F*Zv*hlabels + sample_HTnoise(nu,rdim,N,W); [~,~,oracle_val_obj] = VB4HTPLDA_iteration(nu,F,W,Validation,hlabels); [~,F2,W2] = model2.getParams(); [~,~,val_obj] = VB4HTPLDA_iteration(nu,F2,W2,Validation,hlabels); fprintf('\nvalidation objective: %g\n',val_obj); fprintf('oracle val. objective: %g\n',oracle_val_obj); fprintf('delta : %g\n',val_obj-oracle_val_obj); %Generate independent evaluation data with new speakers nspeakers = 300; %Generate target speakers ntar = nspeakers; Ztar = randn(zdim,ntar); %and some single enrollment data for them Enroll1 = F*Ztar + sample_HTnoise(nu,rdim,ntar,W); %1 enrollment / speaker %and some double enrollments ne = 2; Flags = repmat(1:ntar,ne,1); Flags = sparse(Flags(:),1:ne*ntar,true,ntar,ne*ntar); Enroll2 = F*Ztar*Flags + sample_HTnoise(nu,rdim,ne*ntar,W); %2 enrollments / speaker %and some test data recordings_per_speaker = 10; N = nspeakers*recordings_per_speaker; ilabels = repmat(1:nspeakers,recordings_per_speaker,1); ilabels = ilabels(:).'; % integer speaker labels hlabels = sparse(ilabels,1:N,true,nspeakers,N); %speaker label matrix with one-hot columns Test = F*Ztar*hlabels + sample_HTnoise(nu,rdim,N,W); fprintf('\n\n*** Evaluation on %i target speakers with single/double enrollments and %i test recordings ***\n',nspeakers,N); useBOSARIS = exist('opt_loglr','file'); if useBOSARIS fprintf(' minBXE in brackets\n') BXE = zeros(2,2); minBXE = zeros(2,2); EER = zeros(2,2); Scores = model1.score_trials(Enroll1,[],Test); [BXE(1,1),minBXE(1,1),EER(1,1)] = calcBXE(Scores,hlabels); Scores = model1.score_trials(Enroll2,Flags,Test); [BXE(1,2),minBXE(1,2),EER(1,2)] = calcBXE(Scores,hlabels); Scores = model2.score_trials(Enroll1,[],Test); [BXE(2,1),minBXE(2,1),EER(2,1)] = calcBXE(Scores,hlabels); Scores = model2.score_trials(Enroll2,Flags,Test); [BXE(2,2),minBXE(2,2),EER(2,2)] = calcBXE(Scores,hlabels); fprintf('oracle: single enroll BXE = %g (%g), double enroll BXE = %g (%g)\n',BXE(1,1),minBXE(1,1),BXE(1,2),minBXE(1,2)); fprintf('VB : single enroll BXE = %g (%g), double enroll BXE = %g (%g)\n',BXE(2,1),minBXE(2,1),BXE(2,2),minBXE(2,2)); fprintf('oracle: single enroll EER = %g, double enroll EER = %g\n',EER(1,1),EER(1,2)); fprintf('VB : single enroll EER = %g, double enroll EER = %g\n',EER(2,1),EER(2,2)); else % no BOSARIS tic BXE = zeros(2,2); Scores = model1.score_trials(Enroll1,[],Test); BXE(1,1) = calcBXE(Scores,hlabels); Scores = model1.score_trials(Enroll2,Flags,Test); BXE(1,2) = calcBXE(Scores,hlabels); Scores = model2.score_trials(Enroll1,[],Test); BXE(2,1) = calcBXE(Scores,hlabels); Scores = model2.score_trials(Enroll2,Flags,Test); BXE(2,2) = calcBXE(Scores,hlabels); toc fprintf('oracle: single enroll BXE = %g, double enroll BXE = %g\n',BXE(1,1),BXE(1,2)); fprintf('VB : single enroll BXE = %g, double enroll BXE = %g\n',BXE(2,1),BXE(2,2)); end end function [bxe,min_bxe,EER] = calcBXE(Scores,labels) % Binary cross-entropy, with operating point at target prior at true % proportion, normalized so that llr = 0 gives bxe = 1. tar = Scores(labels); non = Scores(~labels); %ofs = log(length(tar)) - log(length(non)); %bxe = mean([softplus(-tar - ofs).',softplus(non + ofs).']) / log(2); bxe = ( mean(softplus(-tar)) + mean(softplus(non)) ) / (2*log(2)); %ofs = 0 if nargout>=2 [tar,non] = opt_loglr(tar.',non.','raw'); tar = tar'; non = non.'; min_bxe = ( mean(softplus(-tar)) + mean(softplus(non)) ) / (2*log(2)); end if nargout >=3 EER = eer(tar,non); end end function y = softplus(x) % y = log(1+exp(x)); y = x; f = find(x<30); y(f) = log1p(exp(x(f))); end function X = sample_HTnoise(nu,dim,n,W) % Sample n heavy-tailed dim-dimensional variables. (Only for integer nu.) % % Inputs: % nu: integer nu >=1, degrees of freedom of resulting t-distribution % n: number of samples % W: precision matrix for T-distribution % % Output: % X: dim-by-n samples cholW = chol(W); if isinf(nu) precisions = ones(1,n); else precisions = mean(randn(nu,n).^2,1); end std = 1./sqrt(precisions); X = cholW\bsxfun(@times,std,randn(dim,n)); end
github
bsxfan/meta-embeddings-master
MLNDA_MAP_obj.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/MLNDA_MAP_obj.m
1,526
utf_8
c25e0cb0548424de1497aa4331334429
function [y,back] = MLNDA_MAP_obj(newData,newLabels,oldData,oldLabels,oldWeight,F,W,fi,params,nu) if nargin==0 test_this(); return; end ht = exist('nu','var') && ~isempty(nu) && ~isinf(nu); [newR,logdetJnew,back1] = fi(params,newData); [oldR,logdetJold,back3] = fi(params,oldData); if ht [newllh,back2] = htplda_llh(newR,newLabels,F,W,nu); [oldllh,back4] = htplda_llh(oldR,oldLabels,F,W,nu); else [newllh,back2] = splda_llh(newR,newLabels,F,W); [oldllh,back4] = splda_llh(oldR,oldLabels,F,W); end y = (logdetJnew - newllh) + oldWeight*(logdetJold - oldllh); back = @back_this; function dparams = back_this(dy) doldR = back4(-oldWeight*dy); dnewR = back2(-dy); dparams = back3(doldR,oldWeight*dy) + back1(dnewR,dy); end end function test_this() [F,W,oldData,oldLabels] = simulateSPLDA(false,5,2); [~,~,newData,newLabels] = simulateSPLDA(false,5,2); rank = 3; dim = size(oldData,1); [f,fi,paramsz] = create_nice_Trans3(dim,rank); params = randn(paramsz,1); oldWeight = 1/pi; fprintf('test Gaussian PLDA:\n'); obj = @(params) MLNDA_MAP_obj(newData,newLabels,oldData,oldLabels,oldWeight,F,W,fi,params); testBackprop(obj,params); fprintf('test HT PLDA:\n'); nu = 2; obj = @(params) MLNDA_MAP_obj(newData,newLabels,oldData,oldLabels,oldWeight,F,W,fi,params,nu); testBackprop(obj,params); end
github
bsxfan/meta-embeddings-master
logdetNice.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/logdetNice.m
864
utf_8
3dbf0e9b2c0ef0c688e5d05ea7956379
function [logdet,back] = logdetNice(sigma,R,d) if nargin==0 test_this(); return; end RR = R.'*R; S = RR/sigma + diag(1./d); [L,U] = lu(S); dim = size(R,1); logdet = ( sum(log(diag(U).^2)) + sum(log(d.^2)) + dim*log(sigma^2) ) /2; back = @back_this; function [dsigma,dR,dd] = back_this(dlogdet) dS = dlogdet*(inv(U)/L).'; dd = dlogdet./d; dsigma = dim*dlogdet/sigma; dR = R*(dS + dS.')/sigma; dsigma = dsigma - (RR(:).'*dS(:))/sigma^2; dd = dd - diag(dS)./d.^2; end end function test_this() dim = 5; rank = 2; sigma = randn; R = randn(dim,rank); d = randn(rank,1); M = sigma*eye(dim) + R*diag(d)*R.'; [log(abs(det(M))),logdetNice(sigma,R,d)] testBackprop(@logdetNice,{sigma,R,d}) end
github
bsxfan/meta-embeddings-master
logdetNice4.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/logdetNice4.m
1,046
utf_8
62f8d2e7cac7cc028322c8d71f81b2e9
function [logdet,back] = logdetNice4(D,L,R) if nargin==0 test_this(); return; end [~,rank] = size(L); DL = bsxfun(@ldivide,D,L); RDL = R.'*DL; S = RDL + eye(rank); [Ls,Us] = lu(S); logdet = ( sum(log(diag(Us).^2)) + sum(log(D.^2)) ) /2; back = @back_this; function [dD,dL,dR] = back_this(dlogdet) %logdet = ( sum(log(diag(Us).^2)) + sum(log(D^2)) ) /2 dS = dlogdet*(inv(Us)/Ls).'; dD = dlogdet./D; %S = RDL + eye(rank) dRDL = dS; %RDL = R.'*DL dDL = R*dRDL; dR = DL*dRDL.'; % DL = bsxfun(@ldivide,D,L) dL = bsxfun(@ldivide,D,dDL); dD = dD - sum(DL.*dL,2); end end function test_this() dim = 5; rank = 2; D = randn(dim,1); R = randn(dim,rank); L = randn(dim,rank); M = diag(D) + L*R.'; [log(abs(det(M))),logdetNice4(D,L,R)] testBackprop(@logdetNice4,{D,L,R},{1,1,1}) end
github
bsxfan/meta-embeddings-master
htplda_llh.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/htplda_llh.m
2,103
utf_8
d1bda1755ab4932ab4a22c90e64c4d1b
function [llh,back] = htplda_llh(R,labels,F,W,nu) % Inputs: % R: D-by-N, i-vectors % labels: sparse, logical K-by-N, one hot columns, K speakers, N recordings if nargin==0 test_this(); return; end [D,d] = size(F); FW = F.'*W; FWR = FW*R; S = FWR*labels.'; %first order natural parameter for speaker factor posterior %n = full(sum(labels,2)'); %zero order stats (recordings per speaker) FWF = FW*F; G = W - FW.'*(FWF\FW); GR = G*R; q = sum(R.*(GR),1); b = (nu + D - d)./(nu + q); n = b*labels.'; [V,E] = eig(FWF); E = diag(E); nE = bsxfun(@times,n,E); VS = V'*S; nEVS = (1+nE).\VS; Mu = V*nEVS; %posterior means WR = W*R; RWR = sum(R.*(WR),1); llh = ( Mu(:).'*S(:) - sum((nu+D)*log1p(RWR/nu),2) ) / 2; back = @back_this; function dR = back_this(dllh) % llh = ( Mu(:).'*S(:) - sum((nu+D)*log1p(RWR/nu),1) ) / 2 dMu = (dllh/2)*S; dS = (dllh/2)*Mu; dRWR = (-dllh*(nu+D)/(2*nu))./(1+RWR/nu); % RWR = sum(R.*(W*R),1) dR = bsxfun(@times,2*dRWR,WR); % Mu = V*nEVS dnEVS = V.'*dMu; % nEVS = (1+nE).\VS dVS = (1+nE).\dnEVS; dnE = -dVS.*nEVS; % VS = V'*S dS = dS + V*dVS; % nE = bsxfun(@times,n,E) dn = E.'*dnE; %n = b*labels.' db = dn*labels; % b = (nu + D - d)./(nu + q) dq = (-db.*b)./(nu+q); % q = sum(R.*(G*R),1) dR = dR + bsxfun(@times,2*dq,GR); % S = FWR*labels.' dFWR = dS*labels; % FWR = FW*R; dR = dR + FW.'*dFWR; end end function test_this() D = 4; d = 2; N = 10; K = 3; R = randn(D,N); labels = sparse(randi(K,1,N),1:N,true,K,N); F = randn(D,d); W = randn(D,D+1);W=W*W.'; nu = 2; f = @(R) htplda_llh(R,labels,F,W,nu); testBackprop(f,{R}); end
github
bsxfan/meta-embeddings-master
create_nice_Trans4.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/create_nice_Trans4.m
2,926
utf_8
acc1b16001cab1bbc286b4f1c9d385de
function [f,fi,paramsz,fe] = create_nice_Trans4(dim,rank) % Creates affine transform, having a matrix: M = D + L*R.', where D is % diagonal and L and R are of low rank. The forward transform is: % f(X) = M \ X + offset if nargin==0 test_this(); return; end paramsz = dim + 2*dim*rank + dim; f = @f_this; fi = @fi_this; fe = @expand; function T = f_this(P,X) [D,L,R,offset] = expand(P); M = diag(D) + L*R.'; T = bsxfun(@plus,offset,M\X); end function [X,logdetJ,back] = fi_this(P,T) [D,L,R,offset,back0] = expand(P); Delta = bsxfun(@minus,T,offset); RDelta = R.'*Delta; X = bsxfun(@times,D,Delta) + L*RDelta; [logdet,back1] = logdetNice4(D,L,R); n = size(T,2); logdetJ = -n*logdet; back = @back_that; function [dP,dT] = back_that(dX,dlogdetJ) %[logdetJ,back1] = logdetNice4(D,L,R) [dD,dL,dR] = back1(-n*dlogdetJ); % X = bsxfun(@times,D,Delta) + L*RDelta dD = dD + sum(dX.*Delta,2); dDelta = bsxfun(@times,D,dX); dL = dL + dX*RDelta.'; dRDelta = L.'*dX; % RDelta = R.'*Delta; dR = dR + Delta*dRDelta.'; dDelta = dDelta + R*dRDelta; % Delta = bsxfun(@minus,T,offset) dT = dDelta; doffset = -sum(dDelta,2); dP = back0(dD,dL,dR,doffset); end end function [D,L,R,offset,back] = expand(P) at = 1; sz = dim; %logsigma = P(at); %sigma = exp(logsigma); %sigma = P(at); sqrtD = P(at:at+sz-1); D = sqrtD.^2; at = at + sz; sz = dim*rank; L = reshape(P(at:at+sz-1),dim,rank); at = at + sz; sz = dim*rank; R = reshape(P(at:at+sz-1),dim,rank); at = at + sz; sz = dim; offset = P(at:at+sz-1); at = at + sz; assert(at==length(P)+1); back = @back_this; function dP = back_this(dD,dL,dR,doffset) %dlogsigma = sigma*dsigma; %dP = [dlogsigma;dL(:);dd;doffset]; %dP = [dsigma;dL(:);dd;doffset]; dsqrtD = 2*sqrtD.*dD; dP = [dsqrtD;dL(:);dR(:);doffset]; end end end function test_this() dim = 5; rank = 2; n = 6; [f,fi,sz,fe] = create_nice_Trans4(dim,rank); P = randn(sz,1); X = randn(dim,n); T = f(P,X); Xi = fi(P,T); test_inverse = max(abs(X(:)-Xi(:))), testBackprop_multi(fi,2,{P,T}); %testBackprop_multi(fe,4,{P}); end
github
bsxfan/meta-embeddings-master
create_nice_Trans.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/create_nice_Trans.m
3,126
utf_8
564dc31754d76cf3ff3e1b29812bda01
function [f,fi,paramsz,fe] = create_nice_Trans(dim,rank) % Creates affine transform, having a matrix: M = sigma I + L*D*L.', where % L is of low rank and D is diagonal. The forward transform is: % f(X) = M \ X + offset if nargin==0 test_this(); return; end paramsz = 1 + dim*rank + rank + dim; f = @f_this; fi = @fi_this; fe = @expand; function T = f_this(P,R) [sigma,L,d,offset] = expand(P); M = sigma*eye(dim) + L*diag(d)*L.'; T = bsxfun(@plus,offset,M\R); end function [R,logdetJ,back] = fi_this(P,T) [sigma,L,d,offset,back0] = expand(P); Delta = bsxfun(@minus,T,offset); DL = bsxfun(@times,d,L.'); DLDelta = DL*Delta; R = sigma*Delta + L*DLDelta; [logdet,back1] = logdetNice(sigma,L,d); n = size(T,2); logdetJ = -n*logdet; back = @back_that; function [dP,dT] = back_that(dR,dlogdetJ) %[logdetJ,back1] = logdetNice(sigma,L,d) [dsigma,dL,dd] = back1(-n*dlogdetJ); % R = sigma*Delta + L*DLDelta dsigma = dsigma + dR(:).'*Delta(:); dDelta = sigma*dR; dL = dL + dR*DLDelta.'; dDLDelta = L.'*dR; % DLDelta = DL*Delta; dDL = dDLDelta*Delta.'; dDelta = dDelta + DL.'*dDLDelta; % DL = bsxfun(@times,d,L.') dd = dd + sum(dDL.*L.',2); dL = dL + bsxfun(@times,dDL.',d'); % Delta = bsxfun(@minus,T,offset) dT = dDelta; doffset = -sum(dDelta,2); dP = back0(dsigma,dL,dd,doffset); end end function [sigma,L,d,offset,back] = expand(P) at = 1; sz = 1; %logsigma = P(at); %sigma = exp(logsigma); %sigma = P(at); sqrtsigma = P(at); sigma = sqrtsigma^2; at = at + sz; sz = dim*rank; L = reshape(P(at:at+sz-1),dim,rank); at = at + sz; sz = rank; d = P(at:at+sz-1); at = at + sz; sz = dim; offset = P(at:at+sz-1); at = at + sz; assert(at==length(P)+1); back = @back_this; function dP = back_this(dsigma,dL,dd,doffset) %dlogsigma = sigma*dsigma; %dP = [dlogsigma;dL(:);dd;doffset]; %dP = [dsigma;dL(:);dd;doffset]; dsqrtsigma = 2*dsigma*sqrtsigma; dP = [dsqrtsigma;dL(:);dd;doffset]; end end end function test_this() dim = 5; rank = 2; n = 6; [f,fi,sz,fe] = create_nice_Trans(dim,rank); P = randn(sz,1); R = randn(dim,n); T = f(P,R); Ri = fi(P,T); test_inverse = max(abs(R(:)-Ri(:))), testBackprop_multi(fi,2,{P,T}); %testBackprop_multi(fe,4,{P}); end
github
bsxfan/meta-embeddings-master
logdetNice3.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/logdetNice3.m
980
utf_8
64ca857b7b319139b15a8c416ff1ac41
function [logdet,back] = logdetNice3(sigma,L,R) if nargin==0 test_this(); return; end [dim,rank] = size(L); RL = R.'*L; S = RL/sigma + eye(rank); [Ls,Us] = lu(S); logdet = ( sum(log(diag(Us).^2)) + dim*log(sigma^2) ) /2; back = @back_this; function [dsigma,dL,dR] = back_this(dlogdet) %logdet = ( sum(log(diag(Us).^2)) + dim*log(sigma^2) ) /2; dS = dlogdet*(inv(Us)/Ls).'; dsigma = dim*dlogdet/sigma; %S = RL/sigma + eye(rank) dRL = dS/sigma; dsigma = dsigma - (RL(:).'*dS(:))/sigma^2; %RL = R.'*L; dL = R*dRL; dR = L*dRL.'; end end function test_this() dim = 5; rank = 2; sigma = randn; R = randn(dim,rank); L = randn(dim,rank); M = sigma*eye(dim) + L*R.'; [log(abs(det(M))),logdetNice3(sigma,L,R)] testBackprop(@logdetNice3,{sigma,L,R}) end
github
bsxfan/meta-embeddings-master
splda_llh.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/splda_llh.m
1,253
utf_8
9fa88758bc715c7d0d76209bd1936f6a
function [llh,back] = splda_llh(R,labels,F,W) % Inputs: % R: D-by-N, i-vectors % labels: sparse, logical K-by-N, one hot columns, K speakers, N recordings if nargin==0 test_this(); return; end FW = F.'*W; FWR = FW*R; S = FWR*labels.'; %first order natural parameter for speaker factor posterior n = full(sum(labels,2)'); %zero order stats (recordings per speaker) FWF = FW*F; [V,E] = eig(FWF); E = diag(E); nE = bsxfun(@times,n,E); % Mu = V*bsxfun(@ldivide,1+nE,V'*S); %posterior means Mu = V*( (1+nE).\(V'*S) ); %posterior means RR = R*R.'; llh = ( Mu(:).'*S(:) - RR(:).'*W(:) ) / 2; back = @back_this; function dR = back_this(dllh) dMu = (dllh/2)*S; dS = (dllh/2)*Mu; dRR = (-dllh/2)*W; dR = (2*dRR)*R; dS = dS + V*bsxfun(@ldivide,1+nE,V'*dMu); dFWR = dS*labels; dR = dR + FW.'*dFWR; end end function test_this() D = 4; d = 2; N = 10; K = 3; R = randn(D,N); labels = sparse(randi(K,1,N),1:N,true,K,N); F = randn(D,d); W = randn(D,D+1);W=W*W.'; f = @(R) splda_llh(R,labels,F,W); testBackprop(f,{R}); end
github
bsxfan/meta-embeddings-master
create_nice_Trans3.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/create_nice_Trans3.m
2,943
utf_8
e197b146f2ee6588c45fc36d860a3db9
function [f,fi,paramsz,fe] = create_nice_Trans3(dim,rank) % Creates affine transform, having a matrix: M = sigma I + L*R.', where % L and R are of low rank. The forward transform is: % f(X) = M \ X + offset if nargin==0 test_this(); return; end paramsz = 1 + 2*dim*rank + dim; f = @f_this; fi = @fi_this; fe = @expand; function T = f_this(P,X) [sigma,L,R,offset] = expand(P); M = sigma*eye(dim) + L*R.'; T = bsxfun(@plus,offset,M\X); end function [X,logdetJ,back] = fi_this(P,T) [sigma,L,R,offset,back0] = expand(P); Delta = bsxfun(@minus,T,offset); RDelta = R.'*Delta; X = sigma*Delta + L*RDelta; [logdet,back1] = logdetNice3(sigma,L,R); n = size(T,2); logdetJ = -n*logdet; back = @back_that; function [dP,dT] = back_that(dX,dlogdetJ) %[logdetJ,back1] = logdetNice3(sigma,L,R) [dsigma,dL,dR] = back1(-n*dlogdetJ); % X = sigma*Delta + L*RDelta; dsigma = dsigma + dX(:).'*Delta(:); dDelta = sigma*dX; dL = dL + dX*RDelta.'; dRDelta = L.'*dX; % RDelta = R.'*Delta; dR = dR + Delta*dRDelta.'; dDelta = dDelta + R*dRDelta; % Delta = bsxfun(@minus,T,offset) dT = dDelta; doffset = -sum(dDelta,2); dP = back0(dsigma,dL,dR,doffset); end end function [sigma,L,R,offset,back] = expand(P) at = 1; sz = 1; %logsigma = P(at); %sigma = exp(logsigma); %sigma = P(at); sqrtsigma = P(at); sigma = sqrtsigma^2; at = at + sz; sz = dim*rank; L = reshape(P(at:at+sz-1),dim,rank); at = at + sz; sz = dim*rank; R = reshape(P(at:at+sz-1),dim,rank); at = at + sz; sz = dim; offset = P(at:at+sz-1); at = at + sz; assert(at==length(P)+1); back = @back_this; function dP = back_this(dsigma,dL,dR,doffset) %dlogsigma = sigma*dsigma; %dP = [dlogsigma;dL(:);dd;doffset]; %dP = [dsigma;dL(:);dd;doffset]; dsqrtsigma = 2*dsigma*sqrtsigma; dP = [dsqrtsigma;dL(:);dR(:);doffset]; end end end function test_this() dim = 5; rank = 2; n = 6; [f,fi,sz,fe] = create_nice_Trans3(dim,rank); P = randn(sz,1); X = randn(dim,n); T = f(P,X); Xi = fi(P,T); test_inverse = max(abs(X(:)-Xi(:))), testBackprop_multi(fi,2,{P,T}); %testBackprop_multi(fe,4,{P}); end
github
bsxfan/meta-embeddings-master
create_nice_Trans2.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/create_nice_Trans2.m
2,933
utf_8
aba4972b59d6acfb19b6a85c190bb897
function [f,fi,paramsz,fe] = create_nice_Trans2(dim,rank) if nargin==0 test_this(); return; end paramsz = 1 + dim*rank + rank*rank + dim; f = @f_this; fi = @fi_this; fe = @expand; function T = f_this(P,R) [sigma,L,D,offset] = expand(P); M = sigma*eye(dim) + L*D*L.'; T = bsxfun(@plus,offset,M\R); end function [R,logdetJ,back] = fi_this(P,T) [sigma,L,D,offset,back0] = expand(P); Delta = bsxfun(@minus,T,offset); DL = D*L.'; DLDelta = DL*Delta; R = sigma*Delta + L*DLDelta; [logdet,back1] = logdetNice2(sigma,L,D); n = size(T,2); logdetJ = -n*logdet; back = @back_that; function [dP,dT] = back_that(dR,dlogdetJ) %[logdetJ,back1] = logdetNice(sigma,L,d) [dsigma,dL,dD] = back1(-n*dlogdetJ); % R = sigma*Delta + L*DLDelta dsigma = dsigma + dR(:).'*Delta(:); dDelta = sigma*dR; dL = dL + dR*DLDelta.'; dDLDelta = L.'*dR; % DLDelta = DL*Delta; dDL = dDLDelta*Delta.'; dDelta = dDelta + DL.'*dDLDelta; % DL = D*L.' dD = dD + dDL*L; dL = dL + dDL.'*D; % Delta = bsxfun(@minus,T,offset) dT = dDelta; doffset = -sum(dDelta,2); dP = back0(dsigma,dL,dD,doffset); end end function [sigma,L,D,offset,back] = expand(P) at = 1; sz = 1; %logsigma = P(at); %sigma = exp(logsigma); %sigma = P(at); sqrtsigma = P(at); sigma = sqrtsigma^2; at = at + sz; sz = dim*rank; L = reshape(P(at:at+sz-1),dim,rank); at = at + sz; sz = rank*rank; D = reshape(P(at:at+sz-1),rank,rank); at = at + sz; sz = dim; offset = P(at:at+sz-1); at = at + sz; assert(at==length(P)+1); back = @back_this; function dP = back_this(dsigma,dL,dD,doffset) %dlogsigma = sigma*dsigma; %dP = [dlogsigma;dL(:);dd;doffset]; %dP = [dsigma;dL(:);dd;doffset]; dsqrtsigma = 2*dsigma*sqrtsigma; dP = [dsqrtsigma;dL(:);dD(:);doffset]; end end end function test_this() dim = 5; rank = 2; n = 6; [f,fi,sz,fe] = create_nice_Trans2(dim,rank); P = randn(sz,1); R = randn(dim,n); T = f(P,R); Ri = fi(P,T); test_inverse = max(abs(R(:)-Ri(:))), testBackprop_multi(fi,2,{P,T}); %testBackprop_multi(fe,4,{P}); end
github
bsxfan/meta-embeddings-master
logdetNice2.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/logdetNice2.m
929
utf_8
469e8c40a8fb711c201f8fbeaf1c8b32
function [logdet,back] = logdetNice2(sigma,R,D) if nargin==0 test_this(); return; end RR = R.'*R; [Ld,Ud] = lu(D); invD = inv(Ud)/Ld; S = RR/sigma + invD; [L,U] = lu(S); dim = size(R,1); logdet = ( sum(log(diag(U).^2)) + sum(log(diag(Ud).^2)) + dim*log(sigma^2) ) /2; back = @back_this; function [dsigma,dR,dD] = back_this(dlogdet) dS = dlogdet*(inv(U)/L).'; dD = dlogdet*invD.'; dsigma = dim*dlogdet/sigma; dR = R*(dS + dS.')/sigma; dsigma = dsigma - (RR(:).'*dS(:))/sigma^2; dinvD = dS; dD = dD - D.'\(dinvD/D.'); end end function test_this() dim = 5; rank = 2; sigma = randn; R = randn(dim,rank); D = randn(rank); M = sigma*eye(dim) + R*D*R.'; [log(abs(det(M))),logdetNice2(sigma,R,D)] testBackprop(@logdetNice2,{sigma,R,D}) end
github
bsxfan/meta-embeddings-master
LinvSR.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/LinvSR.m
562
utf_8
cc684a75c7911f7d518550620e6b8fc7
function [Y,back] = LinvSR(L,S,R) if nargin==0 test_this(); return; end Z = S\R; Y = L*Z; back = @back_this; function [dL,dS,dR] = back_this(dY) % Y = L*Z dL = dY*Z.'; dZ = L.'*dY; % Z = S\R; dR = S.'\dZ; dS = -dR*Z.'; end end function test_this() m = 3; n = 4; L = randn(m,n); R = randn(n,m); S = randn(n,n); fprintf('test slow derivatives:\n'); testBackprop(@LinvSR,{L,S,R}); end
github
bsxfan/meta-embeddings-master
splda_adaptation_obj.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/splda_adaptation_obj.m
1,783
utf_8
6c6dfe6b4fc0b2eedc0ac2e4802de451
function [y,back] = splda_adaptation_obj(newData,labels,oldF,oldW,params,num_new_Fcols,W_adj_rank,slow) if nargin==0 test_this(); return; end if ~exist('slow','var') slow = false; end [dim,Frank] = size(oldF); [Fcols,Fscal,Cfac] = unpack_SPLDA_adaptation_params(params,dim,Frank,num_new_Fcols,W_adj_rank); [newF,newW,back1] = adaptSPLDA(Fcols,Fscal,Cfac,oldF,oldW); [llh,back2] = splda_llh_full(labels,newF,newW,newData,slow); y = -llh; back = @back_this; function dparams = back_this(dy) dllh = -dy; [dnewF,dnewW] = back2(dllh); [Fcols,Fscal,Cfac] = back1(dnewF,dnewW); dparams = [Fcols(:);Fscal(:);Cfac(:)]; end end function test_this() dim = 20; Frank = 5; num_new_Fcols = 2; W_adj_rank = 3; n = 100; K = 15; newData = randn(dim,n); labels = sparse(randi(K,1,n),1:n,true,K,n); oldF = randn(dim,Frank); oldW = randn(dim,dim+1);oldW = oldW * oldW.'; Fcols = randn(dim,num_new_Fcols); Cfac = randn(dim,W_adj_rank); Fscal = randn(1,Frank); params = [Fcols(:);Fscal(:);Cfac(:)]; f_slow = @(params) splda_adaptation_obj(newData,labels,oldF,oldW,params,num_new_Fcols,W_adj_rank,true); f_fast = @(params) splda_adaptation_obj(newData,labels,oldF,oldW,params,num_new_Fcols,W_adj_rank,false); fprintf('test function value equality:\n'); delta = abs(f_slow(params)-f_fast(params)), fprintf('test slow derivatives:\n'); testBackprop(f_slow,params); [~,back] = f_slow(params); dparams = back(pi); [~,back] = f_fast(params); dparams = back(pi); fprintf('compare fast and slow derivatives:\n'); delta = max(abs(dparams-dparams)), end
github
bsxfan/meta-embeddings-master
logdetLU.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/logdetLU.m
393
utf_8
f89f69d0255592e7c1933492e7894c79
function [y,back] = logdetLU(M) if nargin==0 test_this(); return; end [L,U] = lu(M); y = sum(log(diag(U).^2))/2; back = @back_this; function dM = back_this(dy) %dM = dy*(inv(U)/L).'; dM = dy*(L.'\inv(U.')); end end function test_this() dim = 5; M = randn(dim); testBackprop(@logdetLU,M); end
github
bsxfan/meta-embeddings-master
posteriorNorm2_slow.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/posteriorNorm2_slow.m
1,855
utf_8
c490aa24f95c0ecb840e47f99af01af6
function [y,back] = posteriorNorm2_slow(A,B,b,priorFac) % Computes, for every i: log N( 0 | Pi\A(:,i), inv(Pi) ), where % % precisions are Pi = I + b(i)*B % % This is the slow version, used only to verify correctness of the function % value and derivatives of the fast version, posteriorNorm_fast(). % % Inputs: % A: dim-by-n, natural parameters (precision *mean) for n Gaussians % B: dim-by-dim, common precision matrix factor (full, positive semi-definite) % b: 1-by-n, precision scale factors % % Outputs: % y: 1-by-n, log densities, evaluated at zero % back: backpropagation handle, [dA,dB,db] = back(dy) if nargin==0 test_this(); return; end [dim,n] = size(A); P = priorFac*priorFac.'; % prior precision y = zeros(1,n); S = zeros(dim,n); for i=1:n a = A(:,i); bBI = P+b(i)*B; s = bBI\a; S(:,i) = s; logd = logdet(bBI); y(i) = (logd - s.'*a)/2; end back = @back_this; function [dA,dB,db] = back_this(dy) dA = zeros(size(A)); db = zeros(size(b)); dB = zeros(size(B)); for ii=1:n s = S(:,ii); a = A(:,ii); da = -(dy(ii)/2)*s; ds = -(dy(ii)/2)*a; dlogd = dy(ii)/2; bBI = I+b(ii)*B; dbBI = dlogd*inv(bBI); %#ok<MINV> da2 = bBI.'\ds; dA(:,ii) = da + da2; dbBI = dbBI - (da2)*s.'; dB = dB + b(ii)*dbBI; db(ii) = dbBI(:).'*B(:); end end end function y = logdet(M) [~,U] = lu(M); y = sum(log(diag(U).^2))/2; end function test_this() m = 3; n = 5; A = randn(m,n); b = rand(1,n); B = randn(m,m+1); B = B*B.'; testBackprop(@posteriorNorm_slow,{A,B,b},{1,1,1}); end
github
bsxfan/meta-embeddings-master
adaptSPLDA.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/adaptSPLDA.m
1,791
utf_8
fce312e9e18adccb87760f2788ced832
function [Ft,Wt,back] = adaptSPLDA(Fcols,Fscal,Cfac,F,W) if nargin==0 test_this(); return; end Frank = length(Fscal); Ft = [bsxfun(@times,F,Fscal), Fcols]; % Wt = inv(Ct), Ct = inv(W) + Cfac*Cfac' % Wt = W - W*Cfac*inv(I + Cfac'*W*Cfac)*Cfac'*W WCfac = W*Cfac; S = eye(size(Cfac,2)) + WCfac.'*Cfac; [Adj,back1] = LinvSR(WCfac,S,WCfac.'); Wt = W - (Adj + Adj.')/2; %numerically symmetrize back = @back_this; function [dFcols,dFscal,dCfac,dF,dW] = back_this(dFt,dWt) % Wt = W - (Adj + Adj.')/2 dAdj = -(dWt+dWt.')/2; dW = dWt; % [Wt0,back1] = LinvSR(WCfac,S,WCfac.') [dL,dS,dR] = back1(dAdj); dWCfac = dL + dR.'; % S = eye(size(Cfac,2)) + WCfac.'*Cfac; dWCfac = dWCfac + Cfac*dS.'; dCfac = WCfac*dS; %WCfac = W*Cfac; if nargout>=5 dW = dW + dWCfac*Cfac.'; end dCfac = dCfac + W.'*dWCfac; % Ft = [bsxfun(@times,F,Fscal), Fcols] dFcols = dFt(:,Frank+1:end); %OK dFscal = sum(dFt(:,1:Frank).*F,1); %OK if nargout>=4 dF = bsxfun(@times,dFt(:,1:Frank),Fscal); %OK end end end function test_this() dim = 10; Frank = 2; extra = 3; F = randn(dim,Frank); Fcols = randn(dim,extra); Fscal = randn(1,Frank); W = randn(dim,dim); Cfac = randn(dim,4); f1 = @(Fcols,Fscal,Cfac,F,W) adaptSPLDA(Fcols,Fscal,Cfac,F,W); f2 = @(Fcols,Fscal,Cfac) adaptSPLDA(Fcols,Fscal,Cfac,F,W); testBackprop_multi(f1,2,{Fcols,Fscal,Cfac,F,W}); testBackprop_multi(f2,2,{Fcols,Fscal,Cfac}); end
github
bsxfan/meta-embeddings-master
matinv.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/matinv.m
345
utf_8
140429773a1c0fb820d3ebe7e4d16619
function [Y,back] = matinv(S) if nargin==0 test_this(); return; end Y = inv(S); back = @back_this; function dS = back_this(dY) dS = -Y.'*dY*Y.'; end end function test_this() n = 4; S = randn(n,n); testBackprop(@matinv,S); end
github
bsxfan/meta-embeddings-master
posteriorNorm_mindiv_slow.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/posteriorNorm_mindiv_slow.m
1,999
utf_8
3a06a111867c52058d73244d0ba36117
function [y,Ezz,back] = posteriorNorm_mindiv_slow(A,B,b) % Computes, for every i: log N( 0 | Pi\A(:,i), inv(Pi) ), where % % precisions are Pi = I + b(i)*B % % This is the slow version, used only to verify correctness of the function % value and derivatives of the fast version, posteriorNorm_fast(). % % Inputs: % A: dim-by-n, natural parameters (precision *mean) for n Gaussians % B: dim-by-dim, common precision matrix factor (full, positive semi-definite) % b: 1-by-n, precision scale factors % % Outputs: % y: 1-by-n, log densities, evaluated at zero % back: backpropagation handle, [dA,dB,db] = back(dy) if nargin==0 test_this(); return; end [dim,n] = size(A); I = speye(dim); y = zeros(1,n); S = zeros(dim,n); Ezz = zeros(dim); for i=1:n a = A(:,i); bBI = I+b(i)*B; s = bBI\a; S(:,i) = s; logd = logdet(bBI); y(i) = (logd - s.'*a)/2; Ezz = Ezz + inv(bBI) + s*s.'; end Ezz = Ezz/n; back = @back_this; function [dA,dB,db] = back_this(dy,dEzz) dA = zeros(size(A)); db = zeros(size(b)); dB = zeros(size(B)); for ii=1:n s = S(:,ii); a = A(:,ii); bBI = I+b(i)*B; ds = (2/n)*(dEzz*s); da = -(dy(ii)/2)*s; ds = ds -(dy(ii)/2)*a; dlogd = dy(ii)/2; bBI = I+b(ii)*B; dbBI = dlogd*inv(bBI); %#ok<MINV> da2 = bBI.'\ds; dA(:,ii) = da + da2; dbBI = dbBI - (da2)*s.'; dB = dB + b(ii)*dbBI; db(ii) = dbBI(:).'*B(:); end end end function y = logdet(M) [~,U] = lu(M); y = sum(log(diag(U).^2))/2; end function test_this() m = 3; n = 5; A = randn(m,n); b = rand(1,n); B = randn(m,m+1); B = B*B.'; testBackprop(@posteriorNorm_slow,{A,B,b},{1,1,1}); end
github
bsxfan/meta-embeddings-master
splda_llh_full.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/splda_llh_full.m
3,374
utf_8
9f2a6f749c0dfeb7e8f3ae83f26c362e
function [llh,back] = splda_llh_full(labels,F,W,R,slow) % Like splda_llh(), but backpropagates into all of F,W and R % % Inputs: % R: D-by-N, i-vectors % labels: sparse, logical K-by-N, one hot columns, K speakers, N recordings % F,W: SPLA parameters % slow: [optional, default = false] logical, use slow = true to test derivatives % % facW: [optional, default = true] logical: % true: W = Wfac*Wfac' % false: W = Wfac % % Outputs: % llh: total log density: log P(R | F,W,labels) if nargin==0 test_this(); return; end if ~exist('slow','var') slow = false; end [nspeakers,ndata] = size(labels); FW = F.'*W; FWR = FW*R; S = FWR*labels.'; %first order natural parameter for speaker factor posterior n = full(sum(labels,2)).'; %zero order stats (recordings per speaker) FWF = FW*F; if slow [pn,back1] = posteriorNorm_slow(S,FWF,n); else [pn,back1] = posteriorNorm_fast(S,FWF,n); end RR = R*R.'; % if ~slow % cholW = chol(W); % logdetW = 2*sum(log(diag(cholW))); % else % [Lw,Uw] = lu(W); % logdetW = sum(log(diag(Uw).^2))/2; % end [logdetW,back2] = logdetLU(W); llh = ( ndata*logdetW - RR(:).'*W(:) ) / 2 - sum(pn,2); back = @back_this; function [dF,dW,dR] = back_this(dllh) % llh = ( ndata*logdetW - RR(:).'*W(:) ) / 2 - sum(pn,2) dlogdetW = ndata*dllh/2; if nargout>=3 dRR = (-dllh/2)*W; end dW = (-dllh/2)*RR; dpn = repmat(-dllh,1,nspeakers); % [logdetW,back2] = logdetLU(W) dW = dW + back2(dlogdetW); % RR = R*R.' if nargout>=3 dR = (2*dRR)*R; end % [pn,back1] = posteriorNorm_fast(S,FWF,n) [dS,dFWF] = back1(dpn); % FWF = FW*F dFW = dFWF*F.'; dF = FW.'*dFWF; % S = FWR*labels.' dFWR = dS*labels; % FWR = FW*R; dFW = dFW + dFWR*R.'; if nargout >= 3 dR = dR + FW.'*dFWR; end % FW = F.'*W; dW = dW + F*dFW; dF = dF + W*dFW.'; end end function test_this() D = 4; d = 2; N = 10; K = 3; R = randn(D,N); labels = sparse(randi(K,1,N),1:N,true,K,N); F = randn(D,d); W = randn(D,D+1);W=W*W.'; slow = true; f_slow = @(F,W,R) splda_llh_full(labels,F,W,R,slow); f_fast = @(F,W,R) splda_llh_full(labels,F,W,R); f0 = @(F,W) splda_llh_full(labels,F,W,R); fprintf('test function value equality:\n'); delta = abs(f_slow(F,W,R)-f_fast(F,W,R)), fprintf('test slow derivatives:\n'); testBackprop(f_slow,{F,W,R},{1,1,1}); %return [~,back] = f_slow(F,W,R); [dFs,dWs,dRs] = back(pi); [~,back] = f_fast(F,W,R); [dFf,dWf,dRf] = back(pi); [~,back] = f0(F,W); [dF0,dW0] = back(pi); fprintf('compare fast and slow derivatives:\n'); deltaF = max(abs(dFs(:)-dFf(:))), deltaW = max(abs(dWs(:)-dWf(:))), deltaR = max(abs(dRs(:)-dRf(:))), deltaF0 = max(abs(dFs(:)-dF0(:))), deltaW0 = max(abs(dWs(:)-dW0(:))), end
github
bsxfan/meta-embeddings-master
posteriorNorm_slow.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/posteriorNorm_slow.m
1,815
utf_8
a9b32fbd06cb0f91327d57dac2f41bbd
function [y,back] = posteriorNorm_slow(A,B,b) % Computes, for every i: log N( 0 | Pi\A(:,i), inv(Pi) ), where % % precisions are Pi = I + b(i)*B % % This is the slow version, used only to verify correctness of the function % value and derivatives of the fast version, posteriorNorm_fast(). % % Inputs: % A: dim-by-n, natural parameters (precision *mean) for n Gaussians % B: dim-by-dim, common precision matrix factor (full, positive semi-definite) % b: 1-by-n, precision scale factors % % Outputs: % y: 1-by-n, log densities, evaluated at zero % back: backpropagation handle, [dA,dB,db] = back(dy) if nargin==0 test_this(); return; end [dim,n] = size(A); I = speye(dim); y = zeros(1,n); S = zeros(dim,n); for i=1:n a = A(:,i); bBI = I+b(i)*B; s = bBI\a; S(:,i) = s; logd = logdet(bBI); y(i) = (logd - s.'*a)/2; end back = @back_this; function [dA,dB,db] = back_this(dy) dA = zeros(size(A)); db = zeros(size(b)); dB = zeros(size(B)); for ii=1:n s = S(:,ii); a = A(:,ii); da = -(dy(ii)/2)*s; ds = -(dy(ii)/2)*a; dlogd = dy(ii)/2; bBI = I+b(ii)*B; dbBI = dlogd*inv(bBI); %#ok<MINV> da2 = bBI.'\ds; dA(:,ii) = da + da2; dbBI = dbBI - (da2)*s.'; dB = dB + b(ii)*dbBI; db(ii) = dbBI(:).'*B(:); end end end function y = logdet(M) [~,U] = lu(M); y = sum(log(diag(U).^2))/2; end function test_this() m = 3; n = 5; A = randn(m,n); b = rand(1,n); B = randn(m,m+1); B = B*B.'; testBackprop(@posteriorNorm_slow,{A,B,b},{1,1,1}); end
github
bsxfan/meta-embeddings-master
posteriorNorm_fast.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/param_adaptation/posteriorNorm_fast.m
2,131
utf_8
f950d84510798e37996a0f242fd5f9be
function [y,back] = posteriorNorm_fast(A,B,b) % Computes, for every i: log N( 0 | Pi\A(:,i), inv(Pi) ), where % % precisions are Pi = I + b(i)*B % % This is the fast version, which simultaneously diagonalizes all the Pi, % using eigenanalysis of B. % % Inputs: % A: dim-by-n, natural parameters (precision *mean) for n Gaussians % B: dim-by-dim, common precision matrix factor (full, positive semi-definite) % b: 1-by-n, precision scale factors % % Outputs: % y: 1-by-n, log densities, evaluated at zero % back: backpropagation handle, [dA,dB,db] = back(dy) if nargin==0 test_this(); return; end [V,L] = eig(B); %V*L*V' = B L = diag(L); bL = bsxfun(@times,b,L); logdets = sum(log1p(bL),1); bL1 = 1 + bL; S = V*bsxfun(@ldivide,bL1,V.'*A); Q = sum(A.*S,1); y = (logdets - Q)/2; back = @back_this; function [dA,dB,db] = back_this(dy) hdy = dy/2; dA = bsxfun(@times,-hdy,S); dS = bsxfun(@times,-hdy,A); dlogdets = hdy; dA2 = V*bsxfun(@ldivide,bL1,V.'*dS); dA = dA + dA2; dBlogdet = V*bsxfun(@times,sum(bsxfun(@rdivide,b.*dlogdets,bL1),2),V.'); dBsolve = bsxfun(@times,-b,dA2) * S.'; dB = dBlogdet + (dBsolve+dBsolve.')/2; if nargout>=3 db = L.'*bsxfun(@ldivide,bL1,dlogdets) - sum(S.*(B*dA2),1); end end end function test_this() m = 3; n = 5; A = randn(m,n); b = rand(1,n); B = randn(m,m+1); B = B*B.'; fprintf('test function values:\n'); err = max(abs(posteriorNorm_fast(A,B,b) - posteriorNorm_slow(A,B,b))), fprintf('test derivatives:\n'); [y,back] = posteriorNorm_fast(A,B,b); dy = randn(size(y)); [dAf,dBf,dbf] = back(dy); [~,back] = posteriorNorm_slow(A,B,b); [dAs,dBs,dbs] = back(dy); err_dA = max(abs(dAs(:)-dAf(:))), err_db = max(abs(dbs(:)-dbf(:))), err_dB = max(abs(dBs(:)-dBf(:))), %neither complex, nor real step differentiation seem to work through eig() end
github
bsxfan/meta-embeddings-master
rkhs_inner_prod.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/mmd/rkhs_inner_prod.m
516
utf_8
8df105a9a35bd9faf72c137fd3d1d6e8
function y = rkhs_inner_prod(sigma,B1,a1,B2,a2) dim = length(a1); I = eye(dim); Bconv = (I+sigma*B1)\B1; % inv(sigmaI + inv(B1)) aconv = (I+sigma*B1)\a1; % Bconv*(B1\a) y = gauss_prod_int(aconv,Bconv,a2,B2); end function y = log_gauss_norm(B,a) [logd,mu,back] = logdet_solveLU(B,a); y = (logd-mu.'*a)/2; end function y = gauss_prod_int(a1,B1,a2,B2) y = exp(log_gauss_norm(B1,a1) + log_gauss_norm(B2,a2) ... - log_gauss_norm(B1+B2,a1+a2) ); end
github
bsxfan/meta-embeddings-master
log_gauss_norm.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/mmd/log_gauss_norm.m
527
utf_8
9dba44b2abd5c0513bb1b75566fab019
function [y,back] = log_gauss_norm(B,a) if nargin==0 test_this(); return; end [logd,mu,back1] = logdet_solveLU(B,a); y = (logd -mu.'*a)/2; back = @back_this; function [dB,da] = back_this(dy) dlogd = dy/2; da = (-dy/2)*mu; dmu = (-dy/2)*a; [dB,da1] = back1(dlogd,dmu); da = da + da1; end end function test_this() dim = 5; B = randn(dim); a = rand(dim,1); testBackprop(@log_gauss_norm,{B,a},{1,1}); end
github
bsxfan/meta-embeddings-master
logdet_solveLU.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/mmd/logdet_solveLU.m
508
utf_8
c3ec88a4a91de8ea84a175ef1857bfa8
function [y,mu,back] = logdet_solveLU(B,a) if nargin==0 test_this(); return; end [L,U] = lu(B); y = sum(log(diag(U).^2))/2; %logdet mu = U\(L\a); %solve back = @back_this; function [dB,da] = back_this(dy,dmu) dB = dy*(L.'\inv(U.')); da = L.'\(U.'\dmu); dB = dB - da*mu.'; end end function test_this() dim = 5; B = randn(dim); a = randn(dim,1); testBackprop_multi(@logdet_solveLU,2,{B,a}); end
github
bsxfan/meta-embeddings-master
rkhs_proj_onto_I0_slow.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/mmd/rkhs_proj_onto_I0_slow.m
1,766
utf_8
d012ab760719343ddc73bd3f4aa42563
function [y,back] = rkhs_proj_onto_I0_slow(sigma,A,b,B) % RKHS inner products of multivariate Gaussians onto standard normal. The % RKHS kernel is K(x,y) = ND(x|y,sigma I). The first order natural % parameters of the Gaussians are in the columns of A. The precisions are % proportional to the fixed B, with scaling contants in the vector b. if nargin==0 test_this(); return; end [dim,n] = size(A); Bconv = eye(dim)/(1+sigma); aconv = zeros(dim,1 ); lgn1 = log_gauss_norm(Bconv,aconv); % (-dim/2)*log1p(sigma); lgn2 = zeros(1,n); lgn12 = zeros(1,n); for i=1:n lgn2(i) = log_gauss_norm(b(i)*B,A(:,i)); lgn12(i) = log_gauss_norm(Bconv + b(i)*B,A(:,i)); end y = exp(lgn1 + lgn2 - lgn12); back = @back_this; function [dA,db,dB] = back_this(dy) dlgn2 = dy.*y; dlgn12 = -dlgn2; dA = zeros(dim,n); db = zeros(1,n); dB = zeros(size(B)); for ii=1:n bB = b(ii)*B; a = A(:,ii); [~,back1] = log_gauss_norm(bB,a); [dbB,da] = back1(dlgn2(i)); dA(:,ii) = da; db(ii) = dbB(:).'*B(:); dB = dB + b(ii)*dbB; [~,back2] = log_gauss_norm(Bconv + bB,a); [dbB,da] = back2(dlgn12(ii)); dA(:,ii) = dA(:,ii) + da; db(ii) = db(ii) + dbB(:).'*B(:); dB = dB + b(ii)*dbB; end end end function test_this() dim = 4; n = 3; A = randn(dim,n); b = randn(1,n).^2; B = randn(dim);B=B*B.'; sigma = pi; f = @(A,b,B) rkhs_proj_onto_I0_slow(sigma,A,b,B); testBackprop(f,{A,b,B},{0,0,1}); end
github
bsxfan/meta-embeddings-master
L_BFGS.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/optimization/L_BFGS.m
5,008
utf_8
8a3bd29f4c568d13b7c0f7e466850904
function [w,y,mem,logs] = L_BFGS(obj,w,maxiters,timeout,mem,stpsz0,callback) % L-BFGS Quasi-Newton unconstrained optimizer. % -- This has a small interface change from LBFGS.m -- % % Inputs: % obj: optimization objective, with interface: [y,grad] = obj(w), % where w is the parameter vector, y is the scalar objective value % and grad is a function handle, so that grad(1) gives the gradient % (same size as w). % w: the initial parameter vector % maxiters: max number of LBFGS iterations (line search iterations do not % count towards this limit). % timeout: LBFGS will stop when timeout (in seconds) is reached. % mem is either: (i) A struct with previously computed LBFGS data, to % allow resumption of iteration. % (ii) An integer: the size of the LBFGS memory. A good % default is 20. % %some linesearch magic numbers maxfev = 20; %max number of function evaluations stpmin = 1e-15; %same as Poblano default stpmax = 1e15; %same as Poblano default ftol = 1e-5; % as recommended by Nocedal (c1 in his book) gtol = 0.9; % as recommended by Nocedal (c2 in his book) xtol = 1e-15; %same as Poblano default quiet = false; %termination parameters % relFuncTol = 1e-6; %same as Poblano relFuncTol = 1e-8; if ~exist('stpsz0','var') || isempty(stpsz0) stpsz0 = 1; end stpsz = stpsz0; if ~exist('timeout','var') || isempty(timeout) timeout = 15*60; fprintf('timeout defaulted to 15 minutes'); end; if ~exist('callback','var') || isempty(callback) ncbLogs = 0; else ncbLogs = length( callback(w) ); end; tic; dim = length(w); if ~isstruct(mem) m = mem; mem = []; mem.m = m; mem.sz = 0; mem.rho = zeros(1,m); mem.S = zeros(dim,m); mem.Y = zeros(dim,m); else m = mem.m; end if ~exist('y','var') || isempty(y) [y,grad] = obj(w); g = grad(1); fprintf('LBFGS 0: obj = %g, ||g||=%g\n',y,sqrt(g'*g)); end initial_y = y; logs = zeros(3+ncbLogs, maxiters); nlogs = 0; gmag = sqrt(g'*g); k = 0; while true if gmag< eps fprintf('LBFGS converged with tiny gradient\n'); break; end % choose direction p = -Hprod(g,mem); assert(g'*p<0,'p is not downhill'); % line search g0 = g; y0 = y; w0 = w; [w,y,grad,g,alpha,info,nfev] = minpack_cvsrch(obj,w,y,g,p,stpsz,... ftol,gtol,xtol, ... stpmin,stpmax,maxfev,quiet); stpsz = 1; delta_total = abs(initial_y-y); delta = abs(y0-y); if delta_total>eps relfunc = delta/delta_total; else relfunc = delta; end gmag = sqrt(g'*g); if info==1 %Wolfe is happy sk = w-w0; yk = g-g0; dot = sk'*yk; assert(dot>0); if mem.sz==m mem.S(:,1:m-1) = mem.S(:,2:m); mem.Y(:,1:m-1) = mem.Y(:,2:m); mem.rho(:,1:m-1) = mem.rho(:,2:m); else mem.sz = mem.sz + 1; end sz = mem.sz; mem.S(:,sz) = sk; mem.Y(:,sz) = yk; mem.rho(sz) = 1/dot; fprintf('LBFGS %i: ||g||/n = %g, rel = %g\n',k+1,gmag/length(g),relfunc); else fprintf('LBFGS %i: NO UPDATE, info = %i, ||g||/n = %g, rel = %g\n',k+1,info,gmag/length(g),relfunc); end time = toc; nlogs = nlogs+1; if ncbLogs > 0 logs(:,nlogs) = [time; y; nfev; callback(w)']; disp(logs(4:end,nlogs)'); else logs(:,nlogs) = [time;y;nfev]; end k = k + 1; if k>=maxiters fprintf('LBFGS stopped: maxiters exceeded\n'); break; end if time>timeout fprintf('LBFGS stopped: timeout\n'); break; end if relfunc < relFuncTol fprintf('\nTDN: stopped with minimal function change\n'); break; end end logs = logs(:,1:nlogs); end function r = Hprod(q,mem) if mem.sz==0 r = q; return; end sz = mem.sz; S = mem.S; Y = mem.Y; rho = mem.rho; alpha = zeros(1,sz); for i=sz:-1:1 alpha(i) = rho(i)*S(:,i)'*q; q = q - alpha(i)*Y(:,i); end yy = sum(Y(:,sz).^2,1); r = q/(rho(sz)*yy); for i=1:sz beta = rho(i)*Y(:,i)'*r; r = r + S(:,i)*(alpha(i)-beta); end end
github
bsxfan/meta-embeddings-master
testBackprop_rs.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/test/testBackprop_rs.m
2,198
utf_8
9d88acaf06002d97bf8eb2fdc07bf7b8
function total = testBackprop_rs(block,X,delta,mask) %same as testFBblock, but with real step if ~iscell(X) X = {X}; end dX = cellrndn(X); if exist('mask','var') assert(length(mask)==length(X)); dX = cellmask(dX,mask); end cX1 = cellstep(X,dX,delta); cX2 = cellstep(X,dX,-delta); DX = cell(size(X)); [Y,back] = block(X{:}); DY = randn(size(Y)); [DX{:}] = back(DY); %DX = J'*DY dot1 = celldot(DX,dX); %dX' * J' * DY cY1 = block(cX1{:}); cY2 = block(cX2{:}); [Y2,dY2] = recover(cY1,cY2,delta); %dY2 = J*dX dot2 = DY(:).'*dY2(:); %DY' * J* DX Y_diff = max(abs(Y(:)-Y2(:))), jacobian_diff = abs(dot1-dot2), total = Y_diff + jacobian_diff; if total < 1e-6 fprintf('\ntotal error=%g\n',total); else fprintf(2,'\ntotal error=%g\n',total); end end function R = cellrndn(X) if ~iscell(X) R = randn(size(X)); else R = cell(size(X)); for i=1:numel(X) R{i} = cellrndn(X{i}); end end end function C = cellstep(X,dX,delta) assert(all(size(X)==size(dX))); if ~iscell(X) C = X + delta*dX; else C = cell(size(X)); for i=1:numel(X) C{i} = cellstep(X{i},dX{i},delta); end end end function [R,D] = recover(cX1,cX2,delta) assert(all(size(cX1)==size(cX2))); if ~iscell(cX1) R = (cX1+cX2)/2; D = (cX1-cX2)/(2*delta); else R = cell(size(cX1)); D = cell(size(cX1)); for i=1:numel(cX1) [R{i},D{i}] = recover(cX1{i},cX2{i}); end end end function X = cellmask(X,mask) if ~iscell(X) assert(length(mask)==1); X = X*mask; else for i=1:numel(X) X{i} = cellmask(X{i},mask{i}); end end end function dot = celldot(X,Y) assert(all(size(X)==size(Y))); if ~iscell(X) dot = X(:).' * Y(:); else dot = 0; for i=1:numel(X) dot = dot + celldot(X{i},Y{i}); end end end
github
bsxfan/meta-embeddings-master
testBackprop_multi.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/test/testBackprop_multi.m
2,361
utf_8
ced4a5b7e925d5c00a2d991fb34d012c
function total = testBackprop_multi(block,nout,X,mask) % same as testBackprop, but handles multiple outputs if ~iscell(X) X = {X}; end dX = cellrndn(X); if exist('mask','var') assert(length(mask)==length(X)); dX = cellmask(dX,mask); end cX = cellcomplex(X,dX); DX = cell(size(X)); Y = cell(1,nout); [Y{:},back] = block(X{:}); DY = cell(size(Y)); for i=1:numel(DY) DY{i} = randn(size(Y{i})); end [DX{:}] = back(DY{:}); %DX = J'*DY dot1 = celldot(DX,dX); %dX' * J' * DY cY = cell(1,nout); Y2 = cell(1,nout); dY2 = cell(1,nout); [cY{:}] = block(cX{:}); for i=1:numel(cY) [Y2{i},dY2{i}] = recover(cY{i}); %dY2 = J*dX end dot2 = celldot(DY,dY2); %DY' * J* DX Y_diff = 0; for i=1:nout Y_diff = Y_diff + max(abs(Y{i}(:)-Y2{i}(:))); end Y_diff, jacobian_diff = abs(dot1-dot2), total = Y_diff + jacobian_diff; if total < 1e-6 fprintf('\ntotal error=%g\n',total); else fprintf(2,'\ntotal error=%g\n',total); end end function R = cellrndn(X) if ~iscell(X) R = randn(size(X)); else R = cell(size(X)); for i=1:numel(X) R{i} = cellrndn(X{i}); end end end function X = cellmask(X,mask) if ~iscell(X) assert(length(mask)==1); X = X*mask; else for i=1:numel(X) X{i} = cellmask(X{i},mask{i}); end end end function C = cellcomplex(X,dX) assert(all(size(X)==size(dX))); if ~iscell(X) C = complex(X,1e-20*dX); else C = cell(size(X)); for i=1:numel(X) C{i} = cellcomplex(X{i},dX{i}); end end end function [R,D] = recover(cX) if ~iscell(cX) R = real(cX); D = 1e20*imag(cX); else R = cell(size(cX)); D = cell(size(cX)); for i=1:numel(cX) [R{i},D{i}] = recover(cX{i}); end end end function dot = celldot(X,Y) assert(all(size(X)==size(Y))); if ~iscell(X) dot = X(:).' * Y(:); else dot = 0; for i=1:numel(X) dot = dot + celldot(X{i},Y{i}); end end end
github
bsxfan/meta-embeddings-master
testBackprop.m
.m
meta-embeddings-master/code/Niko/matlab/SRE18/MLNDA_SRE18/test/testBackprop.m
2,015
utf_8
fc73fa404f5441c097eb63f249106078
function total = testBackprop(block,X,mask) if ~iscell(X) X = {X}; end dX = cellrndn(X); if exist('mask','var') assert(length(mask)==length(X)); dX = cellmask(dX,mask); end cX = cellcomplex(X,dX); DX = cell(size(X)); [Y,back] = block(X{:}); DY = randn(size(Y)); [DX{:}] = back(DY); %DX = J'*DY dot1 = celldot(DX,dX); %dX' * J' * DY cY = block(cX{:}); [Y2,dY2] = recover(cY); %dY2 = J*dX dot2 = DY(:).'*dY2(:); %DY' * J* DX Y_diff = max(abs(Y(:)-Y2(:))), jacobian_diff = abs(dot1-dot2), total = Y_diff + jacobian_diff; if total < 1e-6 fprintf('\ntotal error=%g\n',total); else fprintf(2,'\ntotal error=%g\n',total); end end function R = cellrndn(X) if ~iscell(X) R = randn(size(X)); else R = cell(size(X)); for i=1:numel(X) R{i} = cellrndn(X{i}); end end end function X = cellmask(X,mask) if ~iscell(X) assert(length(mask)==1); X = X*mask; else for i=1:numel(X) X{i} = cellmask(X{i},mask{i}); end end end function C = cellcomplex(X,dX) assert(all(size(X)==size(dX))); if ~iscell(X) C = complex(X,1e-20*dX); else C = cell(size(X)); for i=1:numel(X) C{i} = cellcomplex(X{i},dX{i}); end end end function [R,D] = recover(cX) if ~iscell(cX) R = real(cX); D = 1e20*imag(cX); else R = cell(size(cX)); D = cell(size(cX)); for i=1:numel(cX) [R{i},D{i}] = recover(cX{i}); end end end function dot = celldot(X,Y) assert(all(size(X)==size(Y))); if ~iscell(X) dot = X(:).' * Y(:); else dot = 0; for i=1:numel(X) dot = dot + celldot(X{i},Y{i}); end end end
github
gaoxifeng/Robust-Hexahedral-Re-Meshing-master
m2p.m
.m
Robust-Hexahedral-Re-Meshing-master/extern/libigl/python/matlab/m2p.m
786
utf_8
9c36f898544f3e8561f950ac4cc06626
% Converts a Matlab matrix to a python-wrapped Eigen Matrix function [ P ] = m2p( M ) if (isa(M, 'double')) % Convert the matrix to a python 1D array a = py.array.array('d',reshape(M,1,numel(M))); % Then convert it to a eigen type t = py.igl.eigen.MatrixXd(a.tolist()); % Finally reshape it back P = t.MapMatrix(uint16(size(M,1)),uint16(size(M,2))); elseif (isa(M, 'integer')) % Convert the matrix to a python 1D array a = py.array.array('i',reshape(M,1,numel(M))); % Then convert it to a eigen type t = py.igl.eigen.MatrixXi(a.tolist()); % Finally reshape it back P = t.MapMatrix(uint16(size(M,1)),uint16(size(M,2))); else error('Unsupported numerical type.'); end
github
gaoxifeng/Robust-Hexahedral-Re-Meshing-master
p2m.m
.m
Robust-Hexahedral-Re-Meshing-master/extern/libigl/python/matlab/p2m.m
585
utf_8
15f32817630ba8b7a51a95ba7e4d5f2b
% Converts a python-wrapped Eigen Matrix to a Matlab matrix function [ M ] = p2m( P ) if py.repr(py.type(P)) == '<class ''igl.eigen.MatrixXd''>' % Convert it to a python array first t = py.array.array('d',P); % Reshape it M = reshape(double(t),P.rows(),P.cols()); elseif py.repr(py.type(P)) == '<class ''igl.eigen.MatrixXi''>' % Convert it to a python array first t = py.array.array('i',P); % Reshape it M = reshape(int32(t),P.rows(),P.cols()); else error('Unsupported numerical type.'); end end
github
janhavelka/Stochastic-Finite-Element-Method-master
trisurfc.m
.m
Stochastic-Finite-Element-Method-master/functions/trisurfc.m
14,500
utf_8
850e8c97d2b3250b7af61ed01af5dd00
function [cout,hout] = trisurfc(el,xin,yin,zin,N,shift,magnit) % Contouring and surface function for functions defined on triangular meshes % % xin, yin, zin, are arrays of x,y,z values of the points for your surface. % So [x(1) y(1) z(1)] defines the first point, etc. % % The last input N defines the contouring levels. There are several % options: % % N scalar - N number of equally spaced contours will be drawn % N vector - Draws contours at the levels specified in N % % A special call with a two element N where both elements are equal draws a % single contour at that level. % % [C,H] = TRISURFC(...) % % This syntax can be used to pass the contour matrix C and the contour % handels H to clabel by adding clabel(c,h) or clabel(c) after the call to % TRICSURFC. % % % % Contour line code by Darren Engwirda - 2005 ([email protected]) % Updated 15/05/2006 % Modified for trisurfc by JK September 2009 % Surface code added by Jack Kohoutek - 2009 ([email protected] % I/O checking if nargin~=7 error('Incorrect number of inputs') end if nargout>2 error('Incorrect number of outputs') end % Error checking if (size(xin,2)~=1) || (size(yin,2)~=1) || (size(zin,2)~=1) error('Incorrect input dimensions') end if (size(xin,1)~=size(yin,1)) || (size(xin,1)~=size(zin,1)) || (size(yin,1)~=size(zin,1)) error('Lists must have equal lengths.') end p=[xin yin]; % el=delaunay(xin,yin); if (max(el(:))>size(p,1)) || (min(el(:))<=0) error('Not a valid triangulation.') end if (size(N,1)>1) && (size(N,2)>1) error('N cannot be a matrix') end % figure1 = figure('PaperSize',[20.98404194812 29.67743169791]); % % Create figure % axes1 = axes('Parent',figure1,'PlotBoxAspectRatio',[1 1 1],'FontSize',20,... % 'DataAspectRatio',[1 1 1.5],... % 'CameraViewAngle',10.339584907202,... % 'CameraUpVector',[0 0 1],... % 'CameraTarget',[3.61935677548001 -0.524324582796977 -4.25370233938983],... % 'CameraPosition',[-32.9063289650433 -48.1255250002711 47.7078218876765]); % grid(axes1,'on'); % hold(axes1,'all'); % figure trisurf(el,xin,yin,zin,'FaceColor','interp'); % colorbar; Hn=zin; zlimits = get(gca,'Zlim'); % contourplotheight=abs(zlimits(1))-abs(zlimits(1)*5); contourplotheight=-shift; hold all set(gca,'DataAspectRatio',[1 1 magnit]) % A=trimesh(el,xin,yin,contourplotheight.*ones(size(xin,1),1),zeros(size(xin,1),1),'LineWidth',0.1); MeshTri=TriRep(el,xin,yin); h=triplot(MeshTri,'Color',[0.5 0.5 0.5],'LineWidth',0.2); set(h,'ZData',contourplotheight + zeros(4,1)) % h2=triplot(MeshTri,'Color',[0.5 0.5 0.5],'LineWidth',0.2); % MeshTriangul=triangulation(el,xin,yin); set(gca,'FontSize',20,'XGrid','on','YGrid','on'); % % % Generate a struct array containing the complete mesh information % if exist('triangulation','builtin') % MeshTri=triangulation(el,xin,yin); % Bound=freeBoundary(MeshTri); % elseif exist('TriRep','file') % MeshTri=TriRep(el,xin,yin); % Bound=freeBoundary(MeshTri); % else % warning('Either ''triangulation'' or ''TriRep'' builtin functions were not found!') % end % % % plot3(xin(Bound),yin(Bound),contourplotheight.*ones(size(Bound,1),1),'-k','LineWidth',1.5); % triplot(MeshTri,'Color','b','LineWidth',1.2) % Make mesh connectivity data structures (edge based pointers) [e,eINt,e2t] = mkcon(p,el); numt = size(el,1); % Num triangles nume = size(e,1); % Num edges %========================================================================== % Quadratic interpolation to centroids %========================================================================== % Nodes t1 = el(:,1); t2 = el(:,2); t3 = el(:,3); % FORM FEM GRADIENTS % Evaluate centroidal gradients (piecewise-linear interpolants) x23 = p(t2,1)-p(t3,1); y23 = p(t2,2)-p(t3,2); x21 = p(t2,1)-p(t1,1); y21 = p(t2,2)-p(t1,2); % Centroidal values Htx = (y23.*Hn(t1) + (y21-y23).*Hn(t2) - y21.*Hn(t3)) ./ (x23.*y21-x21.*y23); Hty = (x23.*Hn(t1) + (x21-x23).*Hn(t2) - x21.*Hn(t3)) ./ (y23.*x21-y21.*x23); % Form nodal gradients. % Take the average of the neighbouring centroidal values Hnx = 0*Hn; Hny = Hnx; count = Hnx; for k = 1:numt % Nodes n1 = t1(k); n2 = t2(k); n3 = t3(k); % Current values Hx = Htx(k); Hy = Hty(k); % Average to n1 Hnx(n1) = Hnx(n1)+Hx; Hny(n1) = Hny(n1)+Hy; count(n1) = count(n1)+1; % Average to n2 Hnx(n2) = Hnx(n2)+Hx; Hny(n2) = Hny(n2)+Hy; count(n2) = count(n2)+1; % Average to n3 Hnx(n3) = Hnx(n3)+Hx; Hny(n3) = Hny(n3)+Hy; count(n3) = count(n3)+1; end Hnx = Hnx./count; Hny = Hny./count; % Centroids [x,y] pt = (p(t1,:)+p(t2,:)+p(t3,:))/3; % Take unweighted average of the linear extrapolation from nodes to centroids Ht = ( Hn(t1) + (pt(:,1)-p(t1,1)).*Hnx(t1) + (pt(:,2)-p(t1,2)).*Hny(t1) + ... Hn(t2) + (pt(:,1)-p(t2,1)).*Hnx(t2) + (pt(:,2)-p(t2,2)).*Hny(t2) + ... Hn(t3) + (pt(:,1)-p(t3,1)).*Hnx(t3) + (pt(:,2)-p(t3,2)).*Hny(t3) )/3; % DEAL WITH CONTOURING LEVELS if length(N)==1 lev = linspace(max(Ht),min(Ht),N+1); num = N; else if (length(N)==2) && (N(1)==N(2)) lev = N(1); num = 1; else lev = sort(N); num = length(N); lev = lev(num:-1:1); end end % MAIN LOOP c = []; h = []; in = false(numt,1); vec = 1:numt; old = in; for v = 1:num % Loop over contouring levels % Find centroid values >= current level i = vec(Ht>=lev(v)); i = i(~old(i)); % Don't need to check triangles from higher levels in(i) = true; % Locate boundary edges in group bnd = [i; i; i]; % Just to alloc next = 1; for k = 1:length(i) ct = i(k); count = 0; for q = 1:3 % Loop through edges in ct ce = eINt(ct,q); if ~in(e2t(ce,1)) || ((e2t(ce,2)>0)&&~in(e2t(ce,2))) bnd(next) = ce; % Found bnd edge next = next+1; else count = count+1; % Count number of non-bnd edges in ct end end if count==3 % If 3 non-bnd edges ct must be in middle of group old(ct) = true; % & doesn't need to be checked for the next level end end numb = next-1; bnd(next:end) = []; % Skip to next lev if empty if numb==0 continue end % Place nodes approximately on contours by interpolating across bnd % edges t1 = e2t(bnd,1); t2 = e2t(bnd,2); ok = t2>0; % Get two points for interpolation. Always use t1 centroid and % use t2 centroid for internal edges and bnd midpoint for boundary % edges % 1st point is always t1 centroid H1 = Ht(t1); % Centroid value p1 = ( p(el(t1,1),:)+p(el(t1,2),:)+p(el(t1,3),:) )/3; % Centroid [x,y] % 2nd point is either t2 centroid or bnd edge midpoint i1 = t2(ok); % Temp indexing i2 = bnd(~ok); H2 = H1; H2(ok) = Ht(i1); % Centroid values internally H2(~ok) = ( Hn(e(i2,1))+Hn(e(i2,2)) )/2; % Edge values at boundary p2 = p1; p2(ok,:) = ( p(el(i1,1),:)+p(el(i1,2),:)+p(el(i1,3),:) )/3; % Centroid [x,y] internally p2(~ok,:) = ( p(e(i2,1),:)+p(e(i2,2),:) )/2; % Edge [x,y] at boundary % Linear interpolation r = (lev(v)-H1)./(H2-H1); penew = p1 + [r,r].*(p2-p1); % Do a temp connection between adjusted node & endpoint nodes in % ce so that the connectivity between neighbouring adjusted nodes % can be determined vecb = (1:numb)'; m = 2*vecb-1; c1 = 0*m; c2 = 0*m; c1(m) = e(bnd,1); c1(m+1) = e(bnd,2); c2(m) = vecb; c2(m+1) = vecb; % Sort connectivity to place connected edges in sucessive rows [c1,i] = sort(c1); c2 = c2(i); % Connect adjacent adjusted nodes k = 1; next = 1; while k<(2*numb) if c1(k)==c1(k+1) c1(next) = c2(k); c2(next) = c2(k+1); next = next+1; k = k+2; % Skip over connected edge else k = k+1; % Node has only 1 connection - will be picked up above end end ncc = next-1; c1(next:end) = []; c2(next:end) = []; % Plot the contours % If an output is required, extra sorting of the % contours is necessary for CLABEL to work. if nargout>0 % Form connectivity for the contour, connecting % its edges (rows in cc) with its vertices. ndx = repmat(1,nume,1); n2e = 0*penew; for k = 1:ncc % Vertices n1 = c1(k); n2 = c2(k); % Connectivity n2e(n1,ndx(n1)) = k; ndx(n1) = ndx(n1)+1; n2e(n2,ndx(n2)) = k; ndx(n2) = ndx(n2)+1; end bndn = n2e(:,2)==0; % Boundary nodes bnde = bndn(c1)|bndn(c2); % Boundary edges % Alloc some space tmpv = repmat(0,1,ncc); % Loop through the points at the current contour level (lev(v)) % Try to assemble the CS data structure introduced in "contours.m" % so that clabel will work. Assemble CS by "walking" around each % subcontour segment contiguously. ce = 1; start = ce; next = 2; cn = c2(1); flag = false(ncc,1); x = tmpv; x(1) = penew(c1(ce),1); y = tmpv; y(1) = penew(c1(ce),2); for k = 1:ncc % Checked this edge flag(ce) = true; % Add vertices to patch data x(next) = penew(cn,1); y(next) = penew(cn,2); next = next+1; % Find edge (that is not ce) joined to cn if ce==n2e(cn,1) ce = n2e(cn,2); else ce = n2e(cn,1); end % Check the new edge if (ce==0)||(ce==start)||(flag(ce)) % Plot current subcontour as a patch and save handles x = x(1:next-1); y = y(1:next-1); z = repmat(lev(v),1,next); h = [h; patch('Xdata',[x,NaN],'Ydata',[y,NaN],'Zdata',z, ... 'Cdata',z,'facecolor','none','edgecolor','flat')]; hold on % Update the CS data structure as per "contours.m" % so that clabel works c = horzcat(c,[lev(v), x; next-1, y]); if all(flag) % No more points at lev(v) break else % More points, but need to start a new subcontour % Find the unflagged edges edges = find(~flag); ce = edges(1); % Try to select a boundary edge so that we are % not repeatedly running into the boundary for i = 1:length(edges) if bnde(edges(i)) ce = edges(i); break end end % Reset counters start = ce; next = 2; % Get the non bnd node in ce if bndn(c2(ce)) cn = c1(ce); % New patch vectors x = tmpv; x(1) = penew(c2(ce),1); y = tmpv; y(1) = penew(c2(ce),2); else cn = c2(ce); % New patch vectors x = tmpv; x(1) = penew(c1(ce),1); y = tmpv; y(1) = penew(c1(ce),2); end end else % Find node (that is not cn) in ce if cn==c1(ce) cn = c2(ce); else cn = c1(ce); end end end else % Just plot the contours as is, this is faster... z = repmat(lev(v),2,ncc); z2=contourplotheight.*ones(size(z,1),size(z,2)); patch('Xdata',[penew(c1,1),penew(c2,1)]', ... 'Ydata',[penew(c1,2),penew(c2,2)]', ... 'Zdata',z2,'Cdata',z,'facecolor','none','edgecolor','flat','LineWidth',0.7); hold on end end % Assign outputs if needed if nargout>0 cout = c; hout = h; end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [e,eINt,e2t] = mkcon(p,t) numt = size(t,1); vect = 1:numt; % DETERMINE UNIQUE EDGES IN MESH e = [t(:,[1,2]); t(:,[2,3]); t(:,[3,1])]; % Edges - not unique vec = (1:size(e,1))'; % List of edge numbers [e,j,j] = unique(sort(e,2),'rows'); % Unique edges vec = vec(j); % Unique edge numbers eINt = [vec(vect), vec(vect+numt), vec(vect+2*numt)]; % Unique edges in each triangle % DETERMINE EDGE TO TRIANGLE CONNECTIVITY % Each row has two entries corresponding to the triangle numbers % associated with each edge. Boundary edges have one entry = 0. nume = size(e,1); e2t = repmat(0,nume,2); ndx = repmat(1,nume,1); for k = 1:numt % Edge in kth triangle e1 = eINt(k,1); e2 = eINt(k,2); e3 = eINt(k,3); % Edge 1 e2t(e1,ndx(e1)) = k; ndx(e1) = ndx(e1)+1; % Edge 2 e2t(e2,ndx(e2)) = k; ndx(e2) = ndx(e2)+1; % Edge 3 e2t(e3,ndx(e3)) = k; ndx(e3) = ndx(e3)+1; end return
github
janhavelka/Stochastic-Finite-Element-Method-master
position_figure.m
.m
Stochastic-Finite-Element-Method-master/functions/position_figure.m
1,958
utf_8
f5af9ed0a926dc7aa2830616a6cd90aa
% Similar to subplot(), position_figure() divides the screen into rectangular % panes to position figures in. % % Syntax: % position_figure(no_rows, no_columns, fig_no) % % where % 'no_rows' is the total number of figure-rows % 'no_columns' is the total number of figure-columns % 'fig_no' is the running number of the current figure % (numbered row-wise) % % Example: position_figure(2, 3, 4) divides the screen into 6 rectangles that % are arranged in 2 rows and 3 columns. The current figure is placed % in the lower left corner of the screen. % % See also SUBPLOT. % % Copyright Christoph Feenders, 2012 function position_figure(no_rows, no_columns, fig_no) % handle absurd parameters assert(no_rows > 0, 'Number of rows "no_rows" must be a positive integer.') assert(no_columns > 0, 'Number of colums "no_columns" must be a positive integer.') % determine figure-position in terms of row and column [col,row] = ind2sub([no_columns no_rows], mod(fig_no-1, no_rows*no_columns) + 1); % calculate figure position and dimensions according to screen scrsz = get(0, 'ScreenSize'); if strcmp(get(gcf, 'MenuBar'), 'figure') pos = [ 1 + scrsz(3)*( col-1 )/no_columns ... % left 6 + scrsz(4)*(no_rows-row)/no_rows ... % bottom scrsz(3)/no_columns - 1 ... % width scrsz(4)/no_rows - 87 ]; % height else % if plot-icons are switched off pos = [ 1 + scrsz(3)*( col-1 )/no_columns ... % left 6 + scrsz(4)*(no_rows-row)/no_rows ... % bottom scrsz(3)/no_columns - 1 ... % width scrsz(4)/no_rows - 33 ]; % height end % reposition and resize current figure set(gcf, 'Position', pos); end
github
janhavelka/Stochastic-Finite-Element-Method-master
getStiffness.m
.m
Stochastic-Finite-Element-Method-master/functions/mesh_basics/getStiffness.m
2,024
utf_8
95c79401069289772f0168e518bb5393
function K=getStiffness(MESH,lambda) % Jan Havelka ([email protected]) % Copyright 2016, Czech Technical University in Prague % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>. if size(lambda,2)==1 % isotropic case K=sparse(MESH.R_s,MESH.C_s,MESH.B_c.*lambda(:,ones(1,9))'); elseif size(lambda,2)==3 % anisotropic case phi=lambda(:,3); m1=lambda(:,1); m2=lambda(:,2); d1=cos(phi./180*pi).^2.*m1+sin(phi./180*pi).^2.*m2; d2=sin(phi./180*pi).^2.*m1+cos(phi./180*pi).^2.*m2; d3=cos(phi./180*pi).*sin(phi./180*pi).*m1-cos(phi./180*pi).*sin(phi./180*pi).*m2; % k_1=MESH.B(1:3,:).*repmat(d1,1,3)'+MESH.B(4:6,:).*repmat(d3,1,3)'; % k_1=MESH.B(1:3,:).*d1(:,[1 1 1])'+MESH.B(4:6,:).*d3(:,[1 1 1])'; k_1=bsxfun(@times,d1',MESH.B(1:3,:))+bsxfun(@times,d3',MESH.B(4:6,:)); % k_2=MESH.B(1:3,:).*repmat(d3,1,3)'+MESH.B(4:6,:).*repmat(d2,1,3)'; % k_2=MESH.B(1:3,:).*d3(:,[1 1 1])'+MESH.B(4:6,:).*d2(:,[1 1 1])'; k_2=bsxfun(@times,d3',MESH.B(1:3,:))+bsxfun(@times,d2',MESH.B(4:6,:)); % val=k_1([1 2 3 1 2 3 1 2 3],:).*MESH.B([1 1 1 2 2 2 3 3 3],:)+k_2([1 2 3 1 2 3 1 2 3],:).*MESH.B([4 4 4 5 5 5 6 6 6],:); val_dummy=k_1([1 1 1 2 2 3],:).*MESH.B([1 2 3 2 3 3],:)+k_2([1 1 1 2 2 3],:).*MESH.B([4 5 6 5 6 6],:); val=val_dummy([1 2 3 2 4 5 3 5 6],:); K=sparse(MESH.R_s,MESH.C_s,val); end
github
janhavelka/Stochastic-Finite-Element-Method-master
nwspgr.m
.m
Stochastic-Finite-Element-Method-master/Stochastic-Collocation/functions/nwspgr.m
55,365
utf_8
d201003f6a079cff4647bd2dda9defda
%***************************************************************************** %nwSpGr: Nodes and weights for numerical integration on sparse grids (Smolyak) %(c) 2007 Florian Heiss, Viktor Winschel %Nov 11, 2007 %***************************************************************************** %************************************************************************************ %nwspgr(): main function for generating nodes & weights for sparse grids intergration %Syntax: % [n w] = nwSpGr(type, dim, k, sym) %Input: % type = String for type of 1D integration rule: % "KPU": Nested rule for unweighted integral over [0,1] % "KPN": Nested rule for integral with Gaussian weight % "GQU": Gaussian quadrature for unweighted integral over [0,1] (Gauss-Legendre) % "GQN": Gaussian quadrature for integral with Gaussian weight (Gauss-Hermite) % func: any function name. Function must accept level l and % return nodes n and weights w for univariate quadrature rule with % polynomial exactness 2l-1 as [n w] = feval(func,level) % Example: If you have installed the CompEcon Toolbox of Paul Fackler and Mario Miranda % (http://www4.ncsu.edu/~pfackler/compecon/toolbox.html) % and you want to integrate with a lognormal weight function, you can use % nwSpGr('qnwlogn', dim, k) % dim : dimension of the integration problem % k : Accuracy level. The rule will be exact for polynomial up to total order 2k-1 % sym : (optional) only used for own 1D quadrature rule (type not "KPU",...). If % sym is supplied and not=0, the code will run faster but will % produce incorrect results if 1D quadrature rule is asymmetric %Output: % n = matrix of nodes with dim columns % w = row vector of corresponding weights %************************************************************************************* function [nodes, weights] = nwspgr(type, dim, k, sym) % interpret inputs if (nargin < 3); error('not enough input arguments') end builtinfct = (strcmp(type,'GQU') || strcmp(type,'GQN') || strcmp(type,'KPU') || strcmp(type,'KPN')); if (nargin == 3) if builtinfct; sym = true; else sym = false; end else sym = logical(sym); end % get 1D nodes & weights try n1D = cell(k,1); w1D = cell(k,1); R1D = zeros(1,k); for level=1:k [n w] = feval(type,level); % if user supplied symmetric 1D rule: keep only positive orthant if ~builtinfct && sym numnew = rows(n); [n sortvec] = sortrows(n); w = w(sortvec); n = n((floor(numnew/2)+1):numnew,:); w = w((floor(numnew/2)+1):numnew,:); end R1D(level) = length(w); n1D{level} = n; w1D{level} = w; end catch error('Error evaluating the 1D rule'); end % initialization minq = max(0,k-dim); maxq = k-1; nodes = []; weights = []; % outer loop over q for q = minq:maxq r = length(weights); bq = (-1)^(maxq-q) * nchoosek(dim-1,dim+q-k); % matrix of all rowvectors in N^D_{q} is = SpGrGetSeq(dim,dim+q); % preallocate new rows for nodes & weights Rq = prod(R1D(is),2); sRq = sum(Rq); nodes = [nodes ; zeros(sRq,dim)]; weights = [weights ; zeros(sRq,1)]; % inner loop collecting product rules for j=1:size(is,1) midx = is(j,:); [newn,neww] = SpGrKronProd(n1D(midx),w1D(midx)); nodes((r+1):(r+Rq(j)),:) = newn; weights((r+1):(r+Rq(j))) = bq .* neww; r = r + Rq(j); end % collect equal nodes: first sort [nodes sortvec] = sortrows(nodes); weights = weights(sortvec); keep = 1; lastkeep = 1; % then make a list of rows to keep and sum weights of equal nodes for j=2:size(nodes,1) if nodes(j,:)==nodes(j-1,:) weights(lastkeep)=weights(lastkeep)+weights(j); else lastkeep = j; keep = [keep ; j ]; end end % drop equal rows nodes = nodes(keep,:); weights = weights(keep); end % If symmetric rule: so far, it's for the positive orthant. Copy to other % orthants! if sym nr = length(weights); m = n1D{1}; for j=1:dim keep = zeros(nr,1); numnew = 0; for r=1:nr if nodes(r,j) ~= m numnew=numnew+1; keep(numnew)=r; end end if numnew>0 nodes = [nodes ; nodes(keep(1:numnew),:)]; nodes(nr+1:nr+numnew,j) = 2*m - nodes(nr+1:nr+numnew,j); weights = [weights ; weights(keep(1:numnew))]; nr=nr+numnew; end end % 3. final sorting [nodes sortvec] = sortrows(nodes); weights = weights(sortvec); end % normalize weights to account for rounding errors weights = weights / sum(weights); end %************************************************************************************** %SpGrGetSeq(): function for generating matrix of all rowvectors in N^D_{norm} %Syntax: % out = nwSpGr(d,norm) %Input: % d = dimension, will be #columns in output % norm = row sum of elements each of the rows has to have %Output: % out = matrix with d columns. Each row represents one vector with all elements >=1 % and the sum of elements == norm %************************************************************************************** function fs = SpGrGetSeq(d, norm) seq = zeros(1,d); a=norm-d; seq(1)=a; fs = seq; c=1; while seq(d)<a if (c==d) for i=(c-1):-1:1 c=i; if seq(i)~=0, break, end; end end seq(c) = seq(c)-1; c=c+1; seq(c) = a - sum(seq(1:(c-1))); if (c<d) seq((c+1):d)=zeros(1,d-c); end fs = [fs;seq]; end fs = fs+1; end %************************************************************************************ %SpGrKronProd(): function for generating tensor product quadrature rule %Syntax: % [nodes,weights] = SpGrKronProd(n1d,w1D) %Input: % n1D = cell array of 1D nodes % w1D = cell array of 1D weights %Output: % nodes = matrix of tensor product nodes % weights = vector of tensor product weights %************************************************************************************* function [nodes,weights] = SpGrKronProd(n1D,w1D) nodes = n1D{1} ; weights = w1D{1}; for j=2:length(n1D) newnodes = n1D{j}; nodes = [kron(nodes,ones(size(newnodes,1),1)) kron(ones(size(nodes,1),1),newnodes)]; weights = kron(weights,w1D{j}); end end function [n w] = GQU(l) switch l case 1 n = [5.0000000000000000e-001]; w = [1.0000000000000000e+000]; case 2 n = [7.8867513459481287e-001]; w = [5.0000000000000000e-001]; case 3 n = [5.0000000000000000e-001; 8.8729833462074170e-001]; w = [4.4444444444444570e-001; 2.7777777777777712e-001]; case 4 n = [6.6999052179242813e-001; 9.3056815579702623e-001]; w = [3.2607257743127516e-001; 1.7392742256872484e-001]; case 5 n = [5.0000000000000000e-001; 7.6923465505284150e-001; 9.5308992296933193e-001]; w = [2.8444444444444655e-001; 2.3931433524968501e-001; 1.1846344252809174e-001]; case 6 n = [6.1930959304159849e-001; 8.3060469323313235e-001; 9.6623475710157603e-001]; w = [2.3395696728634746e-001; 1.8038078652407072e-001; 8.5662246189581834e-002]; case 7 n = [5.0000000000000000e-001; 7.0292257568869854e-001; 8.7076559279969723e-001; 9.7455395617137919e-001]; w = [2.0897959183673620e-001; 1.9091502525256090e-001; 1.3985269574463935e-001; 6.4742483084431701e-002]; case 8 n = [5.9171732124782495e-001; 7.6276620495816450e-001; 8.9833323870681348e-001; 9.8014492824876809e-001]; w = [1.8134189168918213e-001; 1.5685332293894469e-001; 1.1119051722668793e-001; 5.0614268145185180e-002]; case 9 n = [5.0000000000000000e-001; 6.6212671170190451e-001; 8.0668571635029518e-001; 9.1801555366331788e-001; 9.8408011975381304e-001]; w = [1.6511967750063075e-001; 1.5617353852000226e-001; 1.3030534820146844e-001; 9.0324080347429253e-002; 4.0637194180784583e-002]; case 10 n = [5.7443716949081558e-001; 7.1669769706462361e-001; 8.3970478414951222e-001; 9.3253168334449232e-001; 9.8695326425858587e-001]; w = [1.4776211235737713e-001; 1.3463335965499873e-001; 1.0954318125799158e-001; 7.4725674575290599e-002; 3.3335672154342001e-002]; case 11 n = [5.0000000000000000e-001; 6.3477157797617245e-001; 7.5954806460340585e-001; 8.6507600278702468e-001; 9.4353129988404771e-001; 9.8911432907302843e-001]; w = [1.3646254338895086e-001; 1.3140227225512388e-001; 1.1659688229599563e-001; 9.3145105463867520e-002; 6.2790184732452625e-002; 2.7834283558084916e-002]; case 12 n = [5.6261670425573451e-001; 6.8391574949909006e-001; 7.9365897714330869e-001; 8.8495133709715235e-001; 9.5205862818523745e-001; 9.9078031712335957e-001]; w = [1.2457352290670189e-001; 1.1674626826917781e-001; 1.0158371336153328e-001; 8.0039164271673444e-002; 5.3469662997659276e-002; 2.3587668193254314e-002]; case 13 n = [5.0000000000000000e-001; 6.1522915797756739e-001; 7.2424637551822335e-001; 8.2117466972017006e-001; 9.0078904536665494e-001; 9.5879919961148907e-001; 9.9209152735929407e-001]; w = [1.1627577661543741e-001; 1.1314159013144903e-001; 1.0390802376844462e-001; 8.9072990380973202e-002; 6.9436755109893875e-002; 4.6060749918864378e-002; 2.0242002382656228e-002]; case 14 n = [5.5402747435367183e-001; 6.5955618446394482e-001; 7.5762431817907705e-001; 8.4364645240584268e-001; 9.1360065753488251e-001; 9.6421744183178681e-001; 9.9314190434840621e-001]; w = [1.0763192673157916e-001; 1.0259923186064811e-001; 9.2769198738969161e-002; 7.8601583579096995e-002; 6.0759285343951711e-002; 4.0079043579880291e-002; 1.7559730165874574e-002]; case 15 n = [5.0000000000000000e-001; 6.0059704699871730e-001; 6.9707567353878175e-001; 7.8548608630426942e-001; 8.6220886568008503e-001; 9.2410329170521366e-001; 9.6863669620035298e-001; 9.9399625901024269e-001]; w = [1.0128912096278091e-001; 9.9215742663556039e-002; 9.3080500007781286e-002; 8.3134602908497196e-002; 6.9785338963077315e-002; 5.3579610233586157e-002; 3.5183023744054159e-002; 1.5376620998057434e-002]; case 16 n = [5.4750625491881877e-001; 6.4080177538962946e-001; 7.2900838882861363e-001; 8.0893812220132189e-001; 8.7770220417750155e-001; 9.3281560119391593e-001; 9.7228751153661630e-001; 9.9470046749582497e-001]; w = [9.4725305227534431e-002; 9.1301707522462000e-002; 8.4578259697501462e-002; 7.4797994408288562e-002; 6.2314485627767105e-002; 4.7579255841246545e-002; 3.1126761969323954e-002; 1.3576229705875955e-002]; case 17 n = [5.0000000000000000e-001; 5.8924209074792389e-001; 6.7561588172693821e-001; 7.5634526854323847e-001; 8.2883557960834531e-001; 8.9075700194840068e-001; 9.4011957686349290e-001; 9.7533776088438384e-001; 9.9528773765720868e-001]; w = [8.9723235178103419e-002; 8.8281352683496447e-002; 8.4002051078225143e-002; 7.7022880538405308e-002; 6.7568184234262890e-002; 5.5941923596702053e-002; 4.2518074158589644e-002; 2.7729764686993612e-002; 1.2074151434273140e-002]; case 18 n = [5.4238750652086765e-001; 6.2594311284575277e-001; 7.0587558073142131e-001; 7.7988541553697377e-001; 8.4584352153017661e-001; 9.0185247948626157e-001; 9.4630123324877791e-001; 9.7791197478569880e-001; 9.9578258421046550e-001]; w = [8.4571191481571939e-002; 8.2138241872916504e-002; 7.7342337563132801e-002; 7.0321457335325452e-002; 6.1277603355739306e-002; 5.0471022053143716e-002; 3.8212865127444665e-002; 2.4857274447484968e-002; 1.0808006763240719e-002]; case 19 n = [5.0000000000000000e-001; 5.8017932282011264e-001; 6.5828204998181494e-001; 7.3228537068798050e-001; 8.0027265233084055e-001; 8.6048308866761469e-001; 9.1135732826857141e-001; 9.5157795180740901e-001; 9.8010407606741501e-001; 9.9620342192179212e-001]; w = [8.0527224924391946e-002; 7.9484421696977337e-002; 7.6383021032929960e-002; 7.1303351086803413e-002; 6.4376981269668232e-002; 5.5783322773667113e-002; 4.5745010811225124e-002; 3.4522271368820669e-002; 2.2407113382849821e-002; 9.7308941148624341e-003]; case 20 n = [5.3826326056674867e-001; 6.1389292557082253e-001; 6.8685304435770977e-001; 7.5543350097541362e-001; 8.1802684036325757e-001; 8.7316595323007540e-001; 9.1955848591110945e-001; 9.5611721412566297e-001; 9.8198596363895696e-001; 9.9656429959254744e-001]; w = [7.6376693565363113e-002; 7.4586493236301996e-002; 7.1048054659191187e-002; 6.5844319224588346e-002; 5.9097265980759248e-002; 5.0965059908620318e-002; 4.1638370788352433e-002; 3.1336024167054569e-002; 2.0300714900193556e-002; 8.8070035695753026e-003]; case 21 n = [5.0000000000000000e-001; 5.7278092708044759e-001; 6.4401065840120053e-001; 7.1217106010371944e-001; 7.7580941794360991e-001; 8.3356940209870611e-001; 8.8421998173783889e-001; 9.2668168229165859e-001; 9.6004966707520034e-001; 9.8361341928315316e-001; 9.9687608531019478e-001]; w = [7.3040566824845346e-002; 7.2262201994985134e-002; 6.9943697395536658e-002; 6.6134469316668845e-002; 6.0915708026864350e-002; 5.4398649583574356e-002; 4.6722211728016994e-002; 3.8050056814189707e-002; 2.8567212713428641e-002; 1.8476894885426285e-002; 8.0086141288864491e-003]; case 22 n = [5.3486963665986109e-001; 6.0393021334411068e-001; 6.7096791044604209e-001; 7.3467791899337853e-001; 7.9382020175345580e-001; 8.4724363159334137e-001; 8.9390840298960406e-001; 9.3290628886015003e-001; 9.6347838609358694e-001; 9.8503024891771429e-001; 9.9714729274119962e-001]; w = [6.9625936427816129e-002; 6.8270749173007697e-002; 6.5586752393531317e-002; 6.1626188405256251e-002; 5.6466148040269712e-002; 5.0207072221440600e-002; 4.2970803108533975e-002; 3.4898234212260300e-002; 2.6146667576341692e-002; 1.6887450792407110e-002; 7.3139976491353280e-003]; case 23 n = [5.0000000000000000e-001; 5.6662841214923310e-001; 6.3206784048517251e-001; 6.9515051901514546e-001; 7.5475073892300371e-001; 8.0980493788182306e-001; 8.5933068156597514e-001; 9.0244420080942001e-001; 9.3837617913522076e-001; 9.6648554341300807e-001; 9.8627123560905761e-001; 9.9738466749877608e-001]; w = [6.6827286093053176e-002; 6.6231019702348404e-002; 6.4452861094041150e-002; 6.1524542153364815e-002; 5.7498320111205814e-002; 5.2446045732270824e-002; 4.6457883030017563e-002; 3.9640705888359551e-002; 3.2116210704262994e-002; 2.4018835865542369e-002; 1.5494002928489686e-002; 6.7059297435702412e-003]; case 24 n = [5.3202844643130276e-001; 5.9555943373680820e-001; 6.5752133984808170e-001; 7.1689675381302254e-001; 7.7271073569441984e-001; 8.2404682596848777e-001; 8.7006209578927718e-001; 9.1000099298695147e-001; 9.4320776350220048e-001; 9.6913727600136634e-001; 9.8736427798565474e-001; 9.9759360999851066e-001]; w = [6.3969097673376246e-002; 6.2918728173414318e-002; 6.0835236463901793e-002; 5.7752834026862883e-002; 5.3722135057982914e-002; 4.8809326052057039e-002; 4.3095080765976693e-002; 3.6673240705540205e-002; 2.9649292457718385e-002; 2.2138719408709880e-002; 1.4265694314466934e-002; 6.1706148999928351e-003]; case 25 n = [5.0000000000000000e-001; 5.6143234630535521e-001; 6.2193344186049426e-001; 6.8058615290469393e-001; 7.3650136572285752e-001; 7.8883146512061142e-001; 8.3678318423673415e-001; 8.7962963151867890e-001; 9.1672131438041693e-001; 9.4749599893913761e-001; 9.7148728561448716e-001; 9.8833196072975871e-001; 9.9777848489524912e-001]; w = [6.1588026863357799e-002; 6.1121221495155122e-002; 5.9727881767892461e-002; 5.7429129572855862e-002; 5.4259812237131867e-002; 5.0267974533525363e-002; 4.5514130991481903e-002; 4.0070350167500532e-002; 3.4019166906178545e-002; 2.7452347987917691e-002; 2.0469578350653148e-002; 1.3177493307516108e-002; 5.6968992505125535e-003]; end end function [n w] = GQN(l) switch l case 1 n = [0.0000000000000000e+000]; w = [1.0000000000000000e+000]; case 2 n = [1.0000000000000002e+000]; w = [5.0000000000000000e-001]; case 3 n = [0.0000000000000000e+000; 1.7320508075688772e+000]; w = [6.6666666666666663e-001; 1.6666666666666674e-001]; case 4 n = [7.4196378430272591e-001; 2.3344142183389773e+000]; w = [4.5412414523193145e-001; 4.5875854768068498e-002]; case 5 n = [0.0000000000000000e+000; 1.3556261799742659e+000; 2.8569700138728056e+000]; w = [5.3333333333333344e-001; 2.2207592200561263e-001; 1.1257411327720691e-002]; case 6 n = [6.1670659019259422e-001; 1.8891758777537109e+000; 3.3242574335521193e+000]; w = [4.0882846955602919e-001; 8.8615746041914523e-002; 2.5557844020562431e-003]; case 7 n = [0.0000000000000000e+000; 1.1544053947399682e+000; 2.3667594107345415e+000; 3.7504397177257425e+000]; w = [4.5714285714285757e-001; 2.4012317860501250e-001; 3.0757123967586491e-002; 5.4826885597221875e-004]; case 8 n = [5.3907981135137517e-001; 1.6365190424351082e+000; 2.8024858612875416e+000; 4.1445471861258945e+000]; w = [3.7301225767907736e-001; 1.1723990766175897e-001; 9.6352201207882630e-003; 1.1261453837536784e-004]; case 9 n = [0.0000000000000000e+000; 1.0232556637891326e+000; 2.0768479786778302e+000; 3.2054290028564703e+000; 4.5127458633997826e+000]; w = [4.0634920634920685e-001; 2.4409750289493909e-001; 4.9916406765217969e-002; 2.7891413212317675e-003; 2.2345844007746563e-005]; case 10 n = [4.8493570751549764e-001; 1.4659890943911582e+000; 2.4843258416389546e+000; 3.5818234835519269e+000; 4.8594628283323127e+000]; w = [3.4464233493201940e-001; 1.3548370298026730e-001; 1.9111580500770317e-002; 7.5807093431221972e-004; 4.3106526307183106e-006]; case 11 n = [0.0000000000000000e+000; 9.2886899738106388e-001; 1.8760350201548459e+000; 2.8651231606436447e+000; 3.9361666071299775e+000; 5.1880012243748714e+000]; w = [3.6940836940836957e-001; 2.4224029987397003e-001; 6.6138746071057644e-002; 6.7202852355372697e-003; 1.9567193027122324e-004; 8.1218497902149036e-007]; case 12 n = [4.4440300194413901e-001; 1.3403751971516167e+000; 2.2594644510007993e+000; 3.2237098287700974e+000; 4.2718258479322815e+000; 5.5009017044677480e+000]; w = [3.2166436151283007e-001; 1.4696704804532995e-001; 2.9116687912364138e-002; 2.2033806875331849e-003; 4.8371849225906076e-005; 1.4999271676371597e-007]; case 13 n = [0.0000000000000000e+000; 8.5667949351945005e-001; 1.7254183795882394e+000; 2.6206899734322149e+000; 3.5634443802816347e+000; 4.5913984489365207e+000; 5.8001672523865011e+000]; w = [3.4099234099234149e-001; 2.3787152296413588e-001; 7.9168955860450141e-002; 1.1770560505996543e-002; 6.8123635044292619e-004; 1.1526596527333885e-005; 2.7226276428059039e-008]; case 14 n = [4.1259045795460181e-001; 1.2426889554854643e+000; 2.0883447457019444e+000; 2.9630365798386675e+000; 3.8869245750597696e+000; 4.8969363973455646e+000; 6.0874095469012914e+000]; w = [3.0263462681301945e-001; 1.5408333984251366e-001; 3.8650108824253432e-002; 4.4289191069474066e-003; 2.0033955376074381e-004; 2.6609913440676334e-006; 4.8681612577483872e-009]; case 15 n = [0.0000000000000000e+000; 7.9912906832454811e-001; 1.6067100690287301e+000; 2.4324368270097581e+000; 3.2890824243987664e+000; 4.1962077112690155e+000; 5.1900935913047821e+000; 6.3639478888298378e+000]; w = [3.1825951825951820e-001; 2.3246229360973222e-001; 8.9417795399844444e-002; 1.7365774492137616e-002; 1.5673575035499571e-003; 5.6421464051890157e-005; 5.9754195979205961e-007; 8.5896498996331805e-010]; case 16 n = [3.8676060450055738e-001; 1.1638291005549648e+000; 1.9519803457163336e+000; 2.7602450476307019e+000; 3.6008736241715487e+000; 4.4929553025200120e+000; 5.4722257059493433e+000; 6.6308781983931295e+000]; w = [2.8656852123801241e-001; 1.5833837275094925e-001; 4.7284752354014067e-002; 7.2669376011847411e-003; 5.2598492657390979e-004; 1.5300032162487286e-005; 1.3094732162868203e-007; 1.4978147231618314e-010]; case 17 n = [0.0000000000000000e+000; 7.5184260070389630e-001; 1.5098833077967408e+000; 2.2810194402529889e+000; 3.0737971753281941e+000; 3.9000657171980104e+000; 4.7785315896299840e+000; 5.7444600786594071e+000; 6.8891224398953330e+000]; w = [2.9953837012660756e-001; 2.2670630846897877e-001; 9.7406371162718081e-002; 2.3086657025711152e-002; 2.8589460622846499e-003; 1.6849143155133945e-004; 4.0126794479798725e-006; 2.8080161179305783e-008; 2.5843149193749151e-011]; case 18 n = [3.6524575550769767e-001; 1.0983955180915013e+000; 1.8397799215086457e+000; 2.5958336889112403e+000; 3.3747365357780907e+000; 4.1880202316294044e+000; 5.0540726854427405e+000; 6.0077459113595975e+000; 7.1394648491464796e+000]; w = [2.7278323465428789e-001; 1.6068530389351263e-001; 5.4896632480222654e-002; 1.0516517751941352e-002; 1.0654847962916496e-003; 5.1798961441161962e-005; 1.0215523976369816e-006; 5.9054884788365484e-009; 4.4165887693587078e-012]; case 19 n = [0.0000000000000000e+000; 7.1208504404237993e-001; 1.4288766760783731e+000; 2.1555027613169351e+000; 2.8980512765157536e+000; 3.6644165474506383e+000; 4.4658726268310316e+000; 5.3205363773360386e+000; 6.2628911565132519e+000; 7.3825790240304316e+000]; w = [2.8377319275152108e-001; 2.2094171219914366e-001; 1.0360365727614400e-001; 2.8666691030118496e-002; 4.5072354203420355e-003; 3.7850210941426759e-004; 1.5351145954666744e-005; 2.5322200320928681e-007; 1.2203708484474786e-009; 7.4828300540572308e-013]; case 20 n = [3.4696415708135592e-001; 1.0429453488027509e+000; 1.7452473208141270e+000; 2.4586636111723679e+000; 3.1890148165533900e+000; 3.9439673506573163e+000; 4.7345813340460552e+000; 5.5787388058932015e+000; 6.5105901570136551e+000; 7.6190485416797591e+000]; w = [2.6079306344955544e-001; 1.6173933398400026e-001; 6.1506372063976029e-002; 1.3997837447101043e-002; 1.8301031310804918e-003; 1.2882627996192898e-004; 4.4021210902308646e-006; 6.1274902599829597e-008; 2.4820623623151838e-010; 1.2578006724379305e-013]; case 21 n = [0.0000000000000000e+000; 6.7804569244064405e-001; 1.3597658232112304e+000; 2.0491024682571628e+000; 2.7505929810523733e+000; 3.4698466904753764e+000; 4.2143439816884216e+000; 4.9949639447820253e+000; 5.8293820073044706e+000; 6.7514447187174609e+000; 7.8493828951138225e+000]; w = [2.7026018357287707e-001; 2.1533371569505982e-001; 1.0839228562641938e-001; 3.3952729786542839e-002; 6.4396970514087768e-003; 7.0804779548153736e-004; 4.2192347425515866e-005; 1.2253548361482522e-006; 1.4506612844930740e-008; 4.9753686041217464e-011; 2.0989912195656652e-014]; case 22 n = [3.3117931571527381e-001; 9.9516242227121554e-001; 1.6641248391179071e+000; 2.3417599962877080e+000; 3.0324042278316763e+000; 3.7414963502665177e+000; 4.4763619773108685e+000; 5.2477244337144251e+000; 6.0730749511228979e+000; 6.9859804240188152e+000; 8.0740299840217116e+000]; w = [2.5024359658693501e-001; 1.6190629341367538e-001; 6.7196311428889891e-002; 1.7569072880805774e-002; 2.8087610475772107e-003; 2.6228330325596416e-004; 1.3345977126808712e-005; 3.3198537498140043e-007; 3.3665141594582109e-009; 9.8413789823460105e-012; 3.4794606478771428e-015]; case 23 n = [0.0000000000000000e+000; 6.4847115353449580e-001; 1.2998764683039790e+000; 1.9573275529334242e+000; 2.6243236340591820e+000; 3.3050400217529652e+000; 4.0047753217333044e+000; 4.7307241974514733e+000; 5.4934739864717947e+000; 6.3103498544483996e+000; 7.2146594350518622e+000; 8.2933860274173536e+000]; w = [2.5850974080883904e-001; 2.0995966957754261e-001; 1.1207338260262091e-001; 3.8867183703480947e-002; 8.5796783914656640e-003; 1.1676286374978613e-003; 9.3408186090312983e-005; 4.0899772449921549e-006; 8.7750624838617161e-008; 7.6708888623999076e-010; 1.9229353115677913e-012; 5.7323831678020873e-016]; case 24 n = [3.1737009662945231e-001; 9.5342192293210926e-001; 1.5934804298164202e+000; 2.2404678516917524e+000; 2.8977286432233140e+000; 3.5693067640735610e+000; 4.2603836050199053e+000; 4.9780413746391208e+000; 5.7327471752512009e+000; 6.5416750050986341e+000; 7.4378906660216630e+000; 8.5078035191952583e+000]; w = [2.4087011554664056e-001; 1.6145951286700025e-001; 7.2069364017178436e-002; 2.1126344408967029e-002; 3.9766089291813113e-003; 4.6471871877939763e-004; 3.2095005652745989e-005; 1.2176597454425830e-006; 2.2674616734804651e-008; 1.7186649279648690e-010; 3.7149741527624159e-013; 9.3901936890419202e-017]; case 25 n = [0.0000000000000000e+000; 6.2246227918607611e-001; 1.2473119756167892e+000; 1.8770583699478387e+000; 2.5144733039522058e+000; 3.1627756793881927e+000; 3.8259005699724917e+000; 4.5089299229672850e+000; 5.2188480936442794e+000; 5.9660146906067020e+000; 6.7674649638097168e+000; 7.6560379553930762e+000; 8.7175976783995885e+000]; w = [2.4816935117648548e-001; 2.0485102565034041e-001; 1.1488092430395164e-001; 4.3379970167644971e-002; 1.0856755991462316e-002; 1.7578504052637961e-003; 1.7776690692652660e-004; 1.0672194905202536e-005; 3.5301525602454978e-007; 5.7380238688993763e-009; 3.7911500004771871e-011; 7.1021030370039253e-014; 1.5300389979986825e-017]; end end function [n w] = KPU(l) switch l case 1 n = [5.0000000000000000e-001]; w = [1.0000000000000000e+000]; case 2 n = [5.0000000000000000e-001; 8.8729829999999998e-001]; w = [4.4444440000000002e-001; 2.7777780000000002e-001]; case 3 n = [5.0000000000000000e-001; 8.8729829999999998e-001]; w = [4.4444440000000002e-001; 2.7777780000000002e-001]; case 4 n = [5.0000000000000000e-001; 7.1712189999999998e-001; 8.8729829999999998e-001; 9.8024560000000005e-001]; w = [2.2545832254583223e-001; 2.0069872006987199e-001; 1.3424401342440134e-001; 5.2328105232810521e-002]; case 5 n = [5.0000000000000000e-001; 7.1712189999999998e-001; 8.8729829999999998e-001; 9.8024560000000005e-001]; w = [2.2545832254583223e-001; 2.0069872006987199e-001; 1.3424401342440134e-001; 5.2328105232810521e-002]; case 6 n = [5.0000000000000000e-001; 7.1712189999999998e-001; 8.8729829999999998e-001; 9.8024560000000005e-001]; w = [2.2545832254583223e-001; 2.0069872006987199e-001; 1.3424401342440134e-001; 5.2328105232810521e-002]; case 7 n = [5.0000000000000000e-001; 6.1169330000000000e-001; 7.1712189999999998e-001; 8.1055149999999998e-001; 8.8729829999999998e-001; 9.4422960000000000e-001; 9.8024560000000005e-001; 9.9691600000000002e-001]; w = [1.1275520000000000e-001; 1.0957840000000001e-001; 1.0031430000000000e-001; 8.5755999999999999e-002; 6.7207600000000006e-002; 4.6463600000000001e-002; 2.5801600000000001e-002; 8.5009000000000005e-003]; case 8 n = [5.0000000000000000e-001; 6.1169330000000000e-001; 7.1712189999999998e-001; 8.1055149999999998e-001; 8.8729829999999998e-001; 9.4422960000000000e-001; 9.8024560000000005e-001; 9.9691600000000002e-001]; w = [1.1275520000000000e-001; 1.0957840000000001e-001; 1.0031430000000000e-001; 8.5755999999999999e-002; 6.7207600000000006e-002; 4.6463600000000001e-002; 2.5801600000000001e-002; 8.5009000000000005e-003]; case 9 n = [5.0000000000000000e-001; 6.1169330000000000e-001; 7.1712189999999998e-001; 8.1055149999999998e-001; 8.8729829999999998e-001; 9.4422960000000000e-001; 9.8024560000000005e-001; 9.9691600000000002e-001]; w = [1.1275520000000000e-001; 1.0957840000000001e-001; 1.0031430000000000e-001; 8.5755999999999999e-002; 6.7207600000000006e-002; 4.6463600000000001e-002; 2.5801600000000001e-002; 8.5009000000000005e-003]; case 10 n = [5.0000000000000000e-001; 6.1169330000000000e-001; 7.1712189999999998e-001; 8.1055149999999998e-001; 8.8729829999999998e-001; 9.4422960000000000e-001; 9.8024560000000005e-001; 9.9691600000000002e-001]; w = [1.1275520000000000e-001; 1.0957840000000001e-001; 1.0031430000000000e-001; 8.5755999999999999e-002; 6.7207600000000006e-002; 4.6463600000000001e-002; 2.5801600000000001e-002; 8.5009000000000005e-003]; case 11 n = [5.0000000000000000e-001; 6.1169330000000000e-001; 7.1712189999999998e-001; 8.1055149999999998e-001; 8.8729829999999998e-001; 9.4422960000000000e-001; 9.8024560000000005e-001; 9.9691600000000002e-001]; w = [1.1275520000000000e-001; 1.0957840000000001e-001; 1.0031430000000000e-001; 8.5755999999999999e-002; 6.7207600000000006e-002; 4.6463600000000001e-002; 2.5801600000000001e-002; 8.5009000000000005e-003]; case 12 n = [5.0000000000000000e-001; 6.1169330000000000e-001; 7.1712189999999998e-001; 8.1055149999999998e-001; 8.8729829999999998e-001; 9.4422960000000000e-001; 9.8024560000000005e-001; 9.9691600000000002e-001]; w = [1.1275520000000000e-001; 1.0957840000000001e-001; 1.0031430000000000e-001; 8.5755999999999999e-002; 6.7207600000000006e-002; 4.6463600000000001e-002; 2.5801600000000001e-002; 8.5009000000000005e-003]; case 13 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 14 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 15 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 16 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 17 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 18 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 19 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 20 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 21 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 22 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 23 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 24 n = [5.0000000000000000e-001; 5.5624450000000003e-001; 6.1169330000000000e-001; 6.6556769999999998e-001; 7.1712189999999998e-001; 7.6565989999999995e-001; 8.1055149999999998e-001; 8.5124809999999995e-001; 8.8729829999999998e-001; 9.1836300000000004e-001; 9.4422960000000000e-001; 9.6482740000000000e-001; 9.8024560000000005e-001; 9.9076560000000002e-001; 9.9691600000000002e-001; 9.9954909999999997e-001]; w = [5.6377600000000014e-002; 5.5978400000000011e-002; 5.4789200000000017e-002; 5.2834900000000011e-002; 5.0157100000000017e-002; 4.6813600000000004e-002; 4.2878000000000006e-002; 3.8439800000000010e-002; 3.3603900000000006e-002; 2.8489800000000006e-002; 2.3231400000000003e-002; 1.7978600000000004e-002; 1.2903800000000003e-002; 8.2230000000000011e-003; 4.2173000000000011e-003; 1.2724000000000001e-003]; case 25 n = [5.0000000000000000e-001; 5.2817210000000003e-001; 5.5624450000000003e-001; 5.8411769999999996e-001; 6.1169330000000000e-001; 6.3887490000000002e-001; 6.6556769999999998e-001; 6.9167970000000001e-001; 7.1712189999999998e-001; 7.4180900000000005e-001; 7.6565989999999995e-001; 7.8859789999999996e-001; 8.1055149999999998e-001; 8.3145480000000005e-001; 8.5124809999999995e-001; 8.6987800000000004e-001; 8.8729829999999998e-001; 9.0347029999999995e-001; 9.1836300000000004e-001; 9.3195399999999995e-001; 9.4422960000000000e-001; 9.5518559999999997e-001; 9.6482740000000000e-001; 9.7317140000000002e-001; 9.8024560000000005e-001; 9.8609139999999995e-001; 9.9076560000000002e-001; 9.9434239999999996e-001; 9.9691600000000002e-001; 9.9860309999999997e-001; 9.9954909999999997e-001; 9.9993650000000001e-001]; w = [2.8188799999999993e-002; 2.8138799999999992e-002; 2.7989199999999992e-002; 2.7740699999999993e-002; 2.7394599999999995e-002; 2.6952699999999993e-002; 2.6417499999999993e-002; 2.5791599999999994e-002; 2.5078599999999993e-002; 2.4282199999999993e-002; 2.3406799999999995e-002; 2.2457299999999996e-002; 2.1438999999999996e-002; 2.0357799999999995e-002; 1.9219899999999998e-002; 1.8032199999999998e-002; 1.6801899999999998e-002; 1.5536799999999996e-002; 1.4244899999999996e-002; 1.2934799999999996e-002; 1.1615699999999998e-002; 1.0297099999999998e-002; 8.9892999999999987e-003; 7.7033999999999983e-003; 6.4518999999999983e-003; 5.2490999999999987e-003; 4.1114999999999988e-003; 3.0577999999999990e-003; 2.1087999999999997e-003; 1.2894999999999998e-003; 6.3259999999999987e-004; 1.8159999999999997e-004]; end end function [n w] = KPN(l) switch l case 1 n = [0.0000000000000000e+000]; w = [1.0000000000000000e+000]; case 2 n = [0.0000000000000000e+000; 1.7320508075688772e+000]; w = [6.6666666666666663e-001; 1.6666666666666666e-001]; case 3 n = [0.0000000000000000e+000; 1.7320508075688772e+000]; w = [6.6666666666666674e-001; 1.6666666666666666e-001]; case 4 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.7320508075688772e+000; 4.1849560176727323e+000]; w = [4.5874486825749189e-001; 1.3137860698313561e-001; 1.3855327472974924e-001; 6.9568415836913987e-004]; case 5 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.7320508075688772e+000; 2.8612795760570582e+000; 4.1849560176727323e+000]; w = [2.5396825396825407e-001; 2.7007432957793776e-001; 9.4850948509485125e-002; 7.9963254708935293e-003; 9.4269457556517470e-005]; case 6 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.7320508075688772e+000; 2.8612795760570582e+000; 4.1849560176727323e+000]; w = [2.5396825396825429e-001; 2.7007432957793776e-001; 9.4850948509485070e-002; 7.9963254708935293e-003; 9.4269457556517551e-005]; case 7 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.7320508075688772e+000; 2.8612795760570582e+000; 4.1849560176727323e+000]; w = [2.5396825396825418e-001; 2.7007432957793781e-001; 9.4850948509485014e-002; 7.9963254708935311e-003; 9.4269457556517592e-005]; case 8 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.7320508075688772e+000; 2.8612795760570582e+000; 4.1849560176727323e+000]; w = [2.5396825396825418e-001; 2.7007432957793781e-001; 9.4850948509485042e-002; 7.9963254708935276e-003; 9.4269457556517375e-005]; case 9 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 4.1849560176727323e+000; 5.1870160399136562e+000; 6.3633944943363696e+000]; w = [2.6692223033505302e-001; 2.5456123204171222e-001; 1.4192654826449365e-002; 8.8681002152028010e-002; 1.9656770938777492e-003; 7.0334802378279075e-003; 1.0563783615416941e-004; -8.2049207541509217e-007; 2.1136499505424257e-008]; case 10 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 4.1849560176727323e+000; 5.1870160399136562e+000; 6.3633944943363696e+000]; w = [3.0346719985420623e-001; 2.0832499164960877e-001; 6.1151730125247716e-002; 6.4096054686807610e-002; 1.8085234254798462e-002; -6.3372247933737571e-003; 2.8848804365067559e-003; 6.0123369459847997e-005; 6.0948087314689840e-007; 8.6296846022298632e-010]; case 11 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 4.1849560176727323e+000; 5.1870160399136562e+000; 6.3633944943363696e+000]; w = [3.0346719985420623e-001; 2.0832499164960872e-001; 6.1151730125247709e-002; 6.4096054686807541e-002; 1.8085234254798459e-002; -6.3372247933737545e-003; 2.8848804365067555e-003; 6.0123369459847922e-005; 6.0948087314689830e-007; 8.6296846022298839e-010]; case 12 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 4.1849560176727323e+000; 5.1870160399136562e+000; 6.3633944943363696e+000]; w = [3.0346719985420623e-001; 2.0832499164960872e-001; 6.1151730125247716e-002; 6.4096054686807624e-002; 1.8085234254798466e-002; -6.3372247933737545e-003; 2.8848804365067559e-003; 6.0123369459847841e-005; 6.0948087314689830e-007; 8.6296846022298963e-010]; case 13 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 4.1849560176727323e+000; 5.1870160399136562e+000; 6.3633944943363696e+000]; w = [3.0346719985420600e-001; 2.0832499164960883e-001; 6.1151730125247730e-002; 6.4096054686807638e-002; 1.8085234254798459e-002; -6.3372247933737580e-003; 2.8848804365067555e-003; 6.0123369459847868e-005; 6.0948087314689830e-007; 8.6296846022298756e-010]; case 14 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 4.1849560176727323e+000; 5.1870160399136562e+000; 6.3633944943363696e+000]; w = [3.0346719985420617e-001; 2.0832499164960874e-001; 6.1151730125247702e-002; 6.4096054686807596e-002; 1.8085234254798459e-002; -6.3372247933737563e-003; 2.8848804365067555e-003; 6.0123369459847936e-005; 6.0948087314689851e-007; 8.6296846022298322e-010]; case 15 n = [0.0000000000000000e+000; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 4.1849560176727323e+000; 5.1870160399136562e+000; 6.3633944943363696e+000]; w = [3.0346719985420612e-001; 2.0832499164960874e-001; 6.1151730125247723e-002; 6.4096054686807652e-002; 1.8085234254798459e-002; -6.3372247933737597e-003; 2.8848804365067563e-003; 6.0123369459848091e-005; 6.0948087314689851e-007; 8.6296846022298983e-010]; case 16 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 5.1870160399136562e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [2.5890005324151566e-001; 2.8128101540033167e-002; 1.9968863511734550e-001; 6.5417392836092561e-002; 6.1718532565867179e-002; 1.7608475581318002e-003; 1.6592492698936010e-002; -5.5610063068358157e-003; 2.7298430467334002e-003; 1.5044205390914219e-005; 5.9474961163931621e-005; 6.1435843232617913e-007; 7.9298267864869338e-010; 5.1158053105504208e-012; -1.4840835740298868e-013; 1.2618464280815118e-015]; case 17 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 5.1870160399136562e+000; 5.6981777684881099e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [1.3911022236338039e-001; 1.0387687125574284e-001; 1.7607598741571459e-001; 7.7443602746299481e-002; 5.4677556143463042e-002; 7.3530110204955076e-003; 1.1529247065398790e-002; -2.7712189007789243e-003; 2.1202259559596325e-003; 8.3236045295766745e-005; 5.5691158981081479e-005; 6.9086261179113738e-007; -1.3486017348542930e-008; 1.5542195992782658e-009; -1.9341305000880955e-011; 2.6640625166231651e-013; -9.9313913286822465e-016]; case 18 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 4.7364330859522967e+000; 5.1870160399136562e+000; 5.6981777684881099e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [5.1489450806921377e-004; 1.9176011588804434e-001; 1.4807083115521585e-001; 9.2364726716986353e-002; 4.5273685465150391e-002; 1.5673473751851151e-002; 3.1554462691875513e-003; 2.3113452403522071e-003; 8.1895392750226735e-004; 2.7524214116785131e-004; 3.5729348198975332e-005; 2.7342206801187888e-006; 2.4676421345798140e-007; 2.1394194479561062e-008; 4.6011760348655917e-010; 3.0972223576062995e-012; 5.4500412650638128e-015; 1.0541326582334014e-018]; case 19 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 4.7364330859522967e+000; 5.1870160399136562e+000; 5.6981777684881099e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [5.1489450806921377e-004; 1.9176011588804437e-001; 1.4807083115521585e-001; 9.2364726716986353e-002; 4.5273685465150523e-002; 1.5673473751851151e-002; 3.1554462691875604e-003; 2.3113452403522050e-003; 8.1895392750226670e-004; 2.7524214116785131e-004; 3.5729348198975447e-005; 2.7342206801187884e-006; 2.4676421345798140e-007; 2.1394194479561056e-008; 4.6011760348656077e-010; 3.0972223576063011e-012; 5.4500412650637663e-015; 1.0541326582337958e-018]; case 20 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 4.7364330859522967e+000; 5.1870160399136562e+000; 5.6981777684881099e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [5.1489450806925551e-004; 1.9176011588804440e-001; 1.4807083115521585e-001; 9.2364726716986298e-002; 4.5273685465150537e-002; 1.5673473751851155e-002; 3.1554462691875573e-003; 2.3113452403522080e-003; 8.1895392750226724e-004; 2.7524214116785137e-004; 3.5729348198975352e-005; 2.7342206801187888e-006; 2.4676421345798124e-007; 2.1394194479561056e-008; 4.6011760348656144e-010; 3.0972223576062963e-012; 5.4500412650638365e-015; 1.0541326582335402e-018]; case 21 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 4.7364330859522967e+000; 5.1870160399136562e+000; 5.6981777684881099e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [5.1489450806913744e-004; 1.9176011588804429e-001; 1.4807083115521594e-001; 9.2364726716986312e-002; 4.5273685465150391e-002; 1.5673473751851151e-002; 3.1554462691875565e-003; 2.3113452403522089e-003; 8.1895392750226670e-004; 2.7524214116785142e-004; 3.5729348198975285e-005; 2.7342206801187888e-006; 2.4676421345798119e-007; 2.1394194479561059e-008; 4.6011760348656594e-010; 3.0972223576062950e-012; 5.4500412650638696e-015; 1.0541326582332041e-018]; case 22 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 4.7364330859522967e+000; 5.1870160399136562e+000; 5.6981777684881099e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [5.1489450806903368e-004; 1.9176011588804448e-001; 1.4807083115521574e-001; 9.2364726716986423e-002; 4.5273685465150516e-002; 1.5673473751851161e-002; 3.1554462691875543e-003; 2.3113452403522063e-003; 8.1895392750226713e-004; 2.7524214116785164e-004; 3.5729348198975319e-005; 2.7342206801187905e-006; 2.4676421345798151e-007; 2.1394194479561082e-008; 4.6011760348656005e-010; 3.0972223576063043e-012; 5.4500412650637592e-015; 1.0541326582339926e-018]; case 23 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 4.7364330859522967e+000; 5.1870160399136562e+000; 5.6981777684881099e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [5.1489450806913755e-004; 1.9176011588804442e-001; 1.4807083115521577e-001; 9.2364726716986381e-002; 4.5273685465150468e-002; 1.5673473751851155e-002; 3.1554462691875560e-003; 2.3113452403522045e-003; 8.1895392750226572e-004; 2.7524214116785158e-004; 3.5729348198975298e-005; 2.7342206801187892e-006; 2.4676421345798129e-007; 2.1394194479561072e-008; 4.6011760348656103e-010; 3.0972223576062963e-012; 5.4500412650638207e-015; 1.0541326582338368e-018]; case 24 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 4.7364330859522967e+000; 5.1870160399136562e+000; 5.6981777684881099e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [5.1489450806914438e-004; 1.9176011588804442e-001; 1.4807083115521577e-001; 9.2364726716986340e-002; 4.5273685465150509e-002; 1.5673473751851155e-002; 3.1554462691875586e-003; 2.3113452403522058e-003; 8.1895392750226551e-004; 2.7524214116785142e-004; 3.5729348198975386e-005; 2.7342206801187884e-006; 2.4676421345798082e-007; 2.1394194479561059e-008; 4.6011760348656382e-010; 3.0972223576062942e-012; 5.4500412650638381e-015; 1.0541326582336941e-018]; case 25 n = [0.0000000000000000e+000; 2.4899229757996061e-001; 7.4109534999454085e-001; 1.2304236340273060e+000; 1.7320508075688772e+000; 2.2336260616769419e+000; 2.5960831150492023e+000; 2.8612795760570582e+000; 3.2053337944991944e+000; 3.6353185190372783e+000; 4.1849560176727323e+000; 4.7364330859522967e+000; 5.1870160399136562e+000; 5.6981777684881099e+000; 6.3633944943363696e+000; 7.1221067008046166e+000; 7.9807717985905606e+000; 9.0169397898903032e+000]; w = [5.1489450806919989e-004; 1.9176011588804437e-001; 1.4807083115521580e-001; 9.2364726716986395e-002; 4.5273685465150426e-002; 1.5673473751851158e-002; 3.1554462691875539e-003; 2.3113452403522054e-003; 8.1895392750226681e-004; 2.7524214116785142e-004; 3.5729348198975292e-005; 2.7342206801187884e-006; 2.4676421345798108e-007; 2.1394194479561056e-008; 4.6011760348655901e-010; 3.0972223576062975e-012; 5.4500412650638412e-015; 1.0541326582337527e-018]; end end
github
jlowenz/rrwm-master
makePointMatchingProblem.m
.m
rrwm-master/utils/makePointMatchingProblem.m
1,904
utf_8
d8b1523c4e12502cda5a4a603d756604
%% Make test problem function [ problem ] = makePointMatchingProblem( Set ) %% Get values from structure strNames = fieldnames(Set); for i = 1:length(strNames), eval([strNames{i} '= Set.' strNames{i} ';']); end %% Set number of nodes if bOutBoth, nP1 = nInlier + nOutlier; else nP1 = nInlier; end nP2 = nInlier + nOutlier; %% Generate Nodes switch typeDistribution case 'normal', P1 = randn(2, nP1); Pout = randn(2,nOutlier); % Points in Domain 1 case 'uniform', P1 = rand(2, nP1); Pout = rand(2,nOutlier); % Points in Domain 1 otherwise, disp(''); error('Insert Point Distribution'); end % point transformation matrix Mrot = [cos(transRotate) -sin(transRotate) ; sin(transRotate) cos(transRotate) ]; P2 = Mrot*P1*transScale+deformation*randn(2,nP1); % Points in Domain 2 if bOutBoth, P2(:,(nInlier+1):end) = Pout; else P2 = [P2 Pout]; end % permute graph sequence (prevent accidental good solution) if bPermute, seq = randperm(nP2); P2(:,seq) = P2; seq = seq(1:nP1); else seq = 1:nP1; end %0 P1 = P1'; P2 = P2'; %% 2nd Order Matrix E12 = ones(nP1,nP2); n12 = nnz(E12); [L12(:,1) L12(:,2)] = find(E12); [group1 group2] = make_group12(L12); E1 = ones(nP1); E2 = ones(nP2); [L1(:,1) L1(:,2)] = find(E1); [L2(:,1) L2(:,2)] = find(E2); G1 = P1(L1(:,1),:)-P1(L1(:,2),:); G2 = P2(L2(:,1),:)-P2(L2(:,2),:); G1 = sqrt(G1(:,1).^2+G1(:,2).^2); G2 = sqrt(G2(:,1).^2+G2(:,2).^2); G1 = reshape(G1, [nP1 nP1]); G2 = reshape(G2, [nP2 nP2]); M = (repmat(G1, nP2, nP2)-kron(G2,ones(nP1))).^2; M = exp(-M./scale_2D); M(1:(n12+1):end)=0; %% Ground Truth GT.seq = seq; GT.matrix = zeros(nP1, nP2); for i = 1:nP1, GT.matrix(i,seq(i)) = 1; end GT.bool = GT.matrix(:); %% Return the value problem.nP1 = nP1; problem.nP2 = nP2; problem.P1 = P1; problem.P2 = P2; problem.L12 = L12; problem.E12 = E12; problem.affinityMatrix = M; problem.group1 = group1; problem.group2 = group2; problem.GTbool = GT.bool; end
github
jlowenz/rrwm-master
wrapper_GM.m
.m
rrwm-master/utils/wrapper_GM.m
1,050
utf_8
1576ee070fa2b9ddbae721e3c9b98b1a
%% Makes current problem into Graph Matching form function [accuracy score time X Xraw] = wrapper_GM(method, cdata) % Make function evaluation script str = ['feval(@' func2str(method.fhandle)]; for j = 1:length(method.variable), str = [str ',cdata.' method.variable{j} ]; end if ~isempty(method.param), for i = 1:length(method.param), str = [str, ',method.param{' num2str(i) '}']; end; end str = [str, ')']; % Function evaluation & Excution time Check tic; Xraw = eval(str); time = toc; % Discretization by one-to-one mapping constraints if 1 % Hungarian assignment X = zeros(size(cdata.E12)); X(find(cdata.E12)) = Xraw; X = discretisationMatching_hungarian(X,cdata.E12); X = X(find(cdata.E12)); else % Greedy assignment X = greedyMapping(Xraw, cdata.group1, cdata.group2); end % Matching Score score = X'*cdata.affinityMatrix*X; % objective score function if length(cdata.GTbool) ~= length(cdata.affinityMatrix) accuracy = NaN; % Exception for no GT information else accuracy = (X(:)'*cdata.GTbool(:))/sum(cdata.GTbool); end
github
jlowenz/rrwm-master
RRWM.m
.m
rrwm-master/Methods/RRWM/RRWM.m
4,758
utf_8
ea71ece6a20675bf027025e76e265427
%% Implementaion of PageRank matching algortihm function [ X ] = RRWM( M, group1, group2, varargin) % MATLAB demo code of Reweighted Random Walks Graph Matching of ECCV 2010 % % Minsu Cho, Jungmin Lee, and Kyoung Mu Lee, % Reweighted Random Walks for Graph Matching, % Proc. European Conference on Computer Vision (ECCV), 2010 % http://cv.snu.ac.kr/research/~RRWM/ % % Please cite our work if you find this code useful in your research. % % written by Minsu Cho & Jungmin Lee, 2010, Seoul National University, Korea % http://cv.snu.ac.kr/~minsucho/ % http://cv.snu.ac.kr/~jungminlee/ % % % Date: 31/05/2013 % Version: 1.22 % % * Update report % This code is updated to be easily applied to any affinity matrix of candidate matches. % For image matching demo, combine this with some additional codes and data provided in our site. % ================================================================================================== % % input % M: affinity matrix % group1: conflicting match groups in domain 1 (size(M,1) x nGroup1) % group2: conflicting match groups in domain 2 (size(M,1) x nGroup2) % % e.g. find(group1(:,3)) represents the third goup of matches % sharing the same feature in domain1 % % output % X: steady state distribution of RRWM %% Default Parameters param = struct( ... 'c', 0.2, ... % prob. for walk or reweighted jump? 'amp_max', 30, ... % maximum value for amplification procedure 'iterMax', 300, ... % maximum value for amplification procedure 'thresConvergence', 1e-25, ... % convergence threshold for random walks 'tolC', 1e-3 ... % convergence threshold for the Sinkhorn method ); param = parseargs(param, varargin{:}); %% parameter structure -> parameter value strField = fieldnames(param); for i = 1:length(strField), eval([strField{i} '=param.' strField{i} ';']); end % get groups for bistochastic normalization [idx1 ID1] = make_groups(group1); [idx2 ID2] = make_groups(group2); if ID1(end) < ID2(end) [idx1 ID1 idx2 ID2 dumVal dumSize] = make_groups_slack(idx1, ID1, idx2, ID2); dumDim = 1; elseif ID1(end) > ID2(end) [idx2 ID2 idx1 ID1 dumVal dumSize] = make_groups_slack(idx2, ID2, idx1, ID1); dumDim = 2; else dumDim = 0; dumVal = 0; dumSize = 0; end idx1 = idx1-1; idx2 = idx2-1; % eliminate conflicting elements to prevent conflicting walks M = M.*~full(getConflictMatrix(group1, group2)); % note that this matrix is column-wise stochastic d = sum(M, 1); % degree : col sum maxD = max(d); Mo = M ./ maxD; % nomalize by the max degree % initialize answer nMatch = length(M); prev_score = ones(nMatch,1)/nMatch; % buffer for the previous score prev_score2 = prev_score; % buffer for the two iteration ahead prev_assign = ones(nMatch,1)/nMatch; % buffer for Sinkhorn result of prev_score bCont = 1; iter_i = 0; % for convergence check of power iteration thresConvergence2 = length(prev_score)*norm(M,1)*eps; la = prev_score'*M*prev_score; %% start main iteration while bCont && iter_i < iterMax iter_i = iter_i + 1; %% random walking with reweighted jumps cur_score = Mo * ( c*prev_score + (1-c)*prev_assign ); sumCurScore = sum(cur_score); % normalization of sum 1 if sumCurScore>0, cur_score = cur_score./sumCurScore; end %% update reweighted jumps cur_assign = cur_score; % attenuate small values and amplify large values amp_value = amp_max/ max(cur_assign); % compute amplification factor cur_assign = exp( amp_value*cur_assign ); % amplification % Sinkhorn method of iterative bistocastic normalizations X_slack = [cur_assign; dumVal*ones(dumSize,1)]; X_slack = mexBistocNormalize_match_slack(X_slack, int32(idx1), int32(ID1), int32(idx2), int32(ID2), tolC, dumDim, dumVal, int32(1000)); cur_assign = X_slack(1:nMatch); sumCurAssign = sum(cur_assign); % normalization of sum 1 if sumCurAssign>0, cur_assign = cur_assign./sumCurAssign; end %% Check the convergence of random walks if 1 diff1 = sum((cur_score-prev_score).^2); diff2 = sum((cur_score-prev_score2).^2); % to prevent oscillations diff_min = min(diff1, diff2); if diff_min < thresConvergence bCont = 0; end else normed_cur_score = cur_score/norm(cur_score); if norm(M*normed_cur_score - la*normed_cur_score,1) < thresConvergence2 bCont = 0; end la = normed_cur_score'*M*normed_cur_score; end prev_score2 = prev_score; prev_score = cur_score; prev_assign = cur_assign; end % end of main iteration X = cur_score; end
github
qingsongma/blend-master
make.m
.m
blend-master/tools/libsvm-3.22/matlab/make.m
888
utf_8
4a2ad69e765736f8cca8e3b721fb7ebd
% This make.m is for MATLAB and OCTAVE under Windows, Mac, and Unix function make() try % This part is for OCTAVE if (exist ('OCTAVE_VERSION', 'builtin')) mex libsvmread.c mex libsvmwrite.c mex -I.. svmtrain.c ../svm.cpp svm_model_matlab.c mex -I.. svmpredict.c ../svm.cpp svm_model_matlab.c % This part is for MATLAB % Add -largeArrayDims on 64-bit machines of MATLAB else mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmread.c mex CFLAGS="\$CFLAGS -std=c99" -largeArrayDims libsvmwrite.c mex CFLAGS="\$CFLAGS -std=c99" -I.. -largeArrayDims svmtrain.c ../svm.cpp svm_model_matlab.c mex CFLAGS="\$CFLAGS -std=c99" -I.. -largeArrayDims svmpredict.c ../svm.cpp svm_model_matlab.c end catch err fprintf('Error: %s failed (line %d)\n', err.stack(1).file, err.stack(1).line); disp(err.message); fprintf('=> Please check README for detailed instructions.\n'); end
github
kertansul/caffe-segnet-cudnn5-master
classification_demo.m
.m
caffe-segnet-cudnn5-master/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
ncohn/Windsurf-master
Windsurf_Run_Batch.m
.m
Windsurf-master/Windsurf_Run_Batch.m
261
utf_8
55529be4c74bf42a0cc4951e09301793
%Windsurf_Run_Batch.m - Code which allows to run multiple simulations at once via parfor loop %Created By: N. Cohn, Oregon State University function XBCDM_Run_Batch(Directory) load([Directory, filesep, 'windsurf_setup.mat']); Windsurf_Run; end
github
ncohn/Windsurf-master
Windsurf_BeachNourishment.m
.m
Windsurf-master/Windsurf_BeachNourishment.m
3,484
utf_8
13189e5a9562fdfceaee5f6b8627766e
%Windsurf_BeachNourishment %Code for modifying the beach profile based on volume (type 1), contour (type 2), or fixed time (type 3) changes at some %fixed time intervals based on specified user inputs % %Created By: N. Cohn, Oregon State University if project.flag.nourishment ~= 0 && run_number > 1 %type 1 = volume consideration if project.flag.nourishment == 1 %nourish based on a volume lost threshold [NOT YET TESTED] %find volume in between specified contours ivol = find(run.z>=nourishment.vol.cont1 & run.z<= nourishment.vol.cont2); zvol = run.z - nourishment.vol.cont1; diffX = diff(grids.XGrid); diffX = [diffX diffX(end)]; zvol = zvol.* diffX; zvol = sum(zvol(ivol)); if run_number <= 2 init_vol = zvol; end volchange = zvol-init_vol; if volchange< nourishment.vol.threshold %should track nourishment time schedule nourishment_time_series(run_number) = 1; %only nourish if beyond the time scale needed iuse = [run_number-nourishment.delay]:run_number; iuse = iuse(find(iuse>0)); if nansum(nourishment_time_series(iuse)) > nourishment.delay nourishment_time_series(iuse) = NaN; run.z = nourish(run, grids, nourishment); end end elseif project.flag.nourishment == 2 %nourish based on a contour retreat threshold [NOT YET TESTED] initialX = interp1(XZfinal(:,2), XZfinal(:,1), nourishment.cont.elev); currentX = interp1(run.z, XZfinal(:,1), nourishment.cont.elev); if [initialX-currentX]<-nourishment.cont.maxretreat %only nourish if beyond the time scale needed iuse = [run_number-nourishment.delay]:run_number; iuse = iuse(find(iuse>0)); if nansum(nourishment_time_series(iuse)) > nourishment.delay nourishment_time_series(iuse) = NaN; run.z = nourish(run, grids, nourishment); end end elseif project.flag.nourishment == 3 %nourish at fixed times go_nourish = find(nourishment.times == run_number); if numel(go_nourish) == 1 run.z = nourish(run, grids, nourishment); end clear go_nourish end end function z_out = nourish(run, grids, nourishment) %provide new morphologic profile based on nourishment guidelines %define geometry x = grids.XGrid(:); z = run.z(:); iuse = find(z>nourishment.minZ & z<=nourishment.maxZ); dx = abs(diff(x)); dx = [dx(1); dx(:)]; dx = dx(:); addVol = nourishment.volume; %make all the elevations such that it is appeoximately a flat top addVals = (nourishment.maxZ - z(iuse)).*dx(iuse); %alternative approach for adding sine wave %addVals = sin(0:pi/(numel(iuse)-1):pi).dx(iuse)'; %remove mass from seaward most cells so that is not beyond angle of repose modVals = ones(size(addVals)); entries = round(numel(modVals)/3); if entries>3 modVals(1:entries) = linspace(0,1,entries); end %fix so that the appropriate volume is added addVals = addVals.*modVals; addVals = ((addVals./dx(iuse))./nansum(addVals)).*addVol; %correct the z value z(iuse) = z(iuse)+addVals; %output values z_out = z; end