.. _sdf-examples-chap: ******************************** Structured data fusion: examples ******************************** In :ref:`sdf-basic-chap` 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 :ref:`sdf-basic-chap` remains highly recommended even if a more example based approach is favored by the user. .. _example1-sec: """""""""""""""""""""""""""""""""""" Example 1: nonnegative symmetric CPD """""""""""""""""""""""""""""""""""" As a first example, the nonnegative symmetric CPD of an incomplete tensor :math:`\ten{T}` is computed. First, generate the tensor .. code-block:: tensorlab % 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 .. code-block:: tensorlab 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. .. code-block:: tensorlab % 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: .. code-block:: tensorlab % 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: .. code-block:: tensorlab % 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 :ref:`types-sec`). 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 .. code-block:: tensorlab % 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: .. code-block:: tensorlab % 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: .. code-block:: none :caption: adsfadfiefwjoijio 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): .. code-block:: none :caption: ewfoijfweojiefw 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: .. code-block:: tensorlab % 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: .. code-block:: tensorlab 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 :math:`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 .. code-block:: tensorlab 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'}; .. _coupling-basic-sec: """"""""""""""""""""""""""""""""""""""""""""""""""" Example 2: structured coupled matrix factorization """"""""""""""""""""""""""""""""""""""""""""""""""" Let :math:`\mat{X}` and :math:`\mat{Y}` be square matrices of dimension :math:`N\times N` which we wish to jointly factorize as :math:`\mat{U}\cdot \mat{\Lambda}_X\cdot \mat{V}^{\T}` and :math:`\mat{U}\cdot \mat{\Lambda}_Y\cdot \mat{W}^{\T}`, respectively. The factor :math:`\mat{U}` is common to both :math:`\mat{X}` and :math:`\mat{Y}`, and the extent to which the columns are shared is given by the absolute values of the diagonal matrices :math:`\mat{\Lambda}_X` and :math:`\mat{\Lambda}_Y`. Furthermore, we will require the entries of :math:`\mat{W}` to lie in the interval (-3,5) and impose a Vandermonde structure on :math:`\mat{V}`, so that .. math:: \begin{align} \mat{V} = \begin{bmatrix} v_1^0 & v_1^1 & \cdots & v_1^d\\ \vdots & \vdots & \ddots & \vdots\\ v_N^0 & v_N^1 & \cdots & v_N^d\\ \end{bmatrix} \end{align} with :math:`d = R-1` and :math:`R` the number of terms. Note that :math:`\mat{V}` depends only on a so-called generator vector :math:`\vec{v} = \scriptsize\begin{bmatrix}v_1 & \cdots & v_N\end{bmatrix}^{\T}`. First, the matrices :math:`\mat{X}` and :math:`\mat{Y}` are created: .. code-block:: tensorlab % 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 .. code-block:: tensorlab % 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 :math:`\mat{U}` and :math:`\mat{W}`, the generator vector :math:`\vec{v}` for the Vandermonde matrix :math:`\mat{V}` and the diagonals :math:`\vec{\lambda}_X` and :math:`\vec{\lambda}_Y`. The model assumes that :math:`\mat{X}` and :math:`\mat{Y}` share at most :math:`R=4` vectors in :math:`\mat{U}`. Next, we define the factors as transformed variables with .. code-block:: tensorlab % 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 :math:`\mat{X}` and :math:`\mat{Y}` to the model with .. code-block:: tensorlab % 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 :math:`\mat{X} = \mat{U}\cdot \mat{\Lambda}_X\cdot \mat{V}^{\T}` and :math:`\mat{Y} = \mat{U}\cdot \mat{\Lambda}_Y\cdot \mat{W}^{\T}` by associating the factor matrices :math:`\vec{\lambda}_X` and :math:`\vec{\lambda}_Y`, which are row vectors, with the third dimension of :math:`\mat{X}` and :math:`\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 .. code-block:: tensorlab % 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 :ref:`example1-sec`). """""""""""""""""""""""""""""""" 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 :math:`\vec{q}` that parameterizes a matrix with orthonormal columns :math:`\mat{Q}`. The structure ``struct_orth`` can then be used to transform the variable :math:`\vec{q}` into the factor :math:`\mat{Q}`. First, we construct the data for the problem: .. code-block:: tensorlab % 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 :math:`\vec{q}` should be a vector of length :math:`IR-0.5R(R-1)`. To transform :math:`\vec{q}` into a matrix with orthonormal columns, we need to pass the size of :math:`\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: .. code-block:: tensorlab % 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'); .. code-block:: none :caption: asdffsdfda 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 :math:`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``: .. code-block:: tensorlab Q = ans; Q'*Q .. code-block:: none :caption: qewrwewqf 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: .. code-block:: tensorlab % 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-:math:`(L_r,L_r,1)` terms """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" In this example, the decomposition of a tensor :math:`\ten{T}` into multilinear rank-:math:`(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-:math:`(L_r,L_r,1)` BTD :cite:`r739,r387,r388` of a tensor :math:`\ten{T}` in :math:`R` terms, i.e., .. math:: \ten{T} \approx \sum_{r=1}^R (\mat{A}_r\mat{B}_r^{\T})\op\vec{c}_r where :math:`\vec{c}_r` are vectors and :math:`\mat{A}_r` and :math:`\mat{B}_r` have :math:`L_r` columns. In the unconstrained and uncoupled case, the decomposition into rank-:math:`(L_r,L_r,1)` terms can be computed using the specialized ``ll1`` routines (see :ref:`ll1-chap`). In this example, three ways to compute this decomposition are shown: - using the ``ll1`` factorization 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-:math:`(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-:math:`(L_r,L_r,1)` terms with :math:`L=[3, 2]` in this example. In the CPD formulation of this decomposition, the different factors :math:`\mat{A}_1` and :math:`\mat{A}_2` are concatenated along the second mode, i.e., in Matlab code we have ``A = [A1 A2]``. The same holds for :math:`\mat{B}` and :math:`\mat{C}`. Hence, factors ``A`` and ``B`` have ``sum(L)`` columns, while ``C`` has ``length(L)`` columns (for more information see :ref:`ll1-chap`). To generate the data the ``ll1_rnd`` routine can be used: .. code-block:: tensorlab size_tens = [10 11 12]; L = [3 2]; U0 = ll1_rnd(size_tens, L); T = ll1gen(U0); For the unconstrained decomposition into multilinear rank-:math:`(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: .. code-block:: tensorlab 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-:math:`(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-:math:`(L_r,L_r,1)` terms is a special case of a block term decomposition (BTD), in which the core tensors :math:`\ten{S}_r` are matrices of size :math:`L_r\times L_r \times 1`. The decomposition then takes the form: .. math:: \ten{T} \approx \sum_{r=1}^R \ten{S}_r \tmprod_1 \mat{A}_r \tmprod_2 \mat{B}_r \tmprod_3 \vec{c}_r By default, ``ll1_rnd`` returns a decomposition into multilinear rank-:math:`(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: .. code-block:: tensorlab % 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 :ref:`sdf-advanced-chap`): .. code-block:: tensorlab 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 .. code-block:: tensorlab % 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-:math:`(L_r,L_r,1)` terms uses a CPD. In our example, the decomposition can be written as: .. math:: \ten{T} \approx \sum_{j=1}^{L_1} \mat{A}_1(:,j) \op \mat{B}_1(:,j) \op \vec{c}_1 + \sum_{j=1}^{L_2} \mat{A}_2(:,j) \op \mat{B}_2(:,j) \op \vec{c}_2 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: .. code-block:: tensorlab % 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 :math:`(-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``: .. code-block:: tensorlab 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: .. code-block:: tensorlab % 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: .. code-block:: none :caption: wefwfzddfe 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: .. code-block:: tensorlab % 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: .. code-block:: none :caption: wqefsdfsdaefw 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 :math:`\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``. .. code-block:: tensorlab % 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 :math:`\mat{A}` can be investigated by clicking ``A`` in the Matlab Command Window: .. code-block:: none :caption: gh5grseg 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] .. code-block:: tensorlab % 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 .. code-block:: tensorlab % 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 :math:`\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 :math:`\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., :math:`\|\vec{x}\|_0` is computed using :math:`\sum_i 1 - \text{exp}(-\frac{x_i^2}{\sigma^2})`. The parameter :math:`\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: .. code-block:: tensorlab % 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: .. math:: \begin{align} \min_{\mat{A},\mat{B},\mat{C}} \frac{\lambda_1}{2} \norm{\ten{T} - \ten{M}_{\text{CPD}}(\mat{A},\mat{B},\mat{C})}_{\text{F}}^2 + \frac{\lambda_2}{2} \norm{\mat{A}}_{\text{F}}^2 + \frac{\lambda_3}{2} (\norm{\vectorize(\mat{B})}_1 + \norm{\vectorize(\mat{C})}_1). \end{align} This can be modeled as follows: .. code-block:: tensorlab 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: .. code-block:: tensorlab 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 :math:`\lambda_i` is explained in :ref:`sdf-basic-chap`. """"""""""""""""""""""""""""""""""""""""""" 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 :math:`\ten{T}` with dimensions :math:`150\times160\times170`: .. code-block:: tensorlab 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 :math:`\ten{T}` can be compressed, e.g., using the ``mlsvd_rsi`` method: .. code-block:: tensorlab [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 :math:`\ten{S}` can be computed and expanded to the factors of the full tensor :math:`\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. .. code-block:: tensorlab 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 :math:`\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. .. code-block:: tensorlab 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: .. code-block:: tensorlab 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: .. code-block:: tensorlab 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 :math:`\ten{T} = \ten{M}_{\text{CPD}}(\mat{A},\mat{B},\mat{C})`, a tensor :math:`\ten{S} = \ten{M}_{\text{CPD}}(\mat{D},\mat{E},\mat{F})` and a matrix :math:`\mat{M} = \ten{M}_{\text{CPD}}(\mat{D},\mat{E}) = \mat{D}\mat{E}^{\T}`. Exact coupling, e.g., :math:`\mat{A} = \mat{D}`, has already been discussed in :ref:`coupling-basic-sec`. Here, the following relations are considered: - :math:`\ten{T}` and :math:`\mat{M}` partially share a factor matrix, i.e., :math:`\mat{A} = \mat{D}(:,1:R_1)`, in which :math:`\ten{T}` has rank :math:`R_1` and :math:`\mat{M}` has rank :math:`R_2 > R_1`. - :math:`\ten{T}` and :math:`\ten{S}` are approximately coupled using :math:`\mat{D} = \mat{A} + \mat{N}`, where :math:`\mat{N}` is small compared to :math:`\mat{A}`. - :math:`\ten{T}` and :math:`\mat{M}` are coupled using :math:`\mat{D} = \mat{X}\mat{A}\mat{Y}`, i.e., :math:`\mat{D}` is a linear transformation of :math:`\mat{A}` with known matrices :math:`\mat{X}` and :math:`\mat{Y}`. - :math:`\ten{T}` and :math:`\ten{S}` share an underlying variable :math:`z`, i.e., :math:`\mat{A} = f(z)` and :math:`\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 :math:`\ten{T}` and a matrix :math:`\mat{M}`. The first :math:`R_1 = \text{rank}(\ten{T})` columns of :math:`\mat{D}` are shared. Let :math:`\mat{D} = [\mat{D}_1, \mat{D}_2]` then :math:`\mat{D}_1 = \mat{A}`. The two datasets are modeled as follows: .. code-block:: tensorlab % 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 :math:`\mat{D}` is the horizontal concatenation of variables ``a`` and ``d2``: ``D = {'a', 'd2'}``. The full model is given by .. code-block:: tensorlab 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., :cite:`cabralfarias2015exploring`). In this example, two tensors :math:`\ten{T}` and :math:`\ten{S}` are coupled in the first mode. To model the inexact coupling, an additional 'noise' term :math:`\mat{N}` is used: :math:`\mat{D} = \mat{A} + \mat{N}`. If this noise term is large compared to :math:`\mat{A}`, there is almost no coupling. If the noise term is small compared to :math:`\mat{A}`, the coupling is stronger. The two tensors are constructed as follows: .. code-block:: tensorlab % 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 :math:`\mat{A}` and :math:`\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 :math:`\mat{N}` should be small, otherwise both tensors are uncoupled. Therefore, L2 regularization is applied to :math:`\mat{N}`. .. code-block:: tensorlab 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: .. code-block:: tensorlab [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: .. code-block:: none :caption: htyetyhdeh 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 :math:`\mat{A}` and :math:`\mat{D}` is given by ``mean(abs(sol.factors.A(:) - sol.factors.D(:)))``: .. code-block:: none :caption: qweres 0.0016 which is indeed of the expected order of magnitude (recall that :math:`N` is generated as ``randn(10,3)*1e-3``). ----------------------------------------- Example 9c: linearly transformed coupling ----------------------------------------- In this example, two datasets are coupled using the relation :math:`\mat{D} = \mat{X}\mat{A}\mat{Y}`, i.e., :math:`\mat{D}` is a linear transformation of :math:`\mat{A}` with two known matrices :math:`\mat{X}` and :math:`\mat{Y}`. This relation is used to jointly decompose a tensor :math:`\ten{T}` and a matrix :math:`\mat{M}`, which are generated as follows: .. code-block:: tensorlab % 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 :math:`\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. .. code-block:: tensorlab 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): .. code-block:: none :caption: h6gfgaf 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 :math:`\mat{X}` can be removed, by multiplying the data matrix :math:`\mat{M}` on the left with the (pseudo)inverse of :math:`\mat{X}`. As :math:`\mat{X}` has orthonormal columns, :math:`\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: .. code-block:: tensorlab % 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 :math:`\mat{A}` and :math:`\mat{D}` are constructed as a transposed Vandermonde matrix (see :ref:`coupling-basic-sec`) and a squared transposed Vandermonde matrix. The shared underlying variables :math:`z` are the poles or generators of the Vandermonde matrices. The other factor matrices for tensors :math:`\ten{T}` and :math:`\ten{S}` are generated using ``cpd_rnd``. .. code-block:: tensorlab % 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 :math:`\mat{A}` and :math:`\mat{D}` that use the same variable ``poles``, but through different transformations: .. code-block:: tensorlab % 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 :math:`1\times4` vector of poles is transformed into the correct matrices. For example, by clicking factor ``D`` the different steps can be investigated: .. code-block:: none :caption: sdreggs 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: .. code-block:: tensorlab [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.