1+ import warnings
12import tensorly as tl
23from ..tenalg import khatri_rao
34from ..cp_tensor import CPTensor , validate_cp_rank , cp_to_tensor , cp_normalize
1011
1112
1213def coupled_matrix_tensor_3d_factorization (
13- tensor_3d , matrix , rank , init = "svd" , n_iter_max = 100 , normalize_factors = False
14+ tensor_3d ,
15+ matrix ,
16+ rank ,
17+ init = "svd" ,
18+ n_iter_max = 100 ,
19+ tol = 1e-6 ,
20+ normalize_factors = False ,
1421):
1522 """
1623 Calculates a coupled matrix and tensor factorization of 3rd order tensor and matrix which are
@@ -43,6 +50,10 @@ def coupled_matrix_tensor_3d_factorization(
4350 matrix that is coupled with tensor in first mode: Y = [[A, V]]
4451 rank : int
4552 rank for CP decomposition of X
53+ tol : float, optional
54+ (Default: 1e-6) Relative reconstruction error tolerance. The
55+ algorithm is considered to have found the global minimum when the
56+ reconstruction error is less than `tol`.
4657
4758 Returns
4859 -------
@@ -72,6 +83,11 @@ def coupled_matrix_tensor_3d_factorization(
7283
7384 # initialize values
7485 tensor_cp = initialize_cp (tensor_3d , rank , init = init )
86+ # the coupled factor should be initialized with the concatenated dataset
87+ coupled_unfold = tl .concatenate ((tl .unfold (tensor_3d , 0 ), matrix ), axis = 1 )
88+ coupled_init = initialize_cp (coupled_unfold , rank , init = init )
89+ tensor_cp .factors [0 ] = coupled_init .factors [0 ]
90+
7591 rec_errors = []
7692
7793 # alternating least squares
@@ -81,7 +97,8 @@ def coupled_matrix_tensor_3d_factorization(
8197 V = tl .transpose (tl .lstsq (tensor_cp .factors [0 ], matrix )[0 ])
8298
8399 # Loop over modes of the tensor
84- for ii in range (tl .ndim (tensor_3d )):
100+ # We want to solve for mode 0 last, since the coupled factor matrix is most influential and SVD gave us a good approximation
101+ for ii in reversed (range (tl .ndim (tensor_3d ))):
85102 kr = khatri_rao (tensor_cp .factors , skip_matrix = ii )
86103 unfolded = tl .unfold (tensor_3d , ii )
87104
@@ -100,12 +117,16 @@ def coupled_matrix_tensor_3d_factorization(
100117 )
101118
102119 if iteration > 0 and (
103- tl .abs (error_new - error_old ) / error_old <= 1e-8 or error_new < 1e-5
120+ tl .abs (error_new - error_old ) / error_old <= tol or error_new < tol
104121 ):
105122 break
123+
106124 error_old = error_new
107125 rec_errors .append (error_new )
108126
127+ if iteration == n_iter_max - 1 :
128+ warnings .warn ("Reached maximum iteration number without convergance." )
129+
109130 matrix_pred = CPTensor ((None , [tensor_cp .factors [0 ], V ]))
110131
111132 if normalize_factors :
0 commit comments