Structured data fusion: examples¶
In Structured data fusion the elements in the domain specific language (DSL) used for modeling structured data fusion problems are explained. The three key ingredients of an SDF model are the definition of (1) the variables, (2) the factors as transformed variables and (3) the data sets and which factors to use in their factorizations. Here, different examples illustrate how the SDF framework can be used to model different types of constraints, structures and couplings between datasets. These examples should quickly give a good idea of how the DSL can be used to create new models. Reading Structured data fusion remains highly recommended even if a more example based approach is favored by the user.
Example 1: nonnegative symmetric CPD¶
As a first example, the nonnegative symmetric CPD of an incomplete tensor \(\ten{T}\) is computed. First, generate the tensor
% Generate a nonnegative symmetric CPD.
I = 15;
R = 4;
U = rand(I,R);
U = {U,U,U};
T = cpdgen(U);
% Remove 10% of entries.
T(randperm(numel(T),round(0.1*numel(T)))) = NaN;
% Format as incomplete tensor.
T = fmt(T);
Next, create a structure model which defines the variables of the SDF
problem. It is recommended to start a new model with
model = struct;
This clears previous definitions of variables, factors and factorizations. Forgetting to clear a previous model is a common source of errors.
In this case, there is only one variable and its size is equal to that
of the factor U. The variables field defines the parameters that are
optimized, and is also used to initialize the SDF algorithm.
% Define model variables.
model.variables.u = randn(I,R);
Here, the variable u is defined as a Matlab array. It is also perfectly
valid to define variables as (nested) cell arrays of arrays, if desired. Now we
need to define the factors. There is only one factor in this CPD, which we
define as a transformation of the variable u. More specifically, we
require the factor to be nonnegative:
% Define model factors as transformed variables.
model.factors.U = {'u',@struct_nonneg};
The factor U is built taking the variable u, and applying the
transformation @struct_nonneg. In fact, factors can be built with a much
more complex structure using subfactors, see the following examples for details.
Finally, we define the data set to be factorized and which factors to use:
% Define model factorizations.
model.factorizations.myfac.data = T;
model.factorizations.myfac.cpd = {'U','U','U'};
Each factorization in the SDF problem should be given a new name. In this case
there is only one (named) factorization called myfac and it contains two
fields. The first is data and specifies the tensor to be factorized. The
second should be either cpd, cpdi, btd, lmlra or ll1
depending on which model to use, and define the factors to be used in the
decomposition (see Factorization and regularization types).
Note that it is not necessary to use fields to describe the names of the variables and factors. Instead, one may also create cell arrays of variables and factors and use indices to refer to them. In this format, the model would be written as
% Equivalent SDF model without using names for variables and factors.
model.variables = { randn(I,R) };
model.factors = { {1,@struct_nonneg} };
model.factorizations.myfac.data = T;
model.factorizations.myfac.cpd = {1,1,1};
Since Tensorlab 3.0, the language parser is a lot more forgiving w.r.t.
braces {}. Missing braces are added automatically if this can be done
unambiguously. This is called auto-wrapping. After removing superfluous
braces, the model becomes:
% Equivalent SDF model without using names for variables and factors.
model.variables = randn(I,R); % only if there is a single variable
model.factors = {1,@struct_nonneg};
model.factorizations.myfac.data = T;
model.factorizations.myfac.cpd = ones(1,3); % arrays are also allowed
The resulting model can be checked using the sdf_check(model, 'print')
function:
Factor Size Comment
------------------------------------------------------------------------
1 [15x4]
Factorization Type Factors Comments
------------------------------------------------------------------------
myfac (id = 1) cpd 1,1,1
By clicking on the 1 in the Matlab Command Window, it can be seen that
nonnegativity has indeed been imposed (click the 1 and Factor links
to investigate this):
Expansion of factor 1 (view):
(1,1) 1 [15x4] struct_nonneg Factor [15x4]
By clicking 1 or Factor, its value becomes available as ans, which
can be useful, for example, if we wish to plot an intermediate result. For
example to check if all entries in the factor are positive, after clicking
Factor, we can use all(ans(:)) >= 0.
The model can now be solved with one of the two families of algorithms for SDF
problems: sdf_minf and sdf_nls. Their first output contains the
optimized variables and factors in the fields variables and factors,
respectively:
% Solve the SDF problem.
options.Display = 5; % View convergence progress every 5 iterations.
sol = sdf_nls(model,options);
sol.variables
sol.factors
If no nonnegativity is required, and hence only symmetry is used, the
ccpd_nls and ccpd_minf methods can be used. For unstructured coupled
and/or symmetric problems, these dedicated methods often behave better
numerically:
model = struct;
model.variables = rand(I,R);
model.factors = 1;
model.factorizations.unconst.data = T;
model.factorizations.unconst.cpd = [1 1 1];
Ures = ccpd_nls(model, 'Display', 10);
In case a tensor is symmetric in all modes, it can be useful to introduce an additional dimension to take scaling and signs of the rank-1 terms into account. This extra dimension is a vector of size \(1\times R\). For example a fourth-order fully symmetric real tensor having negative entries on the diagonal cannot be modeled without the extra dimension. With the extra dimension, the problem can be modeled as
model = struct;
model.variables.A = randn(I, R);
model.variables.extra = randn(1, R);
model.factors.A = 'A';
model.factors.E = 'extra';
model.factorizations.symm.data = T;
model.factorizations.symm.cpd = {'A', 'A', 'A', 'A', 'E'};
Example 2: structured coupled matrix factorization¶
Let \(\mat{X}\) and \(\mat{Y}\) be square matrices of dimension \(N\times N\) which we wish to jointly factorize as \(\mat{U}\cdot \mat{\Lambda}_X\cdot \mat{V}^{\T}\) and \(\mat{U}\cdot \mat{\Lambda}_Y\cdot \mat{W}^{\T}\), respectively. The factor \(\mat{U}\) is common to both \(\mat{X}\) and \(\mat{Y}\), and the extent to which the columns are shared is given by the absolute values of the diagonal matrices \(\mat{\Lambda}_X\) and \(\mat{\Lambda}_Y\). Furthermore, we will require the entries of \(\mat{W}\) to lie in the interval (-3,5) and impose a Vandermonde structure on \(\mat{V}\), so that
with \(d = R-1\) and \(R\) the number of terms. Note that \(\mat{V}\) depends only on a so-called generator vector \(\vec{v} = \scriptsize\begin{bmatrix}v_1 & \cdots & v_N\end{bmatrix}^{\T}\).
First, the matrices \(\mat{X}\) and \(\mat{Y}\) are created:
% Generate structured coupled matrices X and Y.
N = 10;
R = 4;
U = randn(N,R);
V = bsxfun(@power,randn(N,1),0:R-1); % Vandermonde factor.
W = rand(N,R)*(5+3)-3; % Entries in (-3,5).
lambdaX = 0:3; % X does not share first column of U.
lambdaY = 3:-1:0; % Y does not share last column of U.
X = U*diag(lambdaX)*V.';
Y = U*diag(lambdaY)*W.';
Then, we define a structure containing the model variables
% Define model variables.
model = struct;
model.variables.u = randn(N,R);
model.variables.v = randn(N,1);
model.variables.w = randn(N,R);
model.variables.lambdaX = randn(1,R);
model.variables.lambdaY = randn(1,R);
Here, the variables are the matrices \(\mat{U}\) and \(\mat{W}\), the generator vector \(\vec{v}\) for the Vandermonde matrix \(\mat{V}\) and the diagonals \(\vec{\lambda}_X\) and \(\vec{\lambda}_Y\). The model assumes that \(\mat{X}\) and \(\mat{Y}\) share at most \(R=4\) vectors in \(\mat{U}\). Next, we define the factors as transformed variables with
% Define the structure for V by creating an anonymous function which stores deg.
deg = [0 R-1]; % Bounds for d: first column is z^0 and last column z^(R-1)
vanderm = @(z,task)struct_vander(z,task,deg);
% Define the structure for W by creating an anonymous function which stores rng.
rng = [-3 5];
sigmoid = @(z,task)struct_sigmoid(z,task,rng);
% Define model factors as transformed variables.
model.factors.U = 'u';
model.factors.V = {'v',vanderm};
model.factors.W = {'w',sigmoid};
model.factors.LX = 'lambdaX';
model.factors.LY = 'lambdaY';
In this example the transformations depend on parameters. To pass along these
parameters, we encapsulate them inside anonymous functions. For example, the
sigmoid transformation struct_sigmoid requires the interval rng to
constrain its argument in.
Now we add the two factorizations of \(\mat{X}\) and \(\mat{Y}\) to the model with
% Define the joint factorization of the matrices X and Y.
model.factorizations.xfac.data = X;
model.factorizations.xfac.cpd = {'U','V','LX'};
model.factorizations.yfac.data = Y;
model.factorizations.yfac.cpd = {'U','W','LY'};
Here, we use the CPD to describe the factorizations \(\mat{X} =
\mat{U}\cdot \mat{\Lambda}_X\cdot \mat{V}^{\T}\) and \(\mat{Y} =
\mat{U}\cdot \mat{\Lambda}_Y\cdot \mat{W}^{\T}\) by associating the factor
matrices \(\vec{\lambda}_X\) and \(\vec{\lambda}_Y\), which are row
vectors, with the third dimension of \(\mat{X}\) and \(\mat{Y}\).
Alternatively, we could describe the two factorizations with the BTD model by
imposing the core tensor to be a diagonal matrix with struct_diag, but this
is less efficient than using the CPD model.
The SDF problem can now be solved with
% Solve the SDF problem.
options.Display = 10; % View convergence progress every 10 iterations.
options.TolFun = 1e-9; % Stop earlier.
options.CGMaxIter = 500; % Recommended if structure/coupling is imposed
[sol, output] = sdf_nls(model,options);
sol.variables
sol.factors
Although the algorithm converges, it usually does not converge to the solution
we used to generate the data. Nevertheless a good relative error is obtained
(see output.relerr). This may indicate that the solution is not unique (in
contrast to the example in Example 1: nonnegative symmetric CPD).
Example 3: an orthogonal factor¶
We show how to compute a simple CPD in which one of the factors is constrained
to have orthonormal colums. To this end, we will create a variable
\(\vec{q}\) that parameterizes a matrix with orthonormal columns
\(\mat{Q}\). The structure struct_orth can then be used to transform the
variable \(\vec{q}\) into the factor \(\mat{Q}\). First, we construct
the data for the problem:
% Generate CPD, where one factor has orthonormal columns.
I = 15;
R = 4;
U = cpd_rnd([I I I],R);
U{1} = orth(U{1}); % Enforce orthonormal columns.
T = cpdgen(U);
The help information provided by struct_orth tells us that the variable
\(\vec{q}\) should be a vector of length \(IR-0.5R(R-1)\). To transform
\(\vec{q}\) into a matrix with orthonormal columns, we need to pass the size
of \(\mat{Q}\) to struct_orth. One way to do this is with an anonymous
function, as shown below. Now we are ready to define and solve the SDF problem:
% Clear previous model
model = struct;
% Define model variables.
model.variables.q = randn(I*R-0.5*R*(R-1),1);
model.variables.b = randn(I,R);
model.variables.c = randn(I,R);
% Define a function that transforms q into Q.
% This anonymous function stores the size of Q as its last argument.
orthq = @(z,task)struct_orth(z,task,[I R]);
% Define model factors.
model.factors.Q = {'q',orthq}; % Create Q as orthq(q).
model.factors.B = 'b';
model.factors.C = 'c';
% Define model factorizations.
model.factorizations.myfac.data = T;
model.factorizations.myfac.cpd = {'Q','B','C'};
sdf_check(model, 'print');
Factor Size Comment
------------------------------------------------------------------------
Q [15x4]
B [15x4]
C [15x4]
Factorization Type Factors Comments
------------------------------------------------------------------------
myfac (id = 1) cpd Q,B,C
The factor Q is indeed a \(15\times4\) matrix. By clicking Q in the
Matlab Command Window, and then view, we can indeed verify the orthogonality
of the factors, as it becomes available as ans:
Q = ans;
Q'*Q
ans =
1.0000 0.0000 -0.0000 0.0000
0.0000 1.0000 -0.0000 0.0000
-0.0000 -0.0000 1.0000 -0.0000
0.0000 0.0000 -0.0000 1.0000
The model can now be computed, e.g., using the sdf_nls solver:
% Solve the SDF problem.
sol = sdf_nls(model, 'Display', 10);
% Check that the result Q indeed has orthonormal columns
sol.factors.Q'*sol.factors.Q
Example 4: decomposition in multilinear rank-\((L_r,L_r,1)\) terms¶
In this example, the decomposition of a tensor \(\ten{T}\) into multilinear rank-\((L_r,L_r,1)\) terms is illustrated. This decomposition can be seen as a special case of the BTD, i.e., having an identity matrix as core, or as a special case of the CPD, i.e., some rank-1 terms have an identical vector in the third mode. More concretely, we want to compute a multilinear rank-\((L_r,L_r,1)\) BTD [25][26][27] of a tensor \(\ten{T}\) in \(R\) terms, i.e.,
where \(\vec{c}_r\) are vectors and \(\mat{A}_r\) and \(\mat{B}_r\)
have \(L_r\) columns. In the unconstrained and uncoupled case, the
decomposition into rank-\((L_r,L_r,1)\) terms can be computed using the
specialized ll1 routines (see Decomposition in multilinear rank- terms). In this example, three ways
to compute this decomposition are shown:
- using the
ll1factorization type, - using the BTD formulation, and
- using the CPD formulation by imposing that some vectors are equal using
struct_LL1.
The ll1 factorization type has been added in Tensorlab 3.0, and is the
recommended way to compute a decomposition in multilinear
rank-\((L_r,L_r,1)\) terms in the constrained and/or coupled case. When no
constraints or coupling are needed, the ll1 method can be used.
Example 4a: using the ll1 factorization type¶
We use a decomposition into multilinear rank-\((L_r,L_r,1)\) terms with
\(L=[3, 2]\) in this example. In the CPD formulation of this decomposition,
the different factors \(\mat{A}_1\) and \(\mat{A}_2\) are concatenated
along the second mode, i.e., in Matlab code we have A = [A1 A2]. The same
holds for \(\mat{B}\) and \(\mat{C}\). Hence, factors A and B
have sum(L) columns, while C has length(L) columns (for more
information see Decomposition in multilinear rank- terms). To generate the data the ll1_rnd routine
can be used:
size_tens = [10 11 12];
L = [3 2];
U0 = ll1_rnd(size_tens, L);
T = ll1gen(U0);
For the unconstrained decomposition into multilinear rank-\((L_r,L_r,1)\)
terms, the ll1, ll1_minf and ll1_nls routines can be used. Here we
illustrate the ll1 factorization type in the SDF framework, as this can be
useful if some factors have structure, or are shared between
factorizations. The decomposition can then be modeled as follows:
L = [3 2];
model = struct;
model.variables.A = randn(size_tens(1), sum(L));
model.variables.B = randn(size_tens(2), sum(L));
model.variables.C = randn(size_tens(3), length(L));
model.factors.A = 'A';
model.factors.B = 'B';
model.factors.C = 'C';
model.factorizations.myll1.data = T;
model.factorizations.myll1.ll1 = {'A', 'B', 'C'};
model.factorizations.myll1.L = L;
The ll1 factorization type only accepts the CPD format for the decomposition
into multilinear rank-\((L_r,L_r,1)\) terms. The L field defines the
different terms. The model can again be solved using the sdf_nls and
sdf_minf solvers.
Example 4b: using the btd factorization type¶
The decomposition into rank-\((L_r,L_r,1)\) terms is a special case of a block term decomposition (BTD), in which the core tensors \(\ten{S}_r\) are matrices of size \(L_r\times L_r \times 1\). The decomposition then takes the form:
By default, ll1_rnd returns a decomposition into multilinear
rank-\((L_r,L_r,1)\) terms in the BTD format. By setting the
OutputFormat option to 'cpd' the CPD format is obtained. The btd
factorization type can be used as follows:
% Define rank-(Lr,Lr,1) BTD model using the BTD.
model = struct;
model.variables.A1 = randn(size_tens(1),L1);
model.variables.B1 = randn(size_tens(2),L1);
model.variables.c1 = randn(size_tens(3),1);
model.variables.S1 = randn(L1,L1,1);
model.variables.A2 = randn(size_tens(1),L2);
model.variables.B2 = randn(size_tens(2),L2);
model.variables.c2 = randn(size_tens(3),1);
model.variables.S2 = randn(L2,L2,1);
model.factors = { 'A1','B1','c1','S1', 'A2','B2','c2','S2' };
model.factorizations.mybtd.data = T;
model.factorizations.mybtd.btd = {{1,2,3,4},{5,6,7,8}};
where, for the sake of brevity, we have used indexed factors. The model can be shortened even further by making use of indexed definitions and references (see Structured data fusion: advanced concepts):
model = struct;
U0 = ll1_rnd(size_tens, L); % Initial guess in BTD format
% Convert {{U{1}{1},U{1}{2},...}, {U{2}{1},...},...}
% to {U{1}{1},U{1}{2},...,U{2}{1},...}
U0 = cat(2, U0{:});
model.variables = U0;
model.factors = 1:8;
model.factorizations.mybtd.data = T;
model.factorizations.mybtd.btd = {1:4, 5:8};
Note that in SDF the BTD is specified in the same format as for other BTD
algorithms, e.g., btd_nls and btd_rnd, i.e., a nested cell of cells is
used, but now references to factors are used instead of factor matrices and
tensors. Thanks to auto-wrapping, many of the braces can be omitted, though. The
BTD can then be computed by
% Solve the SDF problem.
options.Display = 10; % View convergence progress every 10 iterations.
sol = sdf_nls(model,options);
sol.variables
sol.factors
Example 4c: using the cpd factorization type¶
The third way to compute a decomposition into multilinear rank-\((L_r,L_r,1)\) terms uses a CPD. In our example, the decomposition can be written as:
Here, the third CPD factor matrix C looks like
[repmat(c1,1,L1) repmat(c2,1,L2)], while the first two are [A1 A2]
and [B1 B2], respectively. These factor matrices are all built out of
subfactor matrices, which we can implement in the DSL as follows:
% Define rank-(Lr,Lr,1) BTD model using the CPD.
model = struct;
model.variables.A1 = randn(size_tens(1),L1);
model.variables.B1 = randn(size_tens(2),L1);
model.variables.c1 = randn(size_tens(3),1);
model.variables.A2 = randn(size_tens(1),L2);
model.variables.B2 = randn(size_tens(2),L2);
model.variables.c2 = randn(size_tens(3),1);
% The factors A, B and C are built out of subfactors.
% Structure may also be imposed on subfactors if desired.
model.factors.A = {'A1', 'A2'};
model.factors.B = {'B1', 'B2'};
model.factors.C = {'c1', 'c1', 'c1', 'c2', 'c2'};
model.factorizations.mycpd.data = T;
model.factorizations.mycpd.cpd = {'A','B','C'};
The line model.factors.A = {'A1', 'A2'} states that the factor A is a
matrix consisting of two subfactors that are concatenated horizontally.
Internally, the SDF algorithm first builds the subfactors, which are in this
case simply references to the variables A1 and A2, and then calls
cell2mat on the cell array of subfactors to create the factor A. Besides
on factors, structure may also be imposed on subfactors. For instance, we could
have written model.factors.A = {{'A1',@struct_sigmoid},'A2'} to constrain
the elements of the first submatrix in the factor A to the interval
\((-1,1)\) (the elements of the variable A1 itself are not restricted to
this interval however).
The explicit modeling in the previous code block can be avoided using the
transformation struct_LL1:
L = [L1 L2];
LL1 = @(z,task)struct_LL1(z,task,L);
model = struct;
model.variables.A = randn(size_tens(1),L1+L2);
model.variables.B = randn(size_tens(2),L1+L2);
model.variables.c = randn(size_tens(3),2);
model.factors.A = 'A';
model.factors.B = 'B';
model.factors.C = {'c',LL1};
model.factorizations.myll1.data = T;
model.factorizations.myll1.cpd = {'A','B','C'};
Example 5: constants¶
To indicate that a factor or subfactor is constant, it suffices to use that constant array in the factor instead of a reference to a variable.
Example 5a: known factor matrix¶
The following example computes a CPD in which one factor matrix is known:
% Generate a CPD.
I = 15;
R = 4;
U = cpd_rnd([I I I],R);
T = cpdgen(U);
% Model the CPD of T, where C = U{3} is known.
model = struct;
model.variables.a = randn(size(U{1}));
model.variables.b = randn(size(U{1}));
model.factors.A = 'a';
model.factors.B = 'b';
model.factors.C = U{3}; % The third factor is constant.
model.factorizations.myfac.data = T;
model.factorizations.myfac.cpd = {'A','B','C'};
% Solve the SDF model.
options.Display = 5; % View convergence progress every 5 iterations.
sol = sdf_nls(model,options);
sol.variables
sol.factors
When running the sdf_check(model, 'print') function, C is indeed
recognized as a constant factor:
C [15x4] constant
Example 5b: partially known factor matrix¶
To create a factor of which some of the columns are known, simply define the factor to consist of a number of subfactors where one of the subfactors is a fixed array. The following example computes a CPD in which part of one factor matrix is known:
% Generate a CPD.
I = 15;
R = 4;
U = cpd_rnd([I I I],R);
T = cpdgen(U);
% Model the CPD of T, where the last columns of C are known
model = struct;
model.variables.a = randn(size(U{1}));
model.variables.b = randn(size(U{1}));
model.variables.c = randn(size(U{1},1),2);
model.factors.A = 'a';
model.factors.B = 'b';
model.factors.C = {'c',U{3}(:,1:2)}; % The third factor is partially known.
model.factorizations.myfac.data = T;
model.factorizations.myfac.cpd = {'A','B','C'};
% Solve the SDF model.
options.Display = 5; % View convergence progress every 5 iterations.
sol = sdf_nls(model,options);
sol.variables
sol.factors
When running the sdf_check(model, 'print') function, C is indeed
recognized as a partially constant factor:
C [15x4] Partially constant
Example 6: chaining factor structures¶
Factor structures can be chained so that a variable is transformed by a sequence
of functions. In the following example, we compute a CPD in which a subfactor of
the first factor matrix is a nonnegative Toeplitz matrix and the last factor is
known. To create a nonnegative Toeplitz subfactor, we will create a generator
vector for the Toeplitz matrix, transform it with struct_nonneg so that it
is nonnegative, and then transform it with struct_toeplitz to create a
nonnegative Toeplitz subfactor. The factor \(\mat{A}\) is defined as a
matrix consisting of two subfactors: the top subfactor transforms the variable
atop with struct_nonneg, followed by struct_toeplitz, and the bottom
subfactor is simply an unconstrained matrix abtm.
% Generate CPD, wherein
% - the first factor has a nonnegative Toeplitz subfactor.
% - the last factor is known.
I = 15;
R = 4;
U = cpd_rnd([I I I],R);
U{1}(1:R,1:R) = toeplitz(rand(4,1));
T = cpdgen(U);
% Define model variables.
model = struct;
model.variables.atop = randn(2*R-1,1);
model.variables.abtm = randn(I-R,R);
model.variables.b = randn(I,R);
% Define model factors.
% The first factor vertically concatenates two subfactors.
% The top subfactor is generated as a nonnegative Toeplitz matrix.
model.factors.A = {{'atop',@struct_nonneg,@struct_toeplitz}; ...
{'abtm'}};
model.factors.B = 'b';
% Third factor matrix is known.
model.factors.C = U{3};
% Define model factorizations.
model.factorizations.myfac.data = T;
model.factorizations.myfac.cpd = {'A','B','C'};
sdf_check(model, 'print');
The different steps used to construct factor matrix \(\mat{A}\) can be
investigated by clicking A in the Matlab Command Window:
Expansion of factor A (id = 1) with structure [2x1] (view):
(1,1) atop [7x1] struct_nonneg temp [7x1]
temp [7x1] struct_toeplitz Factor [4x4]
(2,1) abtm [11x4]
% Solve the SDF problem.
options.Display = 10; % View convergence progress every 10 iterations.
sol = sdf_nls(model,options);
Example 7: regularization¶
In addition to the CPD and BTD models, SDF also foresees three models that represent L0, L1 and L2 regularization terms. By including the factorizations
% Use L2-regularization on the factors A and B.
model.factorizations.myreg2.data = {zeros(size(U{1})),zeros(size(U{2}))};
model.factorizations.myreg2.regL2 = {'A','B'};
% Use L1-regularization on C-ones(size(C)).
model.factorizations.myreg1.data = ones(size(U{3}));
model.factorizations.myreg1.regL1 = 'C';
in the previous example, the terms
\(\frac{1}{2}\|\begin{bmatrix}\vectorize(\mat{A})^{\T} &
\vectorize(\mat{B})^{\T}\end{bmatrix}^{\T} - \vec{0}\|_2^2 =
\frac{1}{2}(\|\mat{A}\|_{\text{F}}^2 + \|\mat{A}\|_{\text{F}}^2)\) and
\(\frac{1}{2}\|\vectorize(\mat{C}) - \vec{1}\|_1\) are added to the
objective function. The data field defaults to all zeros, if omitted. In the
case of L0 regularization, a smoothed variant is used, i.e.,
\(\|\vec{x}\|_0\) is computed using \(\sum_i 1 -
\text{exp}(-\frac{x_i^2}{\sigma^2})\). The parameter \(\sigma\) can be set
using the sigma field and can be either a scalar constant, or a function in
the iteration number k and the factors x. For example:
% Use L2-regularization on the factors A.
model.factorizations.myreg0.regL0 = 'A';
model.factorizations.myreg0.sigma = 0.01; % (the default) or
model.factorizations.myreg0.sigma = @(k,x) 0.01*frob(x{1}); % x is a cell of factors
When regularization is used, the importance or weight of the regularization is often an important hyperparameter. Consider the following problem:
This can be modeled as follows:
model = struct;
% definition of variables and factors omitted
model.factorizations.tensor.data = T;
model.factorizations.tensor.cpd = {'A', 'B', 'C'};
model.factorizations.tensor.weight = lambda1;
model.factorizations.regA.regL2 = 'A';
model.factorizations.regA.weight = lambda2;
model.factorizations.regBC.regL1 = {'B', 'C'};
model.factorizations.regBC.weight = lambda3;
The example above makes use of absolute weights. It is also possible to work
with relative weights, by using relweight instead of weight. For
example:
model = struct;
% definition of variables and factors omitted
model.factorizations.tensor.data = T;
model.factorizations.tensor.cpd = {'A', 'B', 'C'};
model.factorizations.tensor.relweight = 100;
model.factorizations.regA.regL2 = 'A';
model.factorizations.regA.relweight = 1;
model.factorizations.regBC.regL1 = {'B', 'C'};
model.factorizations.regBC.relweight = 2;
This example states that the tensor decomposition is 100 times more important than the L2 regularization term, and 50 times more important than the L1 regularization term, regardless of how many entries the different terms involve. Similarly, the L1 regularization term is more important than the L2 regularization term. The precise relation between the relative weights and the weights \(\lambda_i\) is explained in Structured data fusion.
Example 8: compression based initialization¶
The cpd and ll1 functions implement a full initialization strategy in
order to reduce the computation time. A similar sdf method does not yet
exist. Nevertheless, we show how compression can be used in SDF to reduce the
computational cost. Consider the following nonnegative CPD of a rank-5 tensor
\(\ten{T}\) with dimensions \(150\times160\times170\):
R = 5;
model = struct;
model.variables.a = rand(150,R);
model.variables.b = rand(160,R);
model.variables.c = rand(170,R);
model.factors.A = {'a', @struct_nonneg};
model.factors.B = {'b', @struct_nonneg};
model.factors.C = {'c', @struct_nonneg};
model.factorizations.tensor.data = T;
model.factorizations.tensor.cpd = {'A', 'B', 'C'};
sol = sdf_nls(model);
In order to reduce the computational cost, the tensor \(\ten{T}\) can be
compressed, e.g., using the mlsvd_rsi method:
[U,S] = mlsvd_rsi(T, [R R R]);
In the unconstrained CPD case, the factor matrices Ucomp{1}, Ucomp{2},
and Ucomp{3} in the CPD of the compressed tensor \(\ten{S}\) can be
computed and expanded to the factors of the full tensor \(\ten{T}\). This
can be done by multiplying the factor matrices Ucomp{1}, Ucomp{2}, and
Ucomp{3} with the compression matrices U{1}, U{2}, and U{3},
respectively.
Ucomp = cpd(S, R);
Uinit = cellfun(@(u,v) u*v, U, Ucomp, 'UniformOutput', false);
Ures = cpd_nls(T, Uinit); % refinement
The last refinement step improves the accuracy in case information was lost in the compression.
In the constrained case, this strategy can no longer be used, as the compressed tensor \(\ten{S}\) is not nonnegative. Tensorlab 3.0 foresees a different strategy, which can be followed in the constrained case as well. The idea is to use the results of the compression for a compact representation as a structured tensor, and use the latter to efficiently obtain a first estimate of the desired factors.
R = 5;
model = struct;
model.variables.a = randn(150,R);
model.variables.b = randn(160,R);
model.variables.c = randn(170,R);
model.factors.A = {'a', @struct_nonneg};
model.factors.B = {'b', @struct_nonneg};
model.factors.C = {'c', @struct_nonneg};
model.factorizations.tensor.data = {U,S};
model.factorizations.tensor.cpd = {'A', 'B', 'C'};
sol = sdf_nls(model);
The results in sol are next used in a refinement step:
R = 5;
model = struct;
model.variables.a = sol.variables.a; % initialization for refinement step
model.variables.b = sol.variables.b;
model.variables.c = sol.variables.c;
model.factors.A = {'a', @struct_nonneg};
model.factors.B = {'b', @struct_nonneg};
model.factors.C = {'c', @struct_nonneg};
model.factorizations.tensor.data = T;
model.factorizations.tensor.cpd = {'A', 'B', 'C'};
sol = sdf_nls(model);
It can be useful to limit the number of iterations in the refinement step by
setting the MaxIter option to avoid unneeded work:
sol = sdf_nls(model, 'MaxIter', 10);
Example 9: advanced coupling¶
The previous examples only considered coupled datasets in which the coupling took the form of a shared factor matrix. In this section, we consider joint tensor-matrix and joint tensor-tensor decompositions with a more complex relation between the datasets. Consider the following three datasets: a tensor \(\ten{T} = \ten{M}_{\text{CPD}}(\mat{A},\mat{B},\mat{C})\), a tensor \(\ten{S} = \ten{M}_{\text{CPD}}(\mat{D},\mat{E},\mat{F})\) and a matrix \(\mat{M} = \ten{M}_{\text{CPD}}(\mat{D},\mat{E}) = \mat{D}\mat{E}^{\T}\). Exact coupling, e.g., \(\mat{A} = \mat{D}\), has already been discussed in Example 2: structured coupled matrix factorization. Here, the following relations are considered:
- \(\ten{T}\) and \(\mat{M}\) partially share a factor matrix, i.e., \(\mat{A} = \mat{D}(:,1:R_1)\), in which \(\ten{T}\) has rank \(R_1\) and \(\mat{M}\) has rank \(R_2 > R_1\).
- \(\ten{T}\) and \(\ten{S}\) are approximately coupled using \(\mat{D} = \mat{A} + \mat{N}\), where \(\mat{N}\) is small compared to \(\mat{A}\).
- \(\ten{T}\) and \(\mat{M}\) are coupled using \(\mat{D} = \mat{X}\mat{A}\mat{Y}\), i.e., \(\mat{D}\) is a linear transformation of \(\mat{A}\) with known matrices \(\mat{X}\) and \(\mat{Y}\).
- \(\ten{T}\) and \(\ten{S}\) share an underlying variable \(z\), i.e., \(\mat{A} = f(z)\) and \(\mat{D} = g(z)\).
Example 9a: partial coupling¶
In this example, we investigate the case in which only a part of a factor matrix is shared. Consider a tensor \(\ten{T}\) and a matrix \(\mat{M}\). The first \(R_1 = \text{rank}(\ten{T})\) columns of \(\mat{D}\) are shared. Let \(\mat{D} = [\mat{D}_1, \mat{D}_2]\) then \(\mat{D}_1 = \mat{A}\). The two datasets are modeled as follows:
% Tensor T
U1 = cpd_rnd([10, 11, 12], 3); % factors A, B, C
T = cpdgen(U1);
% matrix M
U2 = cpd_rnd([10, 13], 5); % factors D, E
U2{1}(:,1:3) = U1{1}; % D(:,1:3) = A
M = cpdgen(U2);
In the SDF language, the partial coupling can be expressed using subfactors,
i.e., factor \(\mat{D}\) is the horizontal concatenation of variables
a and d2: D = {'a', 'd2'}. The full model is given by
model = struct;
model.variables.a = randn(10,3);
model.variables.b = randn(11,3);
model.variables.c = randn(12,3);
model.variables.d2 = randn(10,2); % remaining two vectors
model.variables.e = randn(13,5);
model.factors.A = 'a';
model.factors.B = 'b';
model.factors.C = 'c';
model.factors.D = {'a', 'd2'};
model.factors.E = 'e';
model.factorizations.T.data = T;
model.factorizations.T.cpd = {'A', 'B', 'C'};
model.factorizations.M.data = M;
model.factorizations.M.cpd = {'D', 'E'};
[sol,output] = sdf_nls(model, 'Display', 10, 'MaxIter', 200, 'CGMaxIter', 500);
Some extra options are provided to the sdf_nls solver. The Display
option prints an update every 10 iterations. The MaxIter option decreases
the maximum number of iterations to limit the computation time, if no good
solution is found. Finally, the CGMaxIter option increases the maximum
number of CG iterations from 15 (the default) to 500. When structure is imposed
on some factors or coupled datasets are used, it is recommended to increase
CGMaxIter as it generally improves the convergence behavior at the cost of
more expensive iterations. Often the reduction in the number of iterations makes
up for the increased cost per iteration.
The algorithm may converge to a local optimum, depending on the initialization.
It is therefore recommended to perform multiple runs with different initial
values. Recall that the lines model.variables.a = randn(10,3) etc. provide
the initial guess, hence simply executing the sdf_nls(model) multiple times
does not change the result. The variables have to be reinitialized by
reevaluating the lines model.variables.a, model.variables.b, etc. In the
example above, a good solution can be be found using (multiple) random
initializations. Other problems may require better initialization strategies in
order to get a good solution. One can, for example, compute the decompositions
of the uncoupled datasets, match the different terms and then use this result to
initialize the coupled problem.
Example 9b: approximate coupling¶
The coupling between two or more tensors may not be exact. For example, the shared factors can be approximately the same (see, e.g., [38]). In this example, two tensors \(\ten{T}\) and \(\ten{S}\) are coupled in the first mode. To model the inexact coupling, an additional ‘noise’ term \(\mat{N}\) is used: \(\mat{D} = \mat{A} + \mat{N}\). If this noise term is large compared to \(\mat{A}\), there is almost no coupling. If the noise term is small compared to \(\mat{A}\), the coupling is stronger. The two tensors are constructed as follows:
% first tensor T
U1 = cpd_rnd([10, 11, 12], 3); % factors A, B, C
T = cpdgen(U1);
% second tensor S
U2 = cpd_rnd([10, 13, 14], 3); % factors D, E, F
U2{1} = U1{1} + randn(10,3)*1e-3; % D = A + N;
S = cpdgen(U2);
To model the approximate coupling, two transformations are needed:
struct_select and struct_plus. The former can be used to select one
entry from a cell variable. The latter can be used to sum all entries in a cell
variable. The cell variable an contains the initial guesses for
\(\mat{A}\) and \(\mat{N}\): an = {randn(10,3), randn(10,3)*1e-2}.
Factor A simply selects the first entry of an, while factor D sums
both entries. The noise term \(\mat{N}\) should be small, otherwise both
tensors are uncoupled. Therefore, L2 regularization is applied to
\(\mat{N}\).
model = struct;
model.variables.an = {randn(10,3), randn(10,3)*1e-2}; % {A, N}
model.variables.b = randn(11,3);
model.variables.c = randn(12,3);
model.variables.e = randn(13,3);
model.variables.f = randn(14,3);
model.factors.A = {'an', @(z,task) struct_select(z,task,1)}; % A
model.factors.B = 'b';
model.factors.C = 'c';
model.factors.D = {'an', @struct_plus}; % A + N
model.factors.E = 'e';
model.factors.F = 'f';
model.factors.N = {'an', @(z,task) struct_select(z,task,2)}; % N
model.factorizations.T.data = T;
model.factorizations.T.cpd = {'A', 'B', 'C'};
model.factorizations.S.data = S;
model.factorizations.S.cpd = {'D', 'E', 'F'};
model.factorizations.N.regL2 = {'N'};
sdf_check(model, 'print');
The overview of the model indeed shows that the right factors have been selected. (Click the different factors in the Matlab Command Window.) The model can be computed by:
[sol,output] = sdf_nls(model, 'Display', 10, 'CGMaxIter', 100, 'MaxIter', 200);
The output output.relerr gives the relative error between the data and the
computed decomposition for each factorization. As can be seen, the tensors are
approximated quite well:
relerr: [1.6933e-06 1.4664e-06 Inf]
The Inf entry indicates that the norm of the data for the regularization
term N is zero. (Recall that the data field is zero if no data is
specified.) The absolute error output.abserr is more useful for the
regularization term.
The average difference between the computed factors \(\mat{A}\) and
\(\mat{D}\) is given by mean(abs(sol.factors.A(:) - sol.factors.D(:))):
0.0016
which is indeed of the expected order of magnitude (recall that \(N\) is
generated as randn(10,3)*1e-3).
Example 9c: linearly transformed coupling¶
In this example, two datasets are coupled using the relation \(\mat{D} = \mat{X}\mat{A}\mat{Y}\), i.e., \(\mat{D}\) is a linear transformation of \(\mat{A}\) with two known matrices \(\mat{X}\) and \(\mat{Y}\). This relation is used to jointly decompose a tensor \(\ten{T}\) and a matrix \(\mat{M}\), which are generated as follows:
% tensor
U1 = cpd_rnd([10, 11, 12], 4); % factors A, B, C
T = cpdgen(U1);
% Matrix
U2 = cpd_rnd([10, 13], 4); % factors D, E
X = orth(randn(20,10)); % orthogonality is used pinv(X) = X'
Y = randn(4,4); % random transformation
U2{1} = X*U1{1}*Y; % D = X*A*Y
M = cpdgen(U2);
To model the linear transformation of the factor matrix \(\mat{A}\), the
struct_matvec transformation is used. This transformation can be used to
model left and right multiplications with matrices. Indexed variables are
used to shorten the code.
model = struct;
model.variables = cpd_rnd([10 11 12 13], 4);
model.factors.A = 1;
model.factors.B = 2;
model.factors.C = 3;
model.factors.D = {1, @(z,task) struct_matvec(z, task, X, Y)};
model.factors.E = 4;
model.factorizations.T.data = T;
model.factorizations.T.cpd = {'A', 'B', 'C'};
model.factorizations.M.data = M;
model.factorizations.M.cpd = {'D', 'E'};
[sol,output] = sdf_nls(model, 'Display', 10, 'CGMaxIter', 500, ...
'TolFun', eps^2, 'TolX', eps, 'MaxIter', 250);
The output.relerr field shows that for both datasets the relative error is
very small (multiple initializations may be needed):
output.relerr =
1.0e-14 *
0.0653 0.1022
The same holds for cpderr(U1, {sol.factors.A, sol.factors.B, sol.factors.C}).
By construction, we have all(all(X*sol.factors.A*Y - sol.factors.D == 0)).
Note that cpderr(U2, {sol.factors.D, sol.factors.E}) is not small in
general, as a matrix decomposition is not unique.
Note that the left multiplication with \(\mat{X}\) can be removed, by
multiplying the data matrix \(\mat{M}\) on the left with the (pseudo)inverse
of \(\mat{X}\). As \(\mat{X}\) has orthonormal columns, \(\mat{X}^{\TH}\)
can be used. To do the left multiplication, the tmprod command is used, as
it works both for matrices and higher-order tensors:
% Only relevant lines shown:
model.factors.D = {1, @(z,task) struct_matvec(z, task, [], Y)};
model.factorizations.M.data = tmprod(M, X', 1);
[sol,output] = sdf_nls(model, 'Display', 10, 'CGMaxIter', 500, ...
'TolFun', eps^2, 'TolX', eps, 'MaxIter', 250);
Note that in the first line X is replaced by [] as the multiplication
from the left is no longer necessary.
Example 9d: same underlying variable¶
Datasets may share an underlying variable that is transformed using
different transformations. In this example, factor matrices \(\mat{A}\) and
\(\mat{D}\) are constructed as a transposed Vandermonde matrix (see
Example 2: structured coupled matrix factorization) and a squared transposed Vandermonde matrix. The
shared underlying variables \(z\) are the poles or generators of the
Vandermonde matrices. The other factor matrices for tensors \(\ten{T}\) and
\(\ten{S}\) are generated using cpd_rnd.
% Shorthand function for transposed Vandermonde matrices
vander = @(z,range) struct_vander(z,[],range).';
% Poles = shared variable
poles = exp(2*pi*1i*randn(1,4));
% First tensor T
U1 = cpd_rnd([10, 11, 12], 4); % factors A, B, C
U1{1} = vander(poles, [1 10]);
T = cpdgen(U1);
% Second tensor S
U2 = cpd_rnd([7, 13, 14], 4); % factors D, E, F
U2{1} = vander(poles, [1 7]).^2;
S = cpdgen(U2);
The coupling can easily be expressed by generating two factor matrices
\(\mat{A}\) and \(\mat{D}\) that use the same variable poles, but
through different transformations:
% Predefine transformations to improve readability
vander1 = @(z,task) struct_vander(z, task, [1 10]);
vander2 = @(z,task) struct_vander(z, task, [1 7]);
transp = @struct_transpose;
square = @(z,task) struct_power(z, task, 2);
model = struct;
model.variables.poles = exp(2*pi*1i*rand(1,4));
model.variables.b = randn(11, 4);
model.variables.c = randn(12, 4);
model.variables.e = randn(13, 4);
model.variables.f = randn(14, 4);
model.factors.A = {'poles', vander1, transp};
model.factors.B = 'b';
model.factors.C = 'c';
model.factors.D = {'poles', vander2, transp, square};
model.factors.E = 'e';
model.factors.F = 'f';
model.factorizations.T.data = T;
model.factorizations.T.cpd = {'A', 'B', 'C'};
model.factorizations.S.data = S;
model.factorizations.S.cpd = {'D', 'E', 'F'};
sdf_check(model, 'print');
The overview created by sdf_check shows that the \(1\times4\)
vector of poles is transformed into the correct matrices. For example, by clicking
factor D the different steps can be investigated:
Expansion of factor D (id = 4) (view):
(1,1) poles [1x4] struct_vander temp [4x7]
temp [4x7] struct_transpose temp [7x4]
temp [7x4] struct_power Factor [7x4]
Finally, the model can be computed using the sdf_nls solver:
[sol,output] = sdf_nls(model, 'Display', 10, 'CGMaxIter', 150, ...
'TolFun', eps^2, 'TolX', eps, 'MaxIter', 350);
Multiple initializations may be required to find an accurate solution.