|
| 1 | + |
| 2 | +from numbers import Real |
| 3 | +import numpy as np |
| 4 | +from pyttb.ttensor import ttensor |
| 5 | + |
| 6 | +def tucker_als(tensor, rank, stoptol=1e-4, maxiters=1000, dimorder=None, |
| 7 | + init='random', printitn=1): |
| 8 | + """ |
| 9 | + Compute Tucker decomposition with alternating least squares |
| 10 | +
|
| 11 | + Parameters |
| 12 | + ---------- |
| 13 | + tensor: :class:`pyttb.tensor` |
| 14 | + rank: int, list[int] |
| 15 | + Rank of the decomposition(s) |
| 16 | + stoptol: float |
| 17 | + Tolerance used for termination - when the change in the fitness function in successive iterations drops |
| 18 | + below this value, the iterations terminate (default: 1e-4) |
| 19 | + dimorder: list |
| 20 | + Order to loop through dimensions (default: [range(tensor.ndims)]) |
| 21 | + maxiters: int |
| 22 | + Maximum number of iterations (default: 1000) |
| 23 | + init: str or list[np.ndarray] |
| 24 | + Initial guess (default: "random") |
| 25 | +
|
| 26 | + * "random": initialize using a :class:`pyttb.ttensor` with values chosen from a Normal distribution with mean 1 and standard deviation 0 |
| 27 | + * "nvecs": initialize factor matrices of a :class:`pyttb.ttensor` using the eigenvectors of the outer product of the matricized input tensor |
| 28 | + * :class:`pyttb.ttensor`: initialize using a specific :class:`pyttb.ttensor` as input - must be the same shape as the input tensor and have the same rank as the input rank |
| 29 | +
|
| 30 | + printitn: int |
| 31 | + Number of iterations to perform before printing iteration status - 0 for no status printing (default: 1) |
| 32 | +
|
| 33 | + Returns |
| 34 | + ------- |
| 35 | + M: :class:`pyttb.ttensor` |
| 36 | + Resulting ttensor from Tucker-ALS factorization |
| 37 | + Minit: :class:`pyttb.ttensor` |
| 38 | + Initial guess |
| 39 | + output: dict |
| 40 | + Information about the computation. Dictionary keys: |
| 41 | +
|
| 42 | + * `params` : tuple of (stoptol, maxiters, printitn, dimorder) |
| 43 | + * `iters`: number of iterations performed |
| 44 | + * `normresidual`: norm of the difference between the input tensor and ktensor factorization |
| 45 | + * `fit`: value of the fitness function (fraction of tensor data explained by the model) |
| 46 | +
|
| 47 | + """ |
| 48 | + N = tensor.ndims |
| 49 | + normX = tensor.norm() |
| 50 | + |
| 51 | + # TODO: These argument checks look common with CP-ALS factor out |
| 52 | + if not isinstance(stoptol, Real): |
| 53 | + raise ValueError(f"stoptol must be a real valued scalar but received: {stoptol}") |
| 54 | + if not isinstance(maxiters, Real) or maxiters < 0: |
| 55 | + raise ValueError(f"maxiters must be a non-negative real valued scalar but received: {maxiters}") |
| 56 | + if not isinstance(printitn, Real): |
| 57 | + raise ValueError(f"printitn must be a real valued scalar but received: {printitn}") |
| 58 | + |
| 59 | + if isinstance(rank, Real) or len(rank) == 1: |
| 60 | + rank = rank * np.ones(N, dtype=int) |
| 61 | + |
| 62 | + # Set up dimorder if not specified |
| 63 | + if not dimorder: |
| 64 | + dimorder = list(range(N)) |
| 65 | + else: |
| 66 | + if not isinstance(dimorder, list): |
| 67 | + raise ValueError("Dimorder must be a list") |
| 68 | + elif tuple(range(N)) != tuple(sorted(dimorder)): |
| 69 | + raise ValueError("Dimorder must be a list or permutation of range(tensor.ndims)") |
| 70 | + |
| 71 | + if isinstance(init, list): |
| 72 | + Uinit = init |
| 73 | + if len(init) != N: |
| 74 | + raise ValueError(f"Init needs to be of length tensor.ndim (which was {N}) but only got length {len(init)}.") |
| 75 | + for n in dimorder[1::]: |
| 76 | + correct_shape = (tensor.shape[n], rank[n]) |
| 77 | + if Uinit[n].shape != correct_shape: |
| 78 | + raise ValueError( |
| 79 | + f"Init factor {n} had incorrect shape. Expected {correct_shape} but got {Uinit[n].shape}" |
| 80 | + ) |
| 81 | + elif isinstance(init, str) and init.lower() == 'random': |
| 82 | + Uinit = [None] * N |
| 83 | + # Observe that we don't need to calculate an initial guess for the |
| 84 | + # first index in dimorder because that will be solved for in the first |
| 85 | + # inner iteration. |
| 86 | + for n in range(1, N): |
| 87 | + Uinit[n] = np.random.uniform(0, 1, (tensor.shape[n], rank[n])) |
| 88 | + elif isinstance(init, str) and init.lower() in ('nvecs', 'eigs'): |
| 89 | + # Compute an orthonormal basis for the dominant |
| 90 | + # Rn-dimensional left singular subspace of |
| 91 | + # X_(n) (0 <= n < N). |
| 92 | + Uinit = [None] * N |
| 93 | + for n in dimorder[1::]: |
| 94 | + print(f" Computing {rank[n]} leading e-vector for factor {n}.\n") |
| 95 | + Uinit[n] = tensor.nvecs(n, rank[n]) |
| 96 | + else: |
| 97 | + raise ValueError(f"The selected initialization method is not supported. Provided: {init}") |
| 98 | + |
| 99 | + # Set up for iterations - initializing U and the fit. |
| 100 | + U = Uinit.copy() |
| 101 | + fit = 0 |
| 102 | + |
| 103 | + if printitn > 0: |
| 104 | + print("\nTucker Alternating Least-Squares:\n") |
| 105 | + |
| 106 | + # Main loop: Iterate until convergence |
| 107 | + for iter in range(maxiters): |
| 108 | + fitold = fit |
| 109 | + |
| 110 | + # Iterate over all N modes of the tensor |
| 111 | + for n in dimorder: |
| 112 | + if n == 0: # TODO proposal to change ttm to include_dims and exclude_dims to resolve -0 ambiguity |
| 113 | + dims = np.arange(1, tensor.ndims) |
| 114 | + Utilde = tensor.ttm(U, dims, True) |
| 115 | + else: |
| 116 | + Utilde = tensor.ttm(U, -n, True) |
| 117 | + |
| 118 | + # Maximize norm(Utilde x_n W') wrt W and |
| 119 | + # maintain orthonormality of W |
| 120 | + U[n] = Utilde.nvecs(n, rank[n]) |
| 121 | + |
| 122 | + # Assemble the current approximation |
| 123 | + core = Utilde.ttm(U, n, True) |
| 124 | + |
| 125 | + # Compute fit |
| 126 | + # TODO this abs is missing from MATLAB, but I get negative numbers for trivial examples |
| 127 | + normresidual = np.sqrt(abs(normX**2 - core.norm()**2)) |
| 128 | + fit = 1 - (normresidual / normX) # fraction explained by model |
| 129 | + fitchange = abs(fitold - fit) |
| 130 | + |
| 131 | + if iter % printitn == 0: |
| 132 | + print(f" NormX: {normX} Core norm: {core.norm()}") |
| 133 | + print(f" Iter {iter}: fit = {fit:e} fitdelta = {fitchange:7.1e}\n") |
| 134 | + |
| 135 | + # Check for convergence |
| 136 | + if fitchange < stoptol: |
| 137 | + break |
| 138 | + |
| 139 | + solution = ttensor.from_data(core, U) |
| 140 | + |
| 141 | + output = {} |
| 142 | + output['params'] = (stoptol, maxiters, printitn, dimorder) |
| 143 | + output['iters'] = iter |
| 144 | + output['normresidual'] = normresidual |
| 145 | + output['fit'] = fit |
| 146 | + |
| 147 | + return solution, Uinit, output |
0 commit comments