Canonical polyadic decomposition¶
The polyadic decomposition (PD) [5][6][10][11][12][13] approximates a tensor with a sum of \(R\) rank-one tensors. If the number of rank-1 terms \(R\) is minimal, the decomposition is called canonical (CPD). Let \(\tensor{A} \op \tensor{B}\) denote the outer product between an \(N\)th-order tensor \(\tensor{A}\) and an \(M\)th-order tensor \(\tensor{B}\), then \(\tensor{A} \op \tensor{B}\) is the \((N+M)\)th-order tensor defined by \((\tensor{A} \op \tensor{B})_{i_1\cdots i_N\,j_1\cdots j_M} = a_{i_1\cdots i_N} \cdot b_{j_1\cdots j_M}\). For example, let \(\vec{a}\), \(\vec{b}\) and \(\vec{c}\) be nonzero vectors in \(\R^{n}\), then \(\vec{a} \op \vec{b} \equiv \vec{a}\cdot \vec{b}^{\T}\) is a rank-one matrix and \(\vec{a} \op \vec{b} \op \vec{c}\) is defined to be a rank-one tensor. Let \(\ten{T}\) be a tensor of dimensions \(I_1 \times I_2 \times \cdots \times I_N\), and let \(\mat{U}^{(n)}\) be matrices of size \(I_n \times R\) and \(\vec{u}_r^{(n)}\) the \(r\)th column of \(\mat{U}^{(n)}\), then
A visual representation of this decomposition in the third-order case is shown in Figure 28.
Problem and tensor generation¶
Generating pseudorandom factor matrices¶
Tensorlab stores the factor matrices \(\mat{U}^{(n)} \in \C^{I_n\times R}\),
\(n=1,\ldots,N\), of an \(R\)-term PD of an
\(N\)th-order tensor as a cell array of length \(N\), i.e.,
U = {U{1},U{2},...,U{N}}. To generate pseudorandom factor matrices
\(\mat{U}^{(n)}\), cpd_rnd can be used:
size_tens = [7 8 9]; R = 4;
U = cpd_rnd(size_tens,R);
By default, cpd_rnd generates each factor U{n} as
randn(size_tens(n),R). Options can be given as a structure or as
key-value pairs, e.g.:
% using a structure
options = struct;
options.Real = @rand;
options.Imag = @rand;
U = cpd_rnd(size_tens,R,options);
% using key-value pairs
U = cpd_rnd(size_tens, R, 'Real', @rand, 'Imag', @rand);
Each factor matrix U{n} is then generated as
rand(size_tens(n),R) + rand(size_tens(n),R)*1i.
Generating the associated full tensor¶
Given a cell array of factor matrices U = {U{1},U{2},...}, its
associated full tensor T can be computed with
T = cpdgen(U);
This is equivalent to
M = U{1}*kr(U(end:-1:2)).';
size_tens = cellfun('size',U,1);
T = mat2tens(M,size_tens,1);
The ful command can be used as well to generate the full tensor. Both
ful and cpdgen also allow one to generate subtensors:
U = cpd_rnd([10 11 12], 5);
T = cpdgen(U);
t1 = cpdgen(U, [1 2 3 2 3]); % using linear indices
frob(t1 - T([1 2 3 2 3])) % is zero
t2 = ful(U, ':', 2, ':'); % using subscripts (':' is a string!)
frob(t2 - T(:,2,:)) % is zero
Computing the CPD¶
A number of algorithms are available to compute the CPD of a tensor
\(\ten{T}\) of arbitrary order \(N\) . A deterministic algorithm using
the generalized eigenvalue decomposition is implemented in cpd_gevd [14]. The
cpd_als, cpd_minf and cpd_nls algorithms are optimization-based
algorithms and use alternating least squares, nonlinear unconstrained
optimization and nonlinear least squares, respectively. Finally, a high-level
algorithm is implemented in cpd. This method automatically computes an
initialization and uses this as a starting point for one or more optimization
steps using an optimization-based algorithm. Because cpd is a higher-level
algorithm, it is often the recommended method. All optimization-based algorithms
accept dense, sparse, incomplete and structured tensors (see Datasets: dense, incomplete, sparse and structured).
If structured tensors are used, and a solution accurate up to machine precision
is needed, make sure to read the note at the end of this chapter.
The principal method¶
The easiest way to compute the CPD of a dense, sparse, incomplete or structured
tensor \(\ten{T}\) in \(R\) rank-one terms, is to call cpd(T,R). For
example,
% Generate pseudorandom factor matrices U0 and their associated full tensor T.
size_tens = [7 8 9]; R = 4;
U = cpd_rnd(size_tens,R);
T = cpdgen(U);
% Compute the CPD of the full tensor T.
Uhat = cpd(T,R);
generates and decomposes a real rank-4 tensor. Internally, cpd performs a
number of steps to provide a good initialization and to reduce the computational
cost of the decomposition. First, cpd compresses the tensor using a low
multilinear rank approximation, e.g., using mlsvd_rsi (see
Multilinear singular value decomposition and low multilinear rank approximation), if it is worthwhile. Then cpd chooses a method to
generate an initialization U0, e.g., cpd_gevd, after which cpd
executes an algorithm to compute the CPD given the initialization, e.g.,
cpd_nls. Finally cpd uncompresses the tensor and refines the solution
(if compression was applied). Depending on the kind of input tensor T,
additional substeps are performed. If T is a dense tensor, the command
detectstructure is used to detect if there is any structure to be exploited
during the decomposition (see ExploitStructure option). If structure is
detected, the dense tensor is converted to its efficient representation. If
T is the efficient representation of a sufficiently small structured tensor,
T is expanded to allow the use of better compression and initialization
algorithms (see ExpandLimit option).
The command cpd(T, R) automatically takes care of the initialization for the
chosen optimization algorithm. Alternatively an initial solution can be provided
using
U0 = cpd_rnd([10 11 12], R);
Uhat = cpd(T, U0);
Note that cpd_gevd is a deterministic algorithm, unless slices are combined
randomly (see Slices option). Hence, if this algorithm is used for
initialization in cpd, the result Uhat is always the same for multiple
runs for the same tensor \(\ten{T}\), rank \(R\) and options. Changing
the initialization method to, e.g., cpd_rnd, is useful when different
initializations are needed. The following example uses the cpd_gevd
algorithm as initialization method for the first run, and uses a random
initialization for the other runs:
init = @cpd_gevd;
results = cell(1, 5);
for n = 1:5
results{n} = cpd(T, R, 'Initialization', init);
init = @cpd_rnd;
end
The next subsection explains the different options for the cpd routine.
Setting the options¶
The different steps in cpd are customizable by using the different options
(see help cpd for more information). Options can be provided using an
options structure, or using key-value pairs, e.g.,
options.Display = true; % Show progress on the command line.
options.Initialization = @cpd_rnd; % Select pseudorandom initialization.
options.Algorithm = @cpd_als; % Select ALS as the main algorithm.
options.AlgorithmOptions.LineSearch = @cpd_els; % Add exact line search.
options.AlgorithmOptions.TolFun = 1e-12; % Set function tolerance stop criterion
options.AlgorithmOptions.TolX = 1e-12; % Set step size tolerance stop criterion
Uhat = cpd(T,R,options);
The structures InitializationOptions, AlgorithmOptions and
RefinementOptions are passed as option structures to the algorithms
corresponding to initialization, algorithm and refinement steps, respectively.
In the example above cpd calls cpd_als as
cpd_als(T,options.Initialization(T,R),options.AlgorithmOptions).
Since Tensorlab 3.0 some frequently used options are automatically. For example
cpd(T, R, 'Display', 10) sets Display = true for cpd and
automatically passes the Display = 10 option to AlgorithmOptions and
RefinementOptions. Similarly, the MaxIter, TolX, TolFun and
CGMaxIter options are passed automatically.
A full overview of the possible options is given in help cpd. The
following options are worthwhile to be highlighted:
Complex: If set to'auto', a complex initialization is computed if the tensorTis complex, and a real initialization is computed otherwise. SetComplextotrueif a complex solution is required, whetherTis real or not.ExpandLimit: Allow a structured tensorTto be expanded for the compression and/or initialization steps ifprod(getsize(T)) <= ExpandLimit. SetExpandLimit = 1to make sure tensors are never expanded.ExploitStructure: If'auto'(the default)cpdtries to detect structure within the given dense tensor and uses its efficient representation for the decomposition of the uncompressed tensor if structure is found. Currently, only Hankel structure is detected. Set tofalseto disable structure detection. Set totrueif structure detection should also be enabled for the compressed tensor.UseCPDI: If set totruespecialized computational routines are used ifcpd_nlsis used to compute the CPD of an incomplete tensor. This option is useful if many entries are missing or the pattern of missing entries is not random [15].
Viewing the algorithm output¶
Each step may also output additional information specific to that step. For
instance, most CPD algorithms such as cpd_als keep track of the number
of iterations and objective function value. To obtain this information, capture
the second output:
[Uhat,output] = cpd(T,R,options);
and inspect its fields, for example by plotting the objective function value:
semilogy(0:output.Algorithm.iterations,sqrt(2*output.Algorithm.fval));
xlabel('iteration');
ylabel('frob(cpdres(T,U))');
grid on;
Setting the Display option to true or to a number greater than zero,
prints additional information to the command window. For example:
U = cpd_rnd([10 11 12], 5);
T = cpdgen(U);
Tn = noisy(T, 20);
[Uhat, output] = cpd(Tn, 5, 'Display', 1);
Step 1: Compression is mlsvd_rsi (compression ratio 0.094697 < 0.5)...
relative error = 0.0906931.
Step 2: Initialization is cpd_gevd (sum(R <= size(T)) >= 2)...
relative error = 0.031175.
Step 3: Algorithm is cpd_nls on the compressed tensor... iterations = 6,
relative error = 0.0207.
Step 4: Refinement is cpd_nls on the uncompressed tensor:
| Step 4a: Detecting structure... no structure detected.
| Step 4b: cpd_nls... iterations = 6, relative error = 0.092980
The four steps discussed in the previous section are clearly indicated. The
mlsvd_rsi algorithm is used here to compress the tensor. Next the
cpd_gevd method is used to compute an initialization for the compressed
tensor. This initialization is used as starting point for the optimization
method in step 3. Finally, the tensor is uncompressed again in step 4 and the
solution is refined for the uncompressed tensor. In step 4a, cpd tries to
detect structure to exploit in the computations, but no structure is found in
this case.
In the next example, a sampled cosine function is Hankelized using the
hankelize function (see Tensorization techniques). It can be shown that the
rank of this real tensor is two in the complex field. A complex solution is
computed by setting the Complex option to true.
T = hankelize(cos(2*pi*linspace(0,1,51)), 'order', 3);
options = struct;
options.Initialization = @cpd_rnd;
options.Algorithm = @cpd_als;
options.Refinement = @cpd_nls;
options.Complex = true;
[Uhat, output] = cpd(T, 2, options, 'Display', 1);
The following output is printed:
Step 1: Compression is mlsvd_rsi (compression ratio 0.00145243 < 0.5)...
relative error = 9.61532e-16.
Step 2: Initialization is cpd_rnd (requested by user)... relative error = 0.983011.
Step 3: Algorithm is cpd_als on the compressed tensor... iterations = 10,
relative error = 2.30489e-05.
Step 4: Refinement is cpd_nls on the uncompressed tensor:
| Step 4a: Detecting structure... detected Hankel structure.
| Step 4b: Converted tensor to efficient representation.
| Step 4c: cpd_nls on efficient representation... iterations = 1,
relative error = 6.47107e-10.
| Step 4d: cpd_nls on the original full tensor to improve accuracy...
iterations = 1, relative error = 2.66907e-16.
The structure detection is shown in step 4 of the printed output. Although a
full tensor is given, the algorithm automatically detected the Hankel structure
(step 4a) and converted the tensor to the efficient representation (step 4b).
The refinement is then executed on this efficient representation (step 4c). This
can be done more efficiently than when using the original full tensor. Finally,
some additional refinement steps are applied to the original tensor to improve
the accuracy (step 4d). These substeps are performed in step 3 if no
compression is performed. Note that, for illustration purpose, the cpd_als
and cpd_minf algorithms have been used instead of the default cpd_nls
algorithm, as the latter converges too fast in this case. Due to this fast
convergence, the structure detection is then no longer needed.
In the previous example, the tensor T is a full tensor. The next two
examples show the behavior for efficient representations of structured tensors
T. First, a rank-2 tensor \(\ten{T}\) is created by Hankelizing a
sampled cosine function. To obtain the efficient representation, the hankelize
function with the full option set to false is used. (getstructure(T)
can be used to verify that the efficient Hankel representation is used.) This
efficient representation for the tensor \(\ten{T}\) is used by cpd:
T = hankelize(cos(2*pi*linspace(0,1,51)), 'order', 3, 'full', false);
options = struct;
options.Algorithm = @cpd_minf;
options.Complex = true;
[Uhat, output] = cpd(T, 2, options, 'Display', 1);
Step 1: Compression is mlsvd_rsi (compression ratio 0.00145243 < 0.5):
| Step 1a: Structured tensor expanded to full tensor (prod(getsize(T)) <= 1e+06).
| Step 1b: mlsvd_rsi on full tensor... relative error = 1.06122e-15.
Step 2: Initialization is cpd_gevd (sum(R <= size(T)) >= 2)...
relative error = 3.47269e-16.
Step 3: Algorithm is cpd_minf on the compressed tensor... iterations = 1,
relative error = 3.47269e-16.
Step 4: Refinement skipped (relative error = 9.96998e-16 <= 1e-08)
From the printed output, we see that the number of elements in the full tensor
is smaller than the ExpandLimit = 1e6. Therefore, the representation is
expanded to a full tensor such that the mlsvd_rsi algorithm can be applied
for compression. In case no compression is performed, the expansion is performed
in step 2. Next, an initial guess is computed using the compressed tensor in
step 2. This initial guess is then improved using cpd_minf in step 3.
Finally, in step 4, a refinement step is performed on the original efficient
representation instead of on the compressed tensor. However, in this example,
the relative error is already smaller than what can be obtained using efficient
representations. In case a high accuracy is required, please check the note at
the end of this chapter. Note that the relative error in step 4 is higher than
in step 3. This is due to the fact that the error is computed on the compressed
tensor in step 3, while it is computed on the uncompressed tensor in step 4.
In the second example for structured tensors, we use cpd_rnd for the
initialization instead of cpd_gevd. A different situation occurs: the
relative error in the beginning of the refinement step is not smaller than
1e-08 and the refinement step is still performed on the efficient
representation. As the tensor has Hankel structure by construction, no automatic
detection is needed.
T = hankelize(cos(2*pi*linspace(0,1,51)), 'order', 3, 'full', false);
options = struct;
options.Algorithm = @cpd_minf;
options.Initialization = @cpd_rnd;
options.Complex = true;
[Uhat, output] = cpd(T, 2, options, 'Display', 1);
Step 1: Compression is mlsvd_rsi (compression ratio 0.00145243 < 0.5):
| Step 1a: Structured tensor expanded to full tensor (prod(getsize(T)) <= 1e+06).
| Step 1b: mlsvd_rsi on full tensor... relative error = 5.62399e-16.
Step 2: Initialization is cpd_rnd (requested by user)... relative error = 0.999409.
Step 3: Algorithm is cpd_minf on the compressed tensor... iterations = 73,
relative error = 5.1671e-07.
Step 4: Refinement is cpd_minf on the uncompressed tensor:
| Step 4a: Detection of structure skipped (hankel structure already known).
| Step 4b: cpd_minf... iterations = 7, relative error = 1.69504e-08.
Computing the error¶
The residual between a tensor \(\ten{T}\) and its CPD approximation defined by factor matrices \(\mat{\hat{U}}^{(n)}\) can be computed with
U = cpd_rnd([10 11 12], 5);
T = cpdgen(U);
Uhat = cpd(noisy(T, 60), 5);
res = cpdres(T,Uhat);
If the tensor is dense, then the result is equivalent to cpdgen(Uhat)-T. The
relative error between the tensor and its CPD approximation can then be computed
as
relerr = frob(cpdres(T,Uhat))/frob(T); % or alternatively by
relerr = frobcpdres(T, Uhat)/frob(T);
The latter method also handles efficiently represented tensors.
One can also consider the relative error between the factor matrices
\(\mat{U}^{(n)}\) that generated \(\ten{T}\) and their approximations
\(\mat{\hat{U}}^{(n)}\) computed by cpd. Due to the permutation and
scaling indeterminacies of the CPD, the columns of \(\mat{\hat{U}}^{(n)}\)
need to be permuted and scaled to match the columns of \(\mat{U}^{(n)}\) as
well as possible. The function cpderr takes care of these indeterminacies
and computes the relative error between the given two sets of factor matrices.
I.e.,
relerr = cpderr(U,Uhat);
returns a vector in which the \(n\)th entry is the relative error between \(\mat{U}^{(n)}\) and \(\mat{\hat{U}}^{(n)}\). This method is also applicable when \(\mat{\hat{U}}^{(n)}\) is an under- or overfactoring of the solution, meaning \(\mat{\hat{U}}^{(n)}\) comprises fewer or more rank-one terms than the tensor’s rank, respectively. In the underfactoring case, \(\mat{\hat{U}}^{(n)}\) is padded with zero-columns, and in the overfactoring case only the columns in \(\mat{\hat{U}}^{(n)}\) that best match those in \(\mat{U}^{(n)}\) are kept. The command also returns the permutation matrix, the \(N\) scaling matrices and the permuted and scaled factor matrices \(\mat{\hat{U}}^{(n)}_{\text{ps}}\):
[relerr,P,D,Uhatps] = cpderr(U,Uhat);
See the help information for more details.
Choosing the number of rank-one terms \(R\)¶
Determining the rank \(R\) of a tensor \(\ten{T}\) is often a difficult
problem. In many cases domain knowledge or trial-and-error are used to find the
correct rank. A useful lower bound can be found using the multilinear singular
values. A tool which can sometimes help choosing \(R\) is the rankest
method. Running rankest(T) on a dense, sparse, incomplete or structured
tensor \(\ten{T}\) plots an L-curve which represents the balance between the
relative error of the CPD and the number of rank-one terms \(R\). The
following example applies rankest on the amino acids dataset [16]:
url = 'http://www.models.life.ku.dk/go-engine?filename=amino.mat';
urlwrite(url,'amino.mat'); % Download amino.mat in this directory.
load amino X;
rankest(X);
The resulting figure is shown in Figure 29. The algorithm computes
the CPD of the given tensor for various values of \(R\), starting at the
smallest integer for which the lower bound on the relative error (displayed as a
solid blue line) is smaller than the MaxRelErr option. The lower bound is
based on the truncation error of the tensor’s multilinear singular values
[17]. For incomplete and sparse tensors, this lower bound is not
available and the first value to be tried for \(R\) is \(1\). The number
of rank-one terms is increased until the relative error of the approximation is
less than MinRelErr option. It is recommended to set MaxRelErr higher
than the expected noise level and to set MinRelErr at a value near the noise
level and smaller than MaxRelErr. In a sense, the corner of the resulting
L-curve makes an optimal trade-off between accuracy and compression. The
rankest tool computes the number of rank-one terms \(R\) corresponding
to the L-curve corner and marks it on the plot with a square. This optimal
number of rank-one terms is also rankest‘s first output. By capturing it as
R = rankest(X), the L-curve is no longer plotted.
Overview of algorithms¶
The cpd method uses a variety of algorithms to compute the decomposition
using a multi-step initialization sequence. These algorithms can be called
separately as well. Below, an overview of the available algorithms is
given, as well as an overview of other convenient algorithms.
The following algorithms can be used to compute the canonical polyadic decomposition of dense, sparse, incomplete or efficiently represented tensors.
cpd(T, R)computes the CPD of a tensorTusing a multistep approach.cpd_nls(T, U)computes the CPD of a tensorTusing an nonlinear least squares type algorithm with initial guessU.cpd_minf(T, U)computes the CPD of a tensorTusing nonlinear unconstrained optimization with initial guessU.cpd_als(T, U)computes the CPD of a tensorTusing alternating least squares with initial guessU.cpd_rbs(T, U)computes the CPD of a tensorTusing randomized block sampling with initial guessUand is used for large-scale tensor decompositions [18].cpd_gevd(T, R)computes the CPD using the generalized eigenvalue decomposition [14].cpd_gevdonly accepts full and sparse tensors. For structured tensorscpd_gevd(ful(T), R)can be used.cpd_gevdoften provides a good initialization for optimization-based algorithms.cpd3_sd(T, U)computes the CPD of a third-order, dense tensorTusing simultaneous diagonalization with initial guessU[19].cpd3_sgsd(T, U)computes the CPD of a third-order, dense tensorTusing simultaneous generalized Schur decomposition with initial guessU[20].
The following line and plane search methods can be used in combination with the
optimization routines cpd_nls, cpd_minf and cpd_als (see
help cpd_xxx for more information):
cpd_elsuses exact line search.cpd_aelsuses approximated exact line search.cpd_lsbuses Bro’s line search method [16].cpd_epsuses plane search.
The following routines can be used for problem generation, error analysis and rank estimation.
cpd_rnd(size_tens, R)generates pseudorandom factors for a CPD.cpdgen(U)generates the full tensor from a given CPDU.cpderr(U0, Uest)computes the relative error for each factor matrix inU0andUestafter resolving the scaling and permutation indeterminacies.cpdres(T, U)computes the residualcpdgen(U) - T.frobcpdres(T, U)computes the Frobenius norm of the residualcpdgen(U) - T.crb_cpd(U, variance)computes the Cramér-Rao bound for a CPDUand a given noise variance [21][22][18].rankest(T)tries to estimate the rank of a tensorT.
Note
When using efficient representations of structured tensors, the expected
numerical precision is only half the machine precision. This is due to the
mathematical formulation implemented to exploit the structure. In most cases,
this is not a problem as the maximal attainable precision is already limited
due to noise and model errors. The effect of this reduced accuracy is only
visible in the very specific case when a solution accurate up to machine
precision can be found and is required. (This requires TolFun and
TolX to be eps^2 and eps, respectively.) An automatic solution
has not been implemented yet. For now, a solution is to use the structured
tensor T to compute a solution Ures accurate up to half the machine
precision, and then refine this solution using
cpd_nls(ful(T), Ures, 'TolFun', eps^2,'TolX', eps) for a few iterations.
(It can be useful to set MaxIter to 2 or 3.) This technique
requires only very few expensive iterations involving the full tensor.
Further reading¶
The algorithms outlined in this chapter can be used to compute an unconstrained CPD. In the structured data fusion (SDF) framework constraints can be imposed and coupled decompositions can be defined. See Structured data fusion for more details.
A number of demos illustrating the CPD are available. In the demo “Basic Use of Tensorlab” a beginner’s introduction to Tensorlab and CPD is given. The demos “Multidimensional Harmonic Retrieval”, “Using Basic Tensorlab Features for ICA” and “Using Advanced Tensorlab Features for ICA” show more practical examples of the use of a CPD in a signal processing context.
