9
9
10
10
11
11
def cp_als (
12
- tensor ,
12
+ input_tensor ,
13
13
rank ,
14
14
stoptol = 1e-4 ,
15
15
maxiters = 1000 ,
@@ -114,8 +114,8 @@ def cp_als(
114
114
"""
115
115
116
116
# Extract number of dimensions and norm of tensor
117
- N = tensor .ndims
118
- normX = tensor .norm ()
117
+ N = input_tensor .ndims
118
+ normX = input_tensor .norm ()
119
119
120
120
# Set up dimorder if not specified
121
121
if not dimorder :
@@ -139,17 +139,19 @@ def cp_als(
139
139
init .ncomponents == rank
140
140
), "Initial guess does not have {} components" .format (rank )
141
141
for n in dimorder :
142
- if init .factor_matrices [n ].shape != (tensor .shape [n ], rank ):
142
+ if init .factor_matrices [n ].shape != (input_tensor .shape [n ], rank ):
143
143
assert False , "Mode {} of the initial guess is the wrong size" .format (n )
144
144
elif isinstance (init , str ) and init .lower () == "random" :
145
145
factor_matrices = []
146
146
for n in range (N ):
147
- factor_matrices .append (np .random .uniform (0 , 1 , (tensor .shape [n ], rank )))
147
+ factor_matrices .append (
148
+ np .random .uniform (0 , 1 , (input_tensor .shape [n ], rank ))
149
+ )
148
150
init = ttb .ktensor .from_factor_matrices (factor_matrices )
149
151
elif isinstance (init , str ) and init .lower () == "nvecs" :
150
152
factor_matrices = []
151
153
for n in range (N ):
152
- factor_matrices .append (tensor .nvecs (n , rank ))
154
+ factor_matrices .append (input_tensor .nvecs (n , rank ))
153
155
init = ttb .ktensor .from_factor_matrices (factor_matrices )
154
156
else :
155
157
assert False , "The selected initialization method is not supported"
@@ -159,7 +161,7 @@ def cp_als(
159
161
fit = 0
160
162
161
163
# Store the last MTTKRP result to accelerate fitness computation
162
- U_mttkrp = np .zeros ((tensor .shape [dimorder [- 1 ]], rank ))
164
+ U_mttkrp = np .zeros ((input_tensor .shape [dimorder [- 1 ]], rank ))
163
165
164
166
if printitn > 0 :
165
167
print ("CP_ALS:" )
@@ -176,7 +178,7 @@ def cp_als(
176
178
# Iterate over all N modes of the tensor
177
179
for n in dimorder :
178
180
# Calculate Unew = X_(n) * khatrirao(all U except n, 'r').
179
- Unew = tensor .mttkrp (U , n )
181
+ Unew = input_tensor .mttkrp (U , n )
180
182
181
183
# Save the last MTTKRP result for fitness check.
182
184
if n == dimorder [- 1 ]:
@@ -245,11 +247,11 @@ def cp_als(
245
247
246
248
if printitn > 0 :
247
249
if normX == 0 :
248
- normresidual = M .norm () ** 2 - 2 * tensor .innerprod (M )
250
+ normresidual = M .norm () ** 2 - 2 * input_tensor .innerprod (M )
249
251
fit = normresidual
250
252
else :
251
253
normresidual = np .sqrt (
252
- np .abs (normX ** 2 + M .norm () ** 2 - 2 * tensor .innerprod (M ))
254
+ np .abs (normX ** 2 + M .norm () ** 2 - 2 * input_tensor .innerprod (M ))
253
255
)
254
256
fit = 1 - (normresidual / normX ) # fraction explained by model
255
257
print (f" Final f = { fit :e} " )
0 commit comments