forked from panisson/ntf-school
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathncp.py
784 lines (628 loc) · 24.6 KB
/
ncp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# Copyright (C) 2013 Istituto per l'Interscambio Scientifico I.S.I.
# You can contact us by email ([email protected]) or write to:
# ISI Foundation, Via Alassio 11/c, 10126 Torino, Italy.
#
# This work is licensed under a Creative Commons 4.0
# Attribution-NonCommercial-ShareAlike License
# You may obtain a copy of the License at
# http://creativecommons.org/licenses/by-nc-sa/4.0/
#
# This program was written by Andre Panisson <[email protected]> at
# the Data Science Lab of the ISI Foundation,
# and its development was partly supported by
# the EU FET project MULTIPLEX (grant number 317532).
#
'''
Nonnegative Tensor Factorization, based on the Matlab source code
available at Jingu Kim's ([email protected]) home page:
https://github.com/kimjingu/nonnegfac-matlab
https://github.com/kimjingu/nonnegfac-python
Requires the installation of Numpy and Scikit-Tensor
(https://github.com/mnick/scikit-tensor).
For examples, see main() function.
This code comes with no guarantee or warranty of any kind.
Created on Nov 2013
@author: Andre Panisson
@contact: [email protected]
@organization: ISI Foundation, Torino, Italy
With contributions of Tonmoy Saikia
'''
import numpy as np
from numpy import zeros, ones, diff, kron, tile, any, all, linalg
import numpy.linalg as nla
import time
from sktensor import ktensor
def find(condition):
"Return the indices where ravel(condition) is true"
res, = np.nonzero(np.ravel(condition))
return res
def solve(AtA, AtB):
try:
soln = nla.solve(AtA, AtB)
except np.linalg.LinAlgError:
soln = nla.lstsq(AtA, AtB)[0]
except Exception as e:
raise e
return soln
def normalEqComb(AtA, AtB, PassSet=None):
""" Solve many systems of linear equations using combinatorial grouping.
M. H. Van Benthem and M. R. Keenan, J. Chemometrics 2004; 18: 441-450
Parameters
----------
AtA : numpy.array, shape (n,n)
AtB : numpy.array, shape (n,k)
Returns
-------
Z : numpy.array, shape (n,k) - solution
"""
if AtB.size == 0:
Z = np.zeros([])
elif (PassSet == None) or np.all(PassSet):
Z = solve(AtA, AtB)
else:
Z = np.zeros(AtB.shape)
if PassSet.shape[1] == 1:
if np.any(PassSet):
cols = PassSet.nonzero()[0]
Z[cols] = solve(AtA[np.ix_(cols, cols)], AtB[cols])
else:
#
# Both _column_group_loop() and _column_group_recursive() work well.
# Based on preliminary testing,
# _column_group_loop() is slightly faster for tiny k(<10), but
# _column_group_recursive() is faster for large k's.
#
grps = _column_group_recursive(PassSet)
for gr in grps:
cols = PassSet[:, gr[0]].nonzero()[0]
if cols.size > 0:
ix1 = np.ix_(cols, gr)
ix2 = np.ix_(cols, cols)
#
# scipy.linalg.cho_solve can be used instead of numpy.linalg.solve.
# For small n(<200), numpy.linalg.solve appears faster, whereas
# for large n(>500), scipy.linalg.cho_solve appears faster.
# Usage example of scipy.linalg.cho_solve:
# Z[ix1] = sla.cho_solve(sla.cho_factor(AtA[ix2]),AtB[ix1])
#
Z[ix1] = solve(AtA[ix2], AtB[ix1])
return Z
def _column_group_recursive(B):
""" Given a binary matrix, find groups of the same columns
with a recursive strategy
Parameters
----------
B : numpy.array, True/False in each element
Returns
-------
A list of arrays - each array contain indices of columns that are the same.
"""
initial = np.arange(0, B.shape[1])
return [a for a in column_group_sub(B, 0, initial) if len(a) > 0]
def column_group_sub(B, i, cols):
vec = B[i][cols]
if len(cols) <= 1:
return [cols]
if i == (B.shape[0] - 1):
col_trues = cols[vec.nonzero()[0]]
col_falses = cols[(-vec).nonzero()[0]]
return [col_trues, col_falses]
else:
col_trues = cols[vec.nonzero()[0]]
col_falses = cols[(-vec).nonzero()[0]]
after = column_group_sub(B, i + 1, col_trues)
after.extend(column_group_sub(B, i + 1, col_falses))
return after
def nnlsm_activeset(A, B, overwrite=0, isInputProd=0, init=None):
"""
Nonnegativity Constrained Least Squares with Multiple Righthand Sides
using Active Set method
This function solves the following problem: given A and B, find X such that
minimize || AX-B ||_F^2 where X>=0 elementwise.
Reference:
Charles L. Lawson and Richard J. Hanson,
Solving Least Squares Problems,
Society for Industrial and Applied Mathematics, 1995
M. H. Van Benthem and M. R. Keenan,
Fast Algorithm for the Solution of Large-scale
Non-negativity-constrained Least Squares Problems,
J. Chemometrics 2004; 18: 441-450
Based on the Matlab version written by Jingu Kim ([email protected])
School of Computational Science and Engineering,
Georgia Institute of Technology
Parameters
----------
A : input matrix (m x n) (by default),
or A'*A (n x n) if isInputProd==1
B : input matrix (m x k) (by default),
or A'*B (n x k) if isInputProd==1
overwrite : (optional, default:0)
if turned on, unconstrained least squares solution is computed
in the beginning
isInputProd : (optional, default:0)
if turned on, use (A'*A,A'*B) as input instead of (A,B)
init : (optional) initial value for X
Returns
-------
X : the solution (n x k)
Y : A'*A*X - A'*B where X is the solution (n x k)
"""
if isInputProd:
AtA = A
AtB = B
else:
AtA = A.T.dot(A)
AtB = A.T.dot(B)
n, k = AtB.shape
MAX_ITER = n * 5
# set initial feasible solution
if overwrite:
X = normalEqComb(AtA, AtB)
PassSet = (X > 0).copy()
NotOptSet = any(X < 0)
elif init is not None:
X = init
X[X < 0] = 0
PassSet = (X > 0).copy()
NotOptSet = ones((1, k), dtype=np.bool)
else:
X = zeros((n, k))
PassSet = zeros((n, k), dtype=np.bool)
NotOptSet = ones((1, k), dtype=np.bool)
Y = zeros((n, k))
if (~NotOptSet).any():
Y[:, ~NotOptSet] = AtA.dot(X[:, ~NotOptSet]) - AtB[:, ~NotOptSet]
NotOptCols = find(NotOptSet)
bigIter = 0
while NotOptCols.shape[0] > 0:
bigIter = bigIter + 1
# set max_iter for ill-conditioned (numerically unstable) case
if ((MAX_ITER > 0) & (bigIter > MAX_ITER)):
break
Z = normalEqComb(AtA, AtB[:, NotOptCols], PassSet[:, NotOptCols])
Z[abs(Z) < 1e-12] = 0 # for numerical stability.
InfeaSubSet = Z < 0
InfeaSubCols = find(any(InfeaSubSet, axis=0))
FeaSubCols = find(all(~InfeaSubSet, axis=0))
if InfeaSubCols.shape[0] > 0: # for infeasible cols
ZInfea = Z[:, InfeaSubCols]
InfeaCols = NotOptCols[InfeaSubCols]
Alpha = zeros((n, InfeaSubCols.shape[0]))
Alpha[:] = np.inf
ij = np.argwhere(InfeaSubSet[:, InfeaSubCols])
i = ij[:, 0]
j = ij[:, 1]
InfeaSubIx = np.ravel_multi_index((i, j), Alpha.shape)
if InfeaCols.shape[0] == 1:
InfeaIx = np.ravel_multi_index((i,
InfeaCols * ones((len(j), 1),
dtype=int)),
(n, k))
else:
InfeaIx = np.ravel_multi_index((i, InfeaCols[j]), (n, k))
Alpha.ravel()[InfeaSubIx] = X.ravel()[InfeaIx] / \
(X.ravel()[InfeaIx] - ZInfea.ravel()[InfeaSubIx])
minVal, minIx = np.min(Alpha, axis=0), np.argmin(Alpha, axis=0)
Alpha[:, :] = kron(ones((n, 1)), minVal)
X[:, InfeaCols] = X[:, InfeaCols] + \
Alpha * (ZInfea - X[:, InfeaCols])
IxToActive = np.ravel_multi_index((minIx, InfeaCols), (n, k))
X.ravel()[IxToActive] = 0
PassSet.ravel()[IxToActive] = False
if FeaSubCols.shape[0] > 0: # for feasible cols
FeaCols = NotOptCols[FeaSubCols]
X[:, FeaCols] = Z[:, FeaSubCols]
Y[:, FeaCols] = AtA.dot(X[:, FeaCols]) - AtB[:, FeaCols]
Y[abs(Y) < 1e-12] = 0 # for numerical stability.
NotOptSubSet = (Y[:, FeaCols] < 0) & ~PassSet[:, FeaCols]
NewOptCols = FeaCols[all(~NotOptSubSet, axis=0)]
UpdateNotOptCols = FeaCols[any(NotOptSubSet, axis=0)]
if UpdateNotOptCols.shape[0] > 0:
minIx = np.argmin(Y[:, UpdateNotOptCols] * \
~PassSet[:, UpdateNotOptCols], axis=0)
idx = np.ravel_multi_index((minIx, UpdateNotOptCols), (n, k))
PassSet.ravel()[idx] = True
NotOptSet.T[NewOptCols] = False
NotOptCols = find(NotOptSet)
return X, Y
def nnlsm_blockpivot(A, B, isInputProd=0, init=None):
"""
Nonnegativity Constrained Least Squares with Multiple Righthand Sides
using Block Principal Pivoting method
This function solves the following problem: given A and B, find X such that
minimize || AX-B ||_F^2 where X>=0 elementwise.
Reference:
Jingu Kim and Haesun Park. Fast Nonnegative Matrix Factorization:
An Activeset-like Method and Comparisons.
SIAM Journal on Scientific Computing, 33(6), pp. 3261-3281, 2011.
Based on the Matlab version written by Jingu Kim ([email protected])
School of Computational Science and Engineering,
Georgia Institute of Technology
Parameters
----------
A : input matrix (m x n) (by default),
or A'*A (n x n) if isInputProd==1
B : input matrix (m x k) (by default),
or A'*B (n x k) if isInputProd==1
overwrite : (optional, default:0)
if turned on, unconstrained least squares solution is computed
in the beginning
isInputProd : (optional, default:0)
if turned on, use (A'*A,A'*B) as input instead of (A,B)
init : (optional) initial value for X
Returns
-------
X : the solution (n x k)
Y : A'*A*X - A'*B where X is the solution (n x k)
"""
if isInputProd:
AtA = A
AtB = B
else:
AtA = A.T.dot(A)
AtB = A.T.dot(B)
n, k = AtB.shape
MAX_BIG_ITER = n * 5
# set initial feasible solution
X = zeros((n, k))
if init is None:
Y = - AtB
PassiveSet = zeros((n, k), dtype=np.bool)
else:
PassiveSet = (init > 0).copy()
X = normalEqComb(AtA, AtB, PassiveSet)
Y = AtA.dot(X) - AtB
# parameters
pbar = 3
P = zeros((1, k))
P[:] = pbar
Ninf = zeros((1, k))
Ninf[:] = n + 1
NonOptSet = (Y < 0) & ~PassiveSet
InfeaSet = (X < 0) & PassiveSet
NotGood = (np.sum(NonOptSet, axis=0) + \
np.sum(InfeaSet, axis=0))[np.newaxis, :]
NotOptCols = NotGood > 0
bigIter = 0
while find(NotOptCols).shape[0] > 0:
bigIter = bigIter + 1
# set max_iter for ill-conditioned (numerically unstable) case
if ((MAX_BIG_ITER > 0) & (bigIter > MAX_BIG_ITER)):
break
Cols1 = NotOptCols & (NotGood < Ninf)
Cols2 = NotOptCols & (NotGood >= Ninf) & (P >= 1)
Cols3Ix = find(NotOptCols & ~Cols1 & ~Cols2)
if find(Cols1).shape[0] > 0:
P[Cols1] = pbar
NotGood[Cols1]
Ninf[Cols1] = NotGood[Cols1]
PassiveSet[NonOptSet & tile(Cols1, (n, 1))] = True
PassiveSet[InfeaSet & tile(Cols1, (n, 1))] = False
if find(Cols2).shape[0] > 0:
P[Cols2] = P[Cols2] - 1
PassiveSet[NonOptSet & tile(Cols2, (n, 1))] = True
PassiveSet[InfeaSet & tile(Cols2, (n, 1))] = False
if Cols3Ix.shape[0] > 0:
for i in range(Cols3Ix.shape[0]):
Ix = Cols3Ix[i]
toChange = np.max(find(NonOptSet[:, Ix] | InfeaSet[:, Ix]))
if PassiveSet[toChange, Ix]:
PassiveSet[toChange, Ix] = False
else:
PassiveSet[toChange, Ix] = True
Z = normalEqComb(AtA, AtB[:, NotOptCols.flatten()],
PassiveSet[:, NotOptCols.flatten()])
X[:, NotOptCols.flatten()] = Z[:]
X[abs(X) < 1e-12] = 0 # for numerical stability.
Y[:, NotOptCols.flatten()] = AtA.dot(X[:, NotOptCols.flatten()]) - \
AtB[:, NotOptCols.flatten()]
Y[abs(Y) < 1e-12] = 0 # for numerical stability.
# check optimality
NotOptMask = tile(NotOptCols, (n, 1))
NonOptSet = NotOptMask & (Y < 0) & ~PassiveSet
InfeaSet = NotOptMask & (X < 0) & PassiveSet
NotGood = (np.sum(NonOptSet, axis=0) +
np.sum(InfeaSet, axis=0))[np.newaxis, :]
NotOptCols = NotGood > 0
return X, Y
def getGradient(X, F, nWay, r):
grad = []
for k in range(nWay):
ways = range(nWay)
ways.remove(k)
XF = X.uttkrp(F, k)
# Compute the inner-product matrix
FF = ones((r, r))
for i in ways:
FF = FF * (F[i].T.dot(F[i]))
grad.append(F[k].dot(FF) - XF)
return grad
def getProjGradient(X, F, nWay, r):
pGrad = []
for k in range(nWay):
ways = range(nWay)
ways.remove(k)
XF = X.uttkrp(F, k)
# Compute the inner-product matrix
FF = ones((r, r))
for i in ways:
FF = FF * (F[i].T.dot(F[i]))
grad = F[k].dot(FF) - XF
grad[~((grad < 0) | (F[k] > 0))] = 0.
pGrad.append(grad)
return pGrad
class anls_asgroup(object):
def initializer(self, X, F, nWay, orderWays, r):
F[orderWays[0]] = zeros(F[orderWays[0]].shape)
FF = []
for k in range(nWay):
FF.append((F[k].T.dot(F[k])))
return F, FF
def iterSolver(self, X, F, FF_init, nWay, r, orderWays):
# solve NNLS problems for each factor
for k in range(nWay):
curWay = orderWays[k]
ways = range(nWay)
ways.remove(curWay)
XF = X.uttkrp(F, curWay)
# Compute the inner-product matrix
FF = ones((r, r))
for i in ways:
FF = FF * FF_init[i] # (F[i].T.dot(F[i]))
ow = 0
Fthis, temp = nnlsm_activeset(FF, XF.T, ow, 1, F[curWay].T)
F[curWay] = Fthis.T
FF_init[curWay] = (F[curWay].T.dot(F[curWay]))
return F, FF_init
class anls_bpp(object):
def initializer(self, X, F, nWay, orderWays, r):
F[orderWays[0]] = zeros(F[orderWays[0]].shape)
FF = []
for k in range(nWay):
FF.append((F[k].T.dot(F[k])))
return F, FF
def iterSolver(self, X, F, FF_init, nWay, r, orderWays):
for k in range(nWay):
curWay = orderWays[k]
ways = range(nWay)
ways.remove(curWay)
XF = X.uttkrp(F, curWay)
# Compute the inner-product matrix
FF = ones((r, r))
for i in ways:
FF = FF * FF_init[i] # (F[i].T.dot(F[i]))
Fthis, temp = nnlsm_blockpivot(FF, XF.T, 1, F[curWay].T)
F[curWay] = Fthis.T
FF_init[curWay] = (F[curWay].T.dot(F[curWay]))
return F, FF_init
class mu(object):
def initializer(self, X, F, nWay, orderWays, r):
FF = []
for k in range(nWay):
FF.append((F[k].T.dot(F[k])))
return F, FF
def iterSolver(self, X, F, FF_init, nWay, r, orderWays):
eps = 1e-16
for k in range(nWay):
curWay = orderWays[k]
ways = range(nWay)
ways.remove(curWay)
XF = X.uttkrp(F, curWay)
FF = ones((r, r))
for i in ways:
FF = FF * FF_init[i]
F[curWay] = F[curWay]*XF/(F[curWay].dot(FF) + eps)
FF_init[curWay] = (F[curWay].T.dot(F[curWay]))
return F, FF_init
class hals(object):
def initializer(self, X, F, nWay, orderWays, r):
d = ones((1, r))
for k in range(nWay-1):
curWay = orderWays[k]
norm2 = np.sqrt(np.sum(F[curWay]**2, axis=0))
F[curWay] = F[curWay]/kron(ones((F[curWay].shape[0],1)),norm2) # repmat(a,2,3) -- kron(ones(2,3),a)
d = d*norm2
curWay = orderWays[-1]
F[curWay] = F[curWay]*kron(ones((F[curWay].shape[0],1)),d)
FF = []
for k in range(nWay):
FF.append((F[k].T.dot(F[k])))
return F, FF
def iterSolver(self, X, F, FF_init, nWay, r, orderWays):
eps = 1e-16
d = np.sum(F[orderWays[-1]]**2, axis=0)
for k in range(nWay):
curWay = orderWays[k]
ways = range(nWay)
ways.remove(curWay)
XF = X.uttkrp(F, curWay)
FF = ones((r, r))
for i in ways:
FF = FF * FF_init[i]
if k < nWay-1:
for j in range(r):
F[curWay][:,j] = np.maximum(d[j]*F[curWay][:,j] + XF[:,j]- F[curWay].dot(FF[:,j]), eps)
F[curWay][:,j] = F[curWay][:,j]/np.linalg.norm(F[curWay][:,j])
else:
for j in range(r):
F[curWay][:,j] = np.maximum(F[curWay][:,j] + XF[:,j] - F[curWay].dot(FF[:,j]), eps)
FF_init[curWay] = (F[curWay].T.dot(F[curWay]))
return F, FF_init
def getStopCriterion(pGrad, nWay, nr_grad_all):
retVal = np.sum(np.linalg.norm(pGrad[i], 'fro') ** 2
for i in range(nWay))
return np.sqrt(retVal) / nr_grad_all
def getRelError(X, F_kten, nWay, nr_X):
error = nr_X ** 2 + F_kten.norm() ** 2 - 2 * F_kten.innerprod(X)
return np.sqrt(max(error, 0)) / nr_X
def nonnegative_tensor_factorization(X, r, method='anls_bpp',
tol=1e-4, stop_criterion=1,
min_iter=20, max_iter=200, max_time=1e6,
init=None, orderWays=None):
"""
Nonnegative Tensor Factorization (Canonical Decomposition / PARAFAC)
Based on the Matlab version written by Jingu Kim ([email protected])
School of Computational Science and Engineering,
Georgia Institute of Technology
This software implements nonnegativity-constrained low-rank approximation
of tensors in PARAFAC model. Assuming that a k-way tensor X and target rank
r are given, this software seeks F1, ... , Fk by solving the following
problem:
minimize
|| X- sum_(j=1)^r (F1_j o F2_j o ... o Fk_j) ||_F^2 +
G(F1, ... , Fk) + H(F1, ..., Fk)
where
G(F1, ... , Fk) = sum_(i=1)^k ( alpha_i * ||Fi||_F^2 ),
H(F1, ... , Fk) = sum_(i=1)^k ( beta_i sum_(j=1)^n || Fi_j ||_1^2 ).
such that
Fi >= 0 for all i.
To use this software, it is necessary to first install scikit_tensor.
Reference:
Fast Nonnegative Tensor Factorization with an Active-set-like Method.
Jingu Kim and Haesun Park.
In High-Performance Scientific Computing: Algorithms and Applications,
Springer, 2012, pp. 311-326.
Parameters
----------
X : tensor' object of scikit_tensor
Input data tensor.
r : int
Target low-rank.
method : string, optional
Algorithm for solving NMF. One of the following values:
'anls_bpp' 'anls_asgroup' 'hals' 'mu'
See above paper (and references therein) for the details
of these algorithms.
Default is 'anls_bpp'.
tol : float, optional
Stopping tolerance. Default is 1e-4.
If you want to obtain a more accurate solution,
decrease TOL and increase MAX_ITER at the same time.
min_iter : int, optional
Minimum number of iterations. Default is 20.
max_iter : int, optional
Maximum number of iterations. Default is 200.
init : A cell array that contains initial values for factors Fi.
See examples to learn how to set.
Returns
-------
F : a 'ktensor' object that represent a factorized form of a tensor.
Examples
--------
F = nonnegative_tensor_factorization(X, 5)
F = nonnegative_tensor_factorization(X, 10, tol=1e-3)
F = nonnegative_tensor_factorization(X, 7, init=Finit, tol=1e-5)
"""
nWay = len(X.shape)
if orderWays is None:
orderWays = np.arange(nWay)
# set initial values
if init is not None:
F_cell = init
else:
Finit = [np.random.rand(X.shape[i], r) for i in range(nWay)]
F_cell = Finit
grad = getGradient(X, F_cell, nWay, r)
nr_X = X.norm()
nr_grad_all = np.sqrt(np.sum(np.linalg.norm(grad[i], 'fro') ** 2
for i in range(nWay)))
if method == "anls_bpp":
method = anls_bpp()
elif method == "anls_asgroup":
method = anls_asgroup()
elif method == "mu":
method = mu()
elif method == "hals":
method = hals()
else:
raise Exception("Unknown method")
# Execute initializer
F_cell, FF_init = method.initializer(X, F_cell, nWay, orderWays, r)
tStart = time.time()
if stop_criterion == 2:
F_kten = ktensor(F_cell)
rel_Error = getRelError(X, ktensor(F_cell), nWay, nr_X)
if stop_criterion == 1:
pGrad = getProjGradient(X, F_cell, nWay, r)
SC_PGRAD = getStopCriterion(pGrad, nWay, nr_grad_all)
# main iterations
for iteration in range(max_iter):
cntu = True
F_cell, FF_init = method.iterSolver(X, F_cell,
FF_init, nWay, r, orderWays)
F_kten = ktensor(F_cell)
if iteration >= min_iter:
if time.time() - tStart > max_time:
cntu = False
else:
if stop_criterion == 1:
pGrad = getProjGradient(X, F_cell, nWay, r)
SC_PGRAD = getStopCriterion(pGrad, nWay, nr_grad_all)
if SC_PGRAD < tol:
cntu = False
elif stop_criterion == 2:
prev_rel_Error = rel_Error
rel_Error = getRelError(X, F_kten, nWay, nr_X)
SC_DIFF = np.abs(prev_rel_Error - rel_Error)
if SC_DIFF < tol:
cntu = False
else:
rel_Error = getRelError(X, F_kten, nWay, nr_X)
if rel_Error < 1:
cntu = False
if not cntu:
break
return F_kten
def main():
from numpy.random import rand
# -----------------------------------------------
# Creating a synthetic 4th-order tensor
# -----------------------------------------------
N1 = 20
N2 = 25
N3 = 30
N4 = 30
R = 10
# Random initialization
np.random.seed(42)
A_org = np.random.rand(N1, R)
A_org[A_org < 0.4] = 0
B_org = rand(N2, R)
B_org[B_org < 0.4] = 0
C_org = rand(N3, R)
C_org[C_org < 0.4] = 0
D_org = rand(N4, R)
D_org[D_org < 0.4] = 0
X_ks = ktensor([A_org, B_org, C_org, D_org])
X = X_ks.totensor()
# -----------------------------------------------
# Tentative initial values
# -----------------------------------------------
A0 = np.random.rand(N1, R)
B0 = np.random.rand(N2, R)
C0 = np.random.rand(N3, R)
D0 = np.random.rand(N4, R)
Finit = [A0, B0, C0, D0]
# -----------------------------------------------
# Uncomment only one of the following
# -----------------------------------------------
X_approx_ks = nonnegative_tensor_factorization(X, R)
# X_approx_ks = nonnegative_tensor_factorization(X, R,
# min_iter=5, max_iter=20)
#
# X_approx_ks = nonnegative_tensor_factorization(X, R,
# method='anls_asgroup')
#
# X_approx_ks = nonnegative_tensor_factorization(X, R,
# tol=1e-7, max_iter=300)
#
# X_approx_ks = nonnegative_tensor_factorization(X, R,
# init=Finit)
# -----------------------------------------------
# Approximation Error
# -----------------------------------------------
X_approx = X_approx_ks.totensor()
X_err = (X - X_approx).norm() / X.norm()
print "Error:", X_err
if __name__ == "__main__":
main()